MTAppjQuery を使ってコンテンツデータの日付フィールドのデフォルトを新規作成する日にする方法をご紹介します。
先ほど、MT Hub の質問コーナーで「日付フィールドのデフォルトを「今日」にしたい」という投稿をみました。
弊社のプラグイン「MTAppjQuery」をご利用いただいている場合に限りますが、簡単に実現できますので、その方法をご紹介します。
まず、user.js に以下の setCurrentDateTimeIfEmpty
という関数を定義します。
function setCurrentDateTimeIfEmpty(fieldName) {
if (!fieldName) {
alert('fieldNameは必須です');
}
const id = mtapp.getContentFieldIdByLabel(fieldName);
if (!id) {
return;
}
const dateField = document.querySelector(`[name="date-${id}"]`);
const timeField = document.querySelector(`[name="time-${id}"]`);
const now = new Date();
if (dateField && !dateField.value) {
dateField.value = now.toISOString().slice(0, 10);
}
if (timeField && !timeField.value) {
timeField.value = now.toTimeString().slice(0, 8);
}
}
そして「開催日」という名前の日付フィールドに適用したい場合は、user.js の上記の関数より下で以下のようにして実行します。
setCurrentDateTimeIfEmpty('開催日');
これで「開催日」というフィールドが空の時、つまり新規作成の時だけ、今日の日付がセットされるようになります。
なお、上記の関数は「日付と時刻」「日付」「時刻」の3つのタイプのフィールドに使うことができます。