1

In Lightning component we have used aura id to set value.

Lightning Component

<lightning:recordEditForm objectApiName="Account">                                    
 <lightning:inputField variant="label-hidden" aura:id="userId" label="Users" fieldName="SampleUser__c"  value=""/>
</lightning:recordEditForm> 

component.find('userId').set('v.value', selectedUserId);

How to set the value to a lookup field in LWC. Please advise on this.

<lightning-record-edit-form object-api-name="Account" >
       <lightning-input-field field-name="SampleUser__c" onchange={onUserChange} >  
      </lightning-input-field>
</lightning-record-edit-form>
4

Option 1: Directly identify the element and set value: (Preferred)

<template>
    <div>
        <lightning-button label="Set Acc id" onclick={setAccid}></lightning-button>
    </div>
    <div>
        <lightning-record-edit-form object-api-name="Contact">
            <lightning-messages>
            </lightning-messages>
            <lightning-input-field field-name="FirstName">
            </lightning-input-field>
            <lightning-input-field field-name="LastName">
            </lightning-input-field>
            <lightning-input-field data-accid field-name="AccountId">
            </lightning-input-field>
        </lightning-record-edit-form>
    </div>
</template>

JS:

setAccid() {
    this.template.querySelector('[data-accid]').value = '00128000009j45sAAA';
}

you can invoke setAccid whenever you need. Advantage here is, you need not maintained tracked properties like below option.


Option 2: You can use value directly. Note that LWC is not 2-way binding, so value is used only for default. This is useful when you want to set values in multiple fields through an object property.

HTML:

<lightning-input-field field-name="AccountId" value={accid}>
        </lightning-input-field>

JS:

@track accid;

setAccid(){
    this.accid = '00128000009j45sAAA';
}

You can invoke setAccid whenever you want to set the accid.

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.