[SalesForce] Dynamically setting value of lightning combobox in javascript

I have dynamically created lightning:comboboxes that are instantiated in my JavaScript controller for my lightning component. In my callback function after the component is created, I want to set the value of that combobox if a value exists for it (user is editing instead of creating).

I tried something like this:

$A.createComponent(
            'lightning:combobox',
            {
                'aura:id': 'objectSelect',
                'id': index,
                'placeholder': 'Select Object',
                'label': label,
                'value': 'selectedObject' + index,
                'options': options,
                'onchange': component.getReference('c.handleObjectSelect')
            },
            function(newCombobox, status, error){
                if(status === 'SUCCESS'){
                    var cmpBody = component.get('v.comboboxes');
                    cmpBody.push(newCombobox);
                    component.set('v.comboboxes', cmpBody);

                    var thisCriteria = component.get('v.currentCriteria');
                    if(thisCriteria != null){
                        newCombobox.set('v.value', thisCriteria.objectName);
                    }
                }
                else if(status === 'INCOMPLETE'){
                    console.log('No response from server');
                }
                else if(status === 'ERROR'){
                    console.log(error);
                }
            }
        );

But doing set('v.value') does not seem to work. I know you can do .get('v.value') to get the selected value, I had hoped you could also set it from there.

I also know you can specify 'value' as an attribute for the combobox and bind it to an aura attribute, but I am dynamically creating these, I don't want to hardcode aura attributes in case the combobox is there for it, I would like to be able to just set the value directly instead of through an aura attribute.

Is such a thing possible?

Best Answer

Couldn't you evaluate this just before creating the component? Just check for your object name, and then instantiate. Like so:

var thisCriteria = component.get('v.currentCriteria');
var comboboxValue = thisCriteria == null ? 'selectedObject' + index : thisCriteria.objectName

$A.createComponent(
        'lightning:combobox',
        {
            'aura:id': 'objectSelect',
            'id': index,
            'placeholder': 'Select Object',
            'label': label,
            'value': comboboxValue,
            'options': options,
            'onchange': component.getReference('c.handleObjectSelect')
        },
Related Topic