Prefill values in lightning:inputField

In order to prefill value in Lightning:inputField, first add an aura:Id and then specify the fieldName

<lightning:inputField aura:id="input_AccountId" fieldName="AccountId" />

We will be using lightning:recordEditFor on Contact Object, and add onload method to it, I named it setDefaults for this example:

<lightning:recordEditForm aura:id="recordEditForm" recordId="{!v.recordId}"
                                  objectApiName="Contact" onload="{!c.setDefaults}">

finally, in the setDefaults method in js controller use

component.find("input_FirstName").set("v.value", defaultValue);

Our code should look like this

ContactDetailsCmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
  <lightning:recordEditForm aura:id="recordEditForm" recordId="{!v.recordId}"
                            objectApiName="Contact" onload="{!c.setDefaults}">

    <lightning:messages/>
    <lightning:layout>
      <lightning:layoutItem size="6">
        <lightning:inputField aura:id="input_AccountId" fieldName="AccountId" />
      </lightning:layoutItem>
      <lightning:layoutItem size="6">
        <lightning:inputField aura:id="input_FirstName" fieldName="FirstName" />
      </lightning:layoutItem>
    </lightning:layout>
    <lightning:layout>
      <lightning:layoutItem size="6">
        <lightning:inputField aura:id="input_LastName" fieldName="LastName" />
      </lightning:layoutItem>
      <lightning:layoutItem size="6">
        <lightning:inputField aura:id="input_Email" fieldName="Email" />
      </lightning:layoutItem>
    </lightning:layout>
    <lightning:layout horizontalAlign="center" class="slds-m-top_large">
      <lightning:button variant="brand" label="Submit" title="Submit" type="submit"/>
    </lightning:layout>
  </lightning:recordEditForm>
</aura:component>

And our JS controller should look like this

ContactDetailCmpController.js

({
  setDefaults : function(component, event, helper) {
    component.find("input_FirstName").set("v.value", "DEFAULT FIRSTNAME");
    component.find("input_LastName").set("v.value", "DEFAULT LASTNAME");
    component.find("input_Email").set("v.value", "[email protected]");
  }
})

Now you can see the defaults value on component load:

Prefill values in lightning:inputField

Also, make sure that when you set the default value in  Lookup fields, you use 18 digit Id and not 15 digits or else you will see an error like this

Cannot read property 'fields' of undefined

Cannot read property ‘fields’ of undefined

Was this post useful? If yes then please share.



Leave a Comment

All fields marked with an asterisk (*) are required


shares