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

半城伤御伤魂 提交于 2019-12-13 04:35:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!