function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mike Tol 1Mike Tol 1 

How create contact using lightning-input-field?

Hi everyone.
I created a contact using lightning-input.
But I need to create a contact (and lookup search Account) using lightning-input-field. I сan't link html with js and Apex. Please tell me how can I do that. (I must use Apex).


My code with lightning-input that works:

Html:
<template>
    <lightning-card if:true={showModal}>
       <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <lightning-button-icon class="slds-modal__close" title="Close" icon-name="utility:close" icon-class="slds-button_icon-inverse" onclick={handleDialogClose}></lightning-button-icon>
                <div class="slds-modal__header">
                    <h1 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Create contact with custom lookup</h1>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">                   
                    
                    
                    
                    <lightning-card title="New contact" icon-name="standard:contact">
                        <div class="slds-p-around_x-small">
                           
                            <lightning-input  type="text" label="Last name" value={rec.LNAME} onchange={handlelnameChange}></lightning-input>
                           
                            
                            <br/>
                            <lightning-button label="Save" onclick={handleClick}></lightning-button>
                        </div>
                    </lightning-card>


                </div>    
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open" role="presentation"></div>
    </lightning-card>
</template>

Js:
import { LightningElement, api, wire, track } from 'lwc';
import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import insertContact from '@salesforce/apex/ContactTableProjectSecond.addContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactTableProjectSecond.getContacts';
import {refreshApex} from "@salesforce/apex";

export default class LwcNewContactUsingApexImperativecalling extends LightningElement {

    showModal = false;
    
    @track lname =LNAME_FIELD;
      
     rec={       
         LNAME:this.lname,        
      }

    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }

    handlelnameChange(event) {
        this.rec.LNAME = event.target.value;
        window.console.log("LNAME", this.rec.LNAME);
    }

    handleClick() {
        const contact = {
         
            LastName: this.rec.LNAME,
       
        }
        insertContact ({ con : contact })
            .then(() => {
                // this.rec={}; // Don't. You aren't clearing the value of rec properties, you're removing them. So everywhere you're using them you'll get an error because they will be now undefined properties.
            
                this.rec.LNAME = null;
               
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log('error', JSON.stringify(error));
            });
    }

    @api show() {
        this.showModal = true;
    }

    handleDialogClose() {
        this.showModal = false;
    }   

    // @track selectedAccountId;
    // handleSelected(event){
    //     console.log(event.detail);
    //     this.selectedAccountId = event.detail;
    // }
}

Apex:
public with sharing class ContactTableProjectSecond {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts() {
        return [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
        ];
    }
    
    @AuraEnabled(cacheable=true)
    public static List<Contact> searchContacts(String searchKey) {
        String searchKeyword = '%' + searchKey + '%';
        List<Contact> contacts = [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
            WHERE Name LIKE :searchKeyword
        ];
        return contacts;        
    }

    @AuraEnabled
    public static void deleteContact(Id recordId) {   
        List<Contact> contact = [SELECT Id FROM Contact WHERE Id = :recordId];
        delete contact;   
   }
    
    @AuraEnabled
    public static Contact addContact(Contact con) {
        //Contact contact = new Contact(); 
        system.debug('con'+con);
    insert con;
        return con;
    } 
    
    @AuraEnabled(cacheable=true)
    public static List<account> getCustomLookupAccount(String actName) {
        List<account> accountLookupList =  new List<account>();
        System.debug('accountLookupList' + accountLookupList);
            if (actName != '') {
            String accountName = '%' + actName + '%';
            accountLookupList = [SELECT Id, Name FROM Account WHERE Name like:accountName];
            return accountLookupList;
            }
        return accountLookupList;
        }  
}

My code with lightning-input-field that doesn’t work:

Html:
<template>
    <lightning-card if:true={showModal} title={cardTitle}>
       <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <lightning-button-icon class="slds-modal__close" title="Close" icon-name="utility:close" icon-class="slds-button_icon-inverse" onclick={handleDialogClose}></lightning-button-icon>
                <div class="slds-modal__header">
                    <h1 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Create contact with custom lookup</h1>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">                   
                    
                    
                    <lightning-card title={cardTitle}>                    
                    <div class="slds-m-around_medium">
                        <lightning-record-edit-form object-api-name="Contact">
                        
                            <lightning-input-field field-name="LastName">
                            </lightning-input-field> 
                            <lightning-input-field field-name="AccountId" value={recordId}>
                            </lightning-input-field>
                                <lightning-button
                                label="Save" onclick={handleClick}>
                                </lightning-button>
                        </lightning-record-edit-form>
                    </div>
                </lightning-card>


                </div>    
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open" role="presentation"></div>
    </lightning-card>
</template>

