Search code examples
node.jsmongoosekeystonejs

Dynamic type select in keystonejs model


I would like to use a combobox at the adminUI with fields that come from a webservice. I was thinking on get the data with a pre 'find' hook and then override the options atribute at the 'audience' property in the Schema.

Schema:

Compliance.add({
  title: { type: Types.Text, required: true, initial: true, index: true }, 
  url: { type: Types.Url, required: true, initial: true },
  position: { type: Types.Number, initial: true },
  audience: { type: Types.Select, options: [], many: true, initial: true},
});

Hook:

Compliance.schema.pre('find', async function(next) {
  let audiences = await audienceService.getAudiences();
  next();
})

But I didn't find the way to bind the data. Any ideas how this can be done?

Thanks


Solution

  • You can try making a function from the options:

    function getAudiences() {
        return ['a', 'b', 'c'];
    }
    
    Compliance.add({
      title: { type: Types.Text, required: true, initial: true, index: true }, 
      url: { type: Types.Url, required: true, initial: true },
      position: { type: Types.Number, initial: true },
      audience: { type: Types.Select, many: true, initial: true, options: getAudiences() }
    });
    

    Result as below:

    enter image description here