Populating a field on-load of Record Edit Form in Lightning Web Component

Use Case:- We are using lightning-record-edit-form to create Contact record associated to an Account. We need to populate the account id in Contact form placed on Account record page in Lightning Experience.

Solution:- We have our Lightning Web Component which uses the lightning-record-edit-form to create contact record form to create a record.


    <lightning-card title={cardTitle}
        <div class="slds-m-around_medium">
            <lightning-record-edit-form object-api-name="Contact" onsuccess={handleSuccess}>
                <lightning-input-field field-name="Name">
                <lightning-input-field field-name="AccountId" value={recordId}>
                <lightning-input-field field-name="Title">
                        label="Create new">

Highlights:- We are using value attribute of lightning-input-field to bind it with current account record id using recordId property.


import { LightningElement,track,api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class MyRecordEditForm extends LightningElement {
    @api recordId;
    @track cardTitle='New Contact';
    handleSuccess (){
        const evt = new ShowToastEvent({
            title: "Success!",
            message: "The Contact's record has been successfully saved.",
            variant: "success",

Highlights:- We are using track and api decorators to bind the properties we have used in html markup. Also, We are firing a toast message after record gets saved successfully.


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myRecordEditForm">
    <masterLabel>Contact Card</masterLabel>
    <description>This component shows the new contact record form.</description>
        <targetConfig targets="lightning__RecordPage">

Highlights:- We are exposing component only to account record page so that functionality works properly.


Leave a Reply