【问题标题】:How to add a non-user-editable field to a content type in Strapi?如何向 Strapi 中的内容类型添加非用户可编辑的字段?
【发布时间】:2021-10-27 13:24:38
【问题描述】:

假设我有一个具有以下 4 个字段的 post 内容类型:

  • title(字符串)
  • content(字符串)
  • slug(字符串)
  • author(关系)

如何添加第 5 个字段,该字段的值取决于上述 4 个字段之一并且用户不可编辑?比如说,我想要一个wordCount 字段,其中content 字段中的单词数作为其值。为了合并此功能,我应该考虑探索什么文件?

P.S.:不管怎样,我使用 MongoDB Atlas 来满足我的数据库需求。

【问题讨论】:

    标签: strapi


    【解决方案1】:

    您必须在内容类型中创建 wordCount 属性。

    然后在左侧菜单的内容管理器链接中,您将能够自定义编辑/创建页面的视图。您可以在此处禁用删除页面中的字段。

    之后,您必须进入./api/post/models/Post.js 文件并更新以下函数。

    如果您使用的是 NoSQL 数据库 (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
        });
      }
    },
    

    如果您使用的是 SQL(SQLite、Postgres、MySQL)

    beforeSave: async (model, attrs, options) => {
      if (attrs.content) {
        attrs.wordCount = attrs.content.length;
      }
    },
    

    【讨论】:

      【解决方案2】:

      (对于 Strapi 3.x;NoSQL 和 SQL)

      1. 在内容类型上创建字数字段
      2. 配置内容类型的视图并单击字数字段 - 将“可编辑字段”设置为 false。
      3. 编辑./api/post/models/post.js
      'use strict';
      
      module.exports = {
        lifecycles: {
          async beforeCreate(data) {
            data.wordcount = data.content.match(/(\w+)/g).length;
          },
          async beforeUpdate(params, data) {
            data.wordcount = data.content.match(/(\w+)/g).length;
          },
        },
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        相关资源
        最近更新 更多