[英]How set default date value to today on Strapi
I was searching for a way to set the default date field value to today on Strapi, and I didn't found how to do this.我正在寻找一种在 Strapi 上将默认日期字段值设置为今天的方法,但我没有找到如何执行此操作。 After a while, I succeeded.一段时间后,我成功了。 Below is a step-by-step tutorial.下面是一个循序渐进的教程。
Enable default value in your date field of Content-Type Builder (the value is not relevant)在 Content-Type Builder 的日期字段中启用默认值(该值不相关)
Create a JavaScript Module (don't forget to change "your-content-type-name" by the name of your content-type):创建一个 JavaScript 模块(不要忘记用您的内容类型名称更改“您的内容类型名称”):
./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"); } ); } ); });
Update the line develop
in your package.json (as before don't forget to replace "your-content-type-name"):更新 package.json 中的develop
行(和以前一样不要忘记替换“your-content-type-name”):
./backend/package.json
"auto-today": "node./src/api/article/content-types/article/auto-today.mjs"
You just have to run auto-today
at the same time as you run develop
.您只需要在运行develop
的同时运行auto-today
。 Everyday at midnight, the script will be executed again.每天午夜,脚本将再次执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.