问题
Say I have a post
content type with the following 4 fields:
title
(string)content
(string)slug
(string)author
(relationship)
How can I add a 5th field that depends on one of the above 4 fields for its value and isn't user-editable? Say, I wanted a wordCount
field with the number of words in the content
field as its value. What file should I consider exploring in order to incorporate this functionality?
P.S.: For what it's worth, I'm using MongoDB Atlas for my database needs.
回答1:
You will have to create your wordCount
attribute in your content type.
Then in the content manager link in the left menu, you will be able to custom the view of your edit/create page. Here you will be able to Disable or Remove the field from the page.
After that you will have to go in the ./api/post/models/Post.js
file and update following functions.
If you are using NoSQL database (Mongo)
beforeSave: async (model) => {
if (model.content) {
model.wordCount = model.content.length;
}
},
beforeUpdate: async (model) => {
if (model.getUpdate().content) {
model.update({
wordCount: model.getUpdate().content.length
});
}
},
If you are using SQL (SQLite, Postgres, MySQL)
beforeSave: async (model, attrs, options) => {
if (attrs.content) {
attrs.wordCount = attrs.content.length;
}
},
来源:https://stackoverflow.com/questions/55312969/how-to-add-a-non-user-editable-field-to-a-content-type-in-strapi