2

I just learning Apostrophe CMS and I'm a bit confused as to how I can dynamically fill a select field. I've tried what the ApostropheCMS documentation suggests but there is no example on their site.

Apostrohpe CMS suggestion: First, set the choices option to the name of a method in your module. Pass a string, the name of the method — do not pass a function. Second, implement that function to take a single (req) argument and return an array of choices in the usual format. You may use an async function, or return a promise that will resolve to the array.

I've done this in many different ways but it is not working. I've tried calling self.testchoice, testchoice, I've tried calling the function var testchoice and self.testchoice.

My code is a mock of an eventual API call and is cut down from the entire apostrophe-piece that I am creating.

module.exports = {
  name: 'testtype',
  addFields: [
    {
      name: 'test_dynamic_select',
      type: 'select',
      choices: 'testchoice'
    }
  ],
  construct: function(self, options) {
    self.testchoice = function(req) {
       var testarray = [
          {
            label: 'London',
            value: 'london'
          },
          {
            label: 'Edinburgh',
            value: 'edinburgh'
          },
          {
            label: 'Manchester',
            value: 'manchester'
          }
        ];

        return testarray;
    }
  }
}

Expect a select box with the 3 options, London, Edinburgh, Manchester. Actual results, Empty select box with multiple empty options.

Stack trace in console.

  • TypeError: self.apos.modules[field.moduleName]field.choices.then is not a function
  • at self.routes.choices (/app/node_modules/apostrophe/lib/modules/apostrophe-schemas/lib/routes.js:72:68)
  • 1
    Documentation is misleading "You may use an async function, or return a promise that will resolve to the array." you must use one of these. I have resolved this by setting the function as async. – ThorntonReed Jun 12 '19 at 13:04
  • Just coded up a fix to allow this. https://github.com/apostrophecms/apostrophe/pull/1950 – Tom Boutell Jun 12 '19 at 21:13
  • Nice. I have another question which is related I suppose. https://stackoverflow.com/questions/56581537/dynamic-select-fields-in-apostrophe-inside-array-field-type – ThorntonReed Jun 13 '19 at 13:24

0 Answers0