Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a non-user-editable field to a content type in Strapi?

Tags:

strapi

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.

like image 805
TheLearner Avatar asked Mar 23 '19 10:03

TheLearner


1 Answers

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;
  }
},
like image 84
Jim LAURIE Avatar answered Sep 26 '22 10:09

Jim LAURIE