How to change the options of my Select component?

You can change the selectable options and their corresponding values of a Select component after initializing the form by following these steps:

  • In the initialization code:
    • Add a Hidden component. The Select component will obtain its options from it.
    • Optionally set the defaultValue property of the Hidden component as default options for the Select component.
    • Add a Select component and make it reference the Hidden component for its options. This is done by setting the Select component's dataSrc property to 'custom' and filling its data property with a struct/dict with key custom and JavaScript code that references the data of the Hidden component.
  • In the event handling code:
    • Update the value of the Hidden component to update the options of the Select component.

These steps are illustrated in an example below. First, we give the initialization code:

% This hidden component holds information on the options of the Select.
hiddenKey           = "HiddenKey";
valueFieldName      = "value";
hid                 = component.Hidden(hiddenKey, form);
hid.defaultValue    = struct( ...
    "label",        {"Option 1", "Option 2"}, ...
    valueFieldName, {"opt1", "opt2"} ...
    );

% Create the Select component and make it reference the Hidden component.
sel                 = component.Select("s", form);
sel.dataSrc         = "custom";
sel.data.custom     = "values = data." + hiddenKey;
sel.valueProperty   = valueFieldName;
# This hidden component holds information on the options of the Select.
hidden_key = "HiddenKey"
value_field_name = "value"
hid = component.Hidden(hidden_key, form)
hid.defaultValue = [
    {"label": "Option 1", value_field_name: "opt1"}, 
    {"label": "Option 2", value_field_name: "opt2"}
]

# Create the Select component and make it reference the Hidden component.
sel = component.Select("s", form)
sel.dataSrc = "custom"
sel.data = {"custom": "values = data." + hidden_key}
sel.valueProperty = value_field_name

The event code becomes:

val     = struct( ...
    "label", {"New option 1", "New option 2"}, ...
    "value", {"value1", "value2"} ...
    );
payload = utils.setSubmissionData(payload, "HiddenKey", val);
val = [
    {"label": "New option 1", "value": "value1"}, 
    {"label": "New option 2", "value": "value2"}
]
utils.setSubmissionData(payload, "HiddenKey", val)

In a similar fashion, the options of a Selectboxes component can be changed after initialization as described here.