1

I'm looking for getting a dynamically assigned Aura:id. Below is my attempt to read it in Lightning:recordEditForm.

Component markup:

<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:attribute name="conid" type="Id" default="null" />

    <aura:attribute name="fields" type="String[]" default="['Email','Birthdate']" />

    <lightning:recordEditForm aura:id="conRecEdit" objectApiName="Contact" recordid="{!v.conid}" >
        <lightning:messages />
        <lightning:inputField aura:id="fname" fieldName="FirstName"/>   
        <lightning:inputField aura:id="lname" fieldName="LastName"/>    

        <aura:iteration items="{!v.fields}" var="f" >
            <lightning:inputField aura:id="{!f}" fieldName="{!f}"/>
        </aura:iteration>

        <lightning:button type="button" label="test" onclick="{!c.checkValue}" />
    </lightning:recordEditForm>
</aura:component>

JS Controller:

({
    init : function(component, event, helper) {
        var fld = component.find('fname');
        console.log('fld '+fld);
        if (fld!=null)
            fld.set('v.value', 'new name');

        var fld1 = component.find('Email');
        console.log('fld1 '+fld1);
        if (fld1!=null)
            fld1.set('v.value', 'test@test.com');
    },

    checkValue: function(component, event, helper){
        var fld1 = component.find('Email');
        console.log('fld1 '+fld1);

        if (fld1!=null)
            fld1.set('v.value', 'test@test.com');

    },
})

enter image description here

If we assign aura:id hard-coding it, it works perfectly fine. But if the id is assigned dynamically, seems it's not possible to find here.

Any clues, suggestions to workaround reading the aura:id in above working example. Much Appreciated! Thanks!

5

aura:id can't be populated dynamically:

aura:id doesn't support expressions. You can only assign literal string values to aura:id.

Instead, give all of your <lightning:inputField> components a common aura:id so that you can find them, and then filter by the fieldName attribute:

<aura:iteration items="{!v.fields}" var="f" >
    <lightning:inputField  aura:id="contactField" fieldName="{!f}"/>
</aura:iteration>

then

let emailField = component.find('contactField').filter(x => x.get('v.fieldName') === 'Email')[0];
emailField.set('v.value', 'test@test.com');
  • Hi @David Reed Thank you, and appreciate for your help. worked perfect. – PasanE May 21 at 23:28
  • Probably could use const rather than let. – Adrian Larson May 21 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.