LoginSignup
0
0

More than 3 years have passed since last update.

【kintone】日付フィールドAの経過日数を日付フィールドBへ登録する

Last updated at Posted at 2021-04-03

目次

・はじめに
・カスタマイズ概要
・テンプレート
・変数説明
・おわりに

はじめに

プログラミング初心者の方や、コードをいちいち書きたくないという方の為に、3つの変数の値だけ変更すれば即使えるテンプレートを作りました。

カスタマイズ概要

from(日付フィールドA)から14日後をto(日付フィールドB)へ反映させる。
尚且、to(日付フィールドB)は手動で更新も可能。

対応イベントは以下になります。
・レコード追加画面 表示後
・レコード一覧 インライン編集のフィールド値変更
・レコード編集画面 フィールド値変更
・レコード追加画面 フィールド値変更

①〜④までの変数の値を利用する用途やフィールドコードに合わせて変更してお使い下さい。

テンプレート

// #処理概要
// from(日付)から14日後をto(日付)に反映する。to(日付)は手動で更新も可能。
// #変数
//  ①reflectionDays: 加算する日数を指定する
//  ②from: 計算の元となるフィールド(フィールドコード)
//   ③to: 計算結果を反映するフィールド(フィールドコード)
(function() {
  'use strict';
  const reflectionDays = 14;
  const conf = [
    {
      from: '作業依頼日',
      to: '提出希望日'
    },
    {
      from: '提出希望日_2',
      to: '提出希望日_2'
    }
  ];

  // 値の変更の元となるフィールド(n)
  let targetFields = [];
  conf.forEach(field=>{
    targetFields.push(field.from);
  })

  const targetEvents = createEvents(targetFields)
  function createEvents(fields){
    var eventLists = [
      'app.record.create.show',
    ];
    fields.forEach(field=>{
      eventLists.push(`app.record.index.edit.change.${field}`);
      eventLists.push(`app.record.edit.change.${field}`);
      eventLists.push(`app.record.create.change.${field}`);
    })
    return eventLists;
  }
  kintone.events.on(targetEvents, function(event) {
    // イベントタイプを配列に分解
    const eventTypeArray = event.type.split(".");
    console.log(eventTypeArray);
    const eventType = eventTypeArray[eventTypeArray.length -2];
    // フィールドの変更イベントかそれ以外のイベントかを判定
    if(eventType == 'change') {
      // イベントタイプの一番後ろの文字(変更されたフィールド)を代入
      const changeField = eventTypeArray[eventTypeArray.length -1];
      // 変更元フィールドに対しての更新先フィールドをconfの中から探して代入
      const targetSetting = conf.find(setting => setting.from === changeField).to;
      // 計算処理。加算する場合は'add'。減算する場合は'subtract'
      let result = moment(event.record[changeField].value).add(reflectionDays, 'd').format('YYYY-MM-DD');
      // 計算結果を反映先フィールドへ更新
      event.record[targetSetting]['value'] = result;
      console.log('変更イベントの場合の計算結果:' + result);
    // その他のイベントの場合
    }else{
      // fromからtoへそれぞれ計算結果を反映する
      conf.forEach(fields => {
        let result = moment(event.record[fields.from].value).add(reflectionDays, 'd').format('YYYY-MM-DD');
        event.record[fields.to].value = result;
        console.log('変更イベント以外の場合の計算結果:' + result);
      })  
    }
    return event;
  });
})();

おわりに

この記事を上げた理由は以下になります。
1. kintoneのアプリ開発をしていると同じようなカスタマイズ案件に出会うことがあり、その度に、毎回調べてコードを書くのが面倒。(自分の為)
2. 変数だけ変えるだけで使えるようにテンプレート化してしまえば、コードを書けない方でも使えるじゃん! と。

コードは書けないけどkintoneの標準機能だけでは満足出来ない!という方の為になれば幸いです。
これからも、変数の値を変えるだけで使えるカスタマイズテンプレートを随時投稿していきたいと思います。
最後まで見てくださりありがとうございます!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0