javascriptsitecoresitecore8sitecore-speak-ui

Sitecore SPEAK UI programmatically set selected item of ComboBox


How should I set the selected item of a ComboBox component in Sitecore SPEAK UI?

My ComboBox is populated by a QueryDataSource component which is looking at a folder of items in my core DB.

I can retrieve the currently selected value (which is text, not an ID) using the following code:

var value = this.MyComboBoxId.viewModel.selectedItemId();

and I would have expected to be able to set the selected value using:

var value = "SomeValueWhichExistsInTheList";
this.MyComboBoxId.viewModel.selectedItemId(value);

but this doesn't seem to work. The documentation here mentions using

rebind(items, selectedItem, selectedValue, displayFieldName, valueFieldName)

but I don't want to have to re-populate it, just change the selected item. My code is within the initialize method of my model.

Edit

I found that if the ComboBox does not have DisplayFieldName or ValueFieldName values set in the rendering properties you have to set the value to the appropriate itemId. DisplayFieldName and/or ValueFieldName should be set to the name of a field you have created - you cannot bind to the item name.


Solution

  • In the initialize method, use the following code to set the value:

    app.yourQueryDataSource.on("change:hasItems", function () {
        app.yourComboBox.set("selectedValue", yourValue); 
    });