根据第三方API响应创建窗口小部件选择类型字段

时间:2019-05-27 07:57:59

标签: apostrophe-cms

我们开始基于第三方API在Apostrophe CMS中开发一个网站,并坚持以下问题:

  • 我们需要一个具有选择功能的小部件(在管理员端)。
  • 其中的选项是根据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函数。

我想念一些东西,但我不知道。我们根据文档进行了所有操作。

1 个答案:

答案 0 :(得分:0)

您必须将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;
    }
  }
};