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.
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;
}
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With