Js:
import { LightningElement, api, wire, track } from 'lwc';
import LNAME_FIELD from '@salesforce/schema/Contact.Name';
//import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import insertContact from '@salesforce/apex/ContactTableProjectSecond.addContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactTableProjectSecond.getContacts';
import {refreshApex} from "@salesforce/apex";

export default class LwcNewContactUsingApexImperativecalling extends LightningElement {

    showModal = false;
 
    LastName = LNAME_FIELD;

    field={       
        LNAME:this.LastName,       
     }

    @api recordId;
  
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }

    handlelnameChange(event) {
        this.field.LNAME = event.target.value;
        window.console.log("LNAME", this.field.LNAME);
    }

    handleClick(event) {
        console.log("handleClick", event);
        const contact = {
         
            LastName: this.field.LNAME,
       
        }
        insertContact ({ con : contact })
            .then(() => {
                // this.rec={}; // Don't. You aren't clearing the value of rec properties, you're removing them. So everywhere you're using them you'll get an error because they will be now undefined properties.
            
                this.field.LNAME = null;
               
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log('error', JSON.stringify(error));
            });
    }
    


    @api show() {
        this.showModal = true;
    }

    handleDialogClose() {
        this.showModal = false;
    }   

    // @track selectedAccountId;
    // handleSelected(event){
    //     console.log(event.detail);
    //     this.selectedAccountId = event.detail;
    // }
}

Apex:
public with sharing class ContactTableProjectSecond {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts() {
        return [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
        ];
    }
    
    @AuraEnabled(cacheable=true)
    public static List<Contact> searchContacts(String searchKey) {
        String searchKeyword = '%' + searchKey + '%';
        List<Contact> contacts = [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
            WHERE Name LIKE :searchKeyword
        ];
        return contacts;        
    }

    @AuraEnabled
    public static void deleteContact(Id recordId) {   
        List<Contact> contact = [SELECT Id FROM Contact WHERE Id = :recordId];
        delete contact;   
   }
    
    @AuraEnabled
    public static Contact addContact(Contact con) {
        //Contact contact = new Contact(); 
        system.debug('con'+con);
    insert con;
        return con;
    } 
    
    @AuraEnabled(cacheable=true)
    public static List<account> getCustomLookupAccount(String actName) {
        List<account> accountLookupList =  new List<account>();
        System.debug('accountLookupList' + accountLookupList);
            if (actName != '') {
            String accountName = '%' + actName + '%';
            accountLookupList = [SELECT Id, Name FROM Account WHERE Name like:accountName];
            return accountLookupList;
            }
        return accountLookupList;
        }  
}
 
Best Answer chosen by Mike Tol 1
ravi soniravi soni
hi ,
here is updated code. I made some changes in your code. instead of using onclick, we can use submit type button it saves the record automatically. if you want to call apex class when user click on submit/save button, you have to use prevent.default() method in your handleSubmit method and then call your apex class.
 
<template>
    <lightning-card if:true={showModal} title={cardTitle}>
       <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <lightning-button-icon class="slds-modal__close" title="Close" icon-name="utility:close" icon-class="slds-button_icon-inverse" onclick={handleDialogClose}></lightning-button-icon>
                <div class="slds-modal__header">
                    <h1 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Create contact with custom lookup</h1>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">                   
                    
                    
                    <lightning-card title={cardTitle}>                    
                    <div class="slds-m-around_medium">
                        <lightning-record-edit-form object-api-name="Contact"
						 onsuccess={handleSuccess} onsubmit ={handleSubmit}>
                         <lightning-messages>
                         </lightning-messages>
                            <lightning-input-field field-name="LastName">
                            </lightning-input-field> 
                            <lightning-input-field field-name="AccountId" value={recordId}>
                            </lightning-input-field>
                                <!--<lightning-button type
                                label="Save" onclick={handleClick}>
                                </lightning-button>-->
								 <lightning-button class="slds-m-top_small" variant="brand" type="submit" name="Save" label="Save">
                        </lightning-record-edit-form>
                    </div>
                </lightning-card>


                </div>    
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open" role="presentation"></div>
    </lightning-card>
</template>
=================================================
import { LightningElement, api, wire, track } from 'lwc';
//import LNAME_FIELD from '@salesforce/schema/Contact.Name';
//import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import insertContact from '@salesforce/apex/ContactTableProjectSecond.addContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactTableProjectSecond.getContacts';
import {refreshApex} from "@salesforce/apex";

export default class LwcNewContactUsingApexImperativecalling extends LightningElement {

    showModal = false;
 /*
    LastName = LNAME_FIELD;

    field={       
        LNAME:this.LastName,       
     }*/

