如何在 Strapi 上将默认日期值设置为今天

问题描述 投票:0回答:2

我正在寻找一种在 Strapi 上将默认日期字段值设置为今天的方法,但我没有找到如何执行此操作。过了一会儿,我成功了。以下是分步教程。

javascript date strapi autofill
2个回答
0
投票

第 1 步:

在 Content-Type Builder 的日期字段中启用默认值(该值不相关)


第 2 步:

创建一个 JavaScript 模块(不要忘记将“your-content-type-name”更改为您的内容类型名称):

./src/api/your-content-type-name/content-types/your-content-type-name/auto-today.mjs

console.log(
  "\x1b[102m\x1b[97m\x1b[1m\x1b[3m%s\x1b[0m",
  "auto-today module is on!"
);

// Import "schedule" (for scheduled execution)
import schedule from "node-schedule";

// Import Node.js File System module
import fs from "fs";

// Scheduling of daily execution at midnight
let scheduleExec = schedule.scheduleJob("0 0 * * *", () => {
  // Get and store date, for most locales formats
  // (to be adapted for more uncommon locales formats)
  const date = new Date()
    .toLocaleString({
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    })
    .slice(0, 10)
    .replaceAll(/([./])/g, " ")
    .split(" ")
    .reverse()
    .join()
    .replaceAll(",", "-");

  // Read schema.json file
  fs.readFile(
    "./src/api/article/content-types/article/schema.json",
    function (err, data) {
      // Check for errors
      if (err) throw err;

      // Store schema.json a JavaScript object
      const schema = JSON.parse(data);

      // Remplace default date by today date
      schema.attributes.date.default = date;

      // Converting new schema.json JavaScript object to JSON object
      const newSchema = JSON.stringify(schema);

      // Remplace schema.json content by new content
      fs.writeFile(
        "./src/api/article/content-types/article/schema.json",
        newSchema,
        (err) => {
          // Error checking
          if (err) throw err;
          console.log("schema.json updated");
        }
      );
    }
  );
});


第 3 步:

更新 package.json 中的

develop
行(像以前一样,不要忘记替换“your-content-type-name”):

./backend/package.json

"auto-today": "node ./src/api/article/content-types/article/auto-today.mjs"


如何使用?

您只需在运行

auto-today
的同时运行
develop
即可。每天午夜,脚本都会再次执行。


0
投票

抱歉,我首先以为您想在创建或更新时设置默认值,但后来看到您想在给定时间执行此操作。

对于任何在这里绊倒并想知道如何在创建/更新时执行此操作的人,我会使用生命周期挂钩来完成。 日期字段的默认值是必需的,但可以是任何日期。在您的内容类型中创建一个lifecycles.js:

// src/api/<your-type>/content-types/<your-type>/lifecycles.js
module.exports = {
    // or beforeUpdate(event) {
    beforeCreate(event) {
        const {data} = event.params;
        // dateField is your datefield
        data.dateField = new Date();
    }
}

仅此而已:)

© www.soinside.com 2019 - 2024. All rights reserved.