【问题标题】:Create widget select type field based on 3rd party API response根据 3rd 方 API 响应创建小部件选择类型字段
【发布时间】:2019-05-27 19:47:15
【问题描述】:

我们开始在 Apostrophe CMS 中基于 3rd 方 API 开发一个网站,但遇到了以下问题:

  • 我们需要一个具有选择功能的小部件(在管理端)。
  • 其中的选项是根据 API 响应生成的。
  • 管理员用户将在他/她设置小部件参数(服务器端)时选择一个选项。
  • 基于此选择,我们将调用另一个 API,并基于该响应生成一些 HTML(客户端;图像、文本等)

场景如下:管理员从列表中选择产品,在前端,我们将根据该选择显示信息。

const request = require( 'request-promise' );

module.exports = {
    extend: 'apostrophe-widgets',
    label: 'Preloaded list widget',
    addFields: [
        {
            label: 'Product',
            name: 'product',
            type: 'select',
            required: true,
            choices: "getChoices"
        }
    ],

    getChoices: async function( req )
    {
        const products = await request( {
            uri: "http://API_for_product_list",
            json: true
        } );

        var choiceList = [];
        for( idx = 0; idx < products.totalRecords; idx++ )
        {
            var option =
            {
                label: products.items[ idx ].label,
                value: products.items[ idx ].value
            };

            choiceList.push( option );
        }

        return choiceList;
    }
};


当我启动应用程序时,我收到以下警告: "小部件类型预加载列表,字段名称产品: 使用 showFields 时,field.choices 必须是数组” 并且列表显示为空。永远不会调用 getChoices 函数。

我错过了一些东西,但我不知道是什么。我们按照文档做了一切。

【问题讨论】:

    标签: apostrophe-cms


    【解决方案1】:

    您必须将 getChoices 函数附加到模块本身,以便以后可以引用它。

    const request = require('request-promise');
    
    module.exports = {
      extend: 'apostrophe-widgets',
      label: 'Preloaded list widget',
      addFields: [{
        label: 'Product',
        name: 'product',
        type: 'select',
        required: true,
        choices: 'getChoices'
      }],
      construct: function(self, options) {
        self.getChoices = async function (req) {
          const products = await request({
            uri: "http://API_for_product_list",
            json: true
          });
    
          var choiceList = [];
          for (idx = 0; idx < products.totalRecords; idx++) {
            var option = {
              label: products.items[idx].label,
              value: products.items[idx].value
            };
    
            choiceList.push(option);
          }
          return choiceList;
        }
      }
    };
    

    【讨论】:

    • 感谢您的建议,但结果是一样的。我也有同样的下降,产品选择是空的。
    • 我在一个新的沙箱中,全新安装了撇号 2.90.0,并且此代码有效。您在重组后重新启动了应用程序?你能安慰你返回的选择列表吗?正在检查与field.choices must be an array 相关的警告,以查看field.choices 是否是一个数组,这会让我认为你传递了其他东西。如果函数实际上没有运行,你应该得到更严重的错误self.apos.modules[field.moduleName][field.choices] is not a function。但是,无论我通过什么选择,我都无法让您的具体错误返回..
    • 是的,每次需要重启时我都会重启应用程序。问题是我有一个旧版本:2.89.0。更新后一切正常。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2020-01-12
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多