    @api recordId;
  /*
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }
*/

/*  here is submit method and success method */
 handleSubmit(event) {
        console.log('onsubmit event recordEditForm'+ event.detail.fields);
		/*If you want to prevent records from save, use 'event.preventDefault()' method and call your apex class in this method and pass value in apex method.*/
    }
    handleSuccess(event) {
        console.log('onsuccess event recordEditForm', event.detail.id);
    }
	/* ##################### */
	
	
	
    handlelnameChange(event) {
        this.field.LNAME = event.target.value;
        window.console.log("LNAME", this.field.LNAME);
    }

    handleClick(event) {
        console.log("handleClick", event);
        const contact = {
         
            LastName: this.field.LNAME,
       
        }
        insertContact ({ con : contact })
            .then(() => {
                // this.rec={}; // Don't. You aren't clearing the value of rec properties, you're removing them. So everywhere you're using them you'll get an error because they will be now undefined properties.
            
                this.field.LNAME = null;
               
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log('error', JSON.stringify(error));
            });
    }
    


    @api show() {
        this.showModal = true;
    }

    handleDialogClose() {
        this.showModal = false;
    }   

    // @track selectedAccountId;
    // handleSelected(event){
    //     console.log(event.detail);
    //     this.selectedAccountId = event.detail;
    // }
}

don't forget to mark it as best answer if above solution is helpfull to you.
thank you
 

All Answers

ravi soniravi soni
hi ,
here is updated code. I made some changes in your code. instead of using onclick, we can use submit type button it saves the record automatically. if you want to call apex class when user click on submit/save button, you have to use prevent.default() method in your handleSubmit method and then call your apex class.
 
<template>
    <lightning-card if:true={showModal} title={cardTitle}>
       <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <lightning-button-icon class="slds-modal__close" title="Close" icon-name="utility:close" icon-class="slds-button_icon-inverse" onclick={handleDialogClose}></lightning-button-icon>
                <div class="slds-modal__header">
                    <h1 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Create contact with custom lookup</h1>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">                   
                    
                    
                    <lightning-card title={cardTitle}>                    
                    <div class="slds-m-around_medium">
                        <lightning-record-edit-form object-api-name="Contact"
						 onsuccess={handleSuccess} onsubmit ={handleSubmit}>
                         <lightning-messages>
                         </lightning-messages>
                            <lightning-input-field field-name="LastName">
                            </lightning-input-field> 
                            <lightning-input-field field-name="AccountId" value={recordId}>
                            </lightning-input-field>
                                <!--<lightning-button type
                                label="Save" onclick={handleClick}>
                                </lightning-button>-->
								 <lightning-button class="slds-m-top_small" variant="brand" type="submit" name="Save" label="Save">
                        </lightning-record-edit-form>
                    </div>
                </lightning-card>


                </div>    
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open" role="presentation"></div>
    </lightning-card>
</template>
=================================================
import { LightningElement, api, wire, track } from 'lwc';
//import LNAME_FIELD from '@salesforce/schema/Contact.Name';
//import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import insertContact from '@salesforce/apex/ContactTableProjectSecond.addContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactTableProjectSecond.getContacts';
import {refreshApex} from "@salesforce/apex";

export default class LwcNewContactUsingApexImperativecalling extends LightningElement {

    showModal = false;
 /*
    LastName = LNAME_FIELD;

    field={       
        LNAME:this.LastName,       
     }*/

    @api recordId;
  /*
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }
*/

/*  here is submit method and success method */
 handleSubmit(event) {
        console.log('onsubmit event recordEditForm'+ event.detail.fields);
		/*If you want to prevent records from save, use 'event.preventDefault()' method and call your apex class in this method and pass value in apex method.*/
    }
    handleSuccess(event) {
        console.log('onsuccess event recordEditForm', event.detail.id);
    }
	/* ##################### */
	
	
	
    handlelnameChange(event) {
        this.field.LNAME = event.target.value;
        window.console.log("LNAME", this.field.LNAME);
    }

    handleClick(event) {
        console.log("handleClick", event);
        const contact = {
         
            LastName: this.field.LNAME,
       
        }
        insertContact ({ con : contact })
            .then(() => {
                // this.rec={}; // Don't. You aren't clearing the value of rec properties, you're removing them. So everywhere you're using them you'll get an error because they will be now undefined properties.
            
                this.field.LNAME = null;
               
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log('error', JSON.stringify(error));
            });
    }
    


    @api show() {
        this.showModal = true;
    }

    handleDialogClose() {
        this.showModal = false;
    }   

    // @track selectedAccountId;
    // handleSelected(event){
    //     console.log(event.detail);
    //     this.selectedAccountId = event.detail;
    // }
}

don't forget to mark it as best answer if above solution is helpfull to you.
thank you
 
This was selected as the best answer
Mike Tol 1Mike Tol 1

thank you very much!