+ Start a Discussion
Mike Tol 1Mike Tol 1 

error creating contact

Hi everyone.
I can't create a contact. Please tell me what is wrong.

User-added image


My code:
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={cardTitle}>                    
                        <div class="slds-m-around_medium">
                            <lightning-record-edit-form
                         
                            object-api-name="Contact"
                        >
                            <lightning-messages> </lightning-messages>
                           
                            <lightning-input-field  field-name="LastName"></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;
    //object-api-name="{objectApiName}"
    //record-id="{recordId}"
    @api recordId;
    @api objectApiName;
 
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }
    handlelnameChange(event) {
        this.LastName = event.target.value;
        window.console.log("LNAME", this.LastName);
    }
    handleClick(event) {
        console.log("handleClick", event);
        const contact = {
         
            LastName: this.LastName,
       
        }
        insertContact ({ con : contact })
            .then(() => {            
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
                this.showModal = false;
                return refreshApex(this._wiredResult);
            })
            .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
mukesh guptamukesh gupta
Hi Mike,

Please use below JS code:-
 
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;
    //object-api-name="{objectApiName}"
    //record-id="{recordId}"
    @api recordId;
    @api objectApiName;
 
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }
    handlelnameChange(event) {
        this.LastName = event.target.value;
        window.console.log("LNAME", this.LastName);
    }
    handleClick(event) {
        console.log("handleClick", event);
        const contact = {         
            LNAME_FIELD: this.LastName,
       }
        insertContact ({ con : contact })
            .then(() => {            
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
                this.showModal = false;
                return refreshApex(this._wiredResult);
            })
            .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;
    // }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 

All Answers

mukesh guptamukesh gupta
Hi Mike,

Please use below JS code:-
 
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;
    //object-api-name="{objectApiName}"
    //record-id="{recordId}"
    @api recordId;
    @api objectApiName;
 
    @wire(getContacts)
    wiredCallback(result) {
        this._wiredResult = result;
    }
    handlelnameChange(event) {
        this.LastName = event.target.value;
        window.console.log("LNAME", this.LastName);
    }
    handleClick(event) {
        console.log("handleClick", event);
        const contact = {         
            LNAME_FIELD: this.LastName,
       }
        insertContact ({ con : contact })
            .then(() => {            
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created',
                        variant: 'success',
                    }),
                );
                this.showModal = false;
                return refreshApex(this._wiredResult);
            })
            .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;
    // }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 
This was selected as the best answer
Mike Tol 1Mike Tol 1

thank you very much!