🗒️
Google Formのドロップダウンを動的に更新するときのメモ
目標
Google Formで動的に選択肢を更新させる
発端
Google Formでフォームを作成していたら日付入力がしにくいとクレームが来た😿
その時はGoogle Form標準の日付選択を使用していたが、iPhoneからだと数字を入力するのが嫌だったみたいです
要件
・当日以降の日付を入力できるようにする
・手で設定すると更新し忘れるので自動で更新したい
・やるなら無料でできるGoogleAppsScriptでやりたい
ソースコード
update.gs
function main() {
// 選択肢を作成する
const options = [];
for (let i = 0; i < 14; i++) {
options.push(getDayStr(i));
}
updateList("[更新したいフォームID]", "[項目タイトル]", options);
}
/**
* フォームを更新する
* @param {string} formId フォームID
* @param {string} targetTitle 毎日更新したいタイトル
* @param {string[]} options 選択肢リスト
*/
function updateList(formId, targetTitle, options) {
const form = FormApp.openById(formId);
const items = form.getItems();
for (const item of items) {
console.log(item.getTitle());
if (item.getTitle() !== targetTitle) continue;
const checkbox = item.asListItem();
checkbox.setChoiceValues(options)
}
}
/**
* n日後の日付をyyyy/MM/dd形式で返す
* @param {number} n
* @returns {string} n日後のyyyy/MM/dd形式の日付
*/
function getDayStr(n) {
const d = new Date();
d.setDate(d.getDate() + n);
return Utilities.formatDate(d, "JST", "yyyy/MM/dd");
}
/**
* @typedef ApiFormSubmittedEvent
* @property {{[key:string]: string[]}} namedValues
* @property {SpreadsheetApp.Range} range
* @property {string} triggerUid
* @property {string[]} values
*
* @see https://developers.google.com/apps-script/guides/triggers/events?hl=ja
*/
/**
* 文字列としてスプレッドシートに登録されるので先頭の'を削除する
* @param {ApiFormSubmittedEvent} e
*/
function onFormSubmit(e) {
const range = e.range;
const values = range.getDisplayValues().shift();
for (let i = 0; i < values.length; i++) {
const text = values[i];
if (!text) continue;
values[i] = text.replace(/^'/, "");
}
range.setValues([values]);
}
Discussion