September 17, 2021

How to pass values from lightning:recordEditForm to apex class in Salesforce?

Sample Code:
CMP:
<aura:component implements="force:appHostable" controller="SampleAuraController">
    <lightning:card>
        <lightning:recordEditForm aura:id="recordEditForm" objectApiName="Lead" onsubmit="{!c.doSubmit}">
            <lightning:messages />
            <lightning:inputField fieldName="FirstName" />
            <lightning:inputField fieldName="LastName" />
            <lightning:inputField fieldName="Email" />
            <lightning:inputField fieldName="Phone" />
            <lightning:inputField fieldName="Company" />
            <div id="recaptchaCheckbox"></div>
            <br/>
            <lightning:button aura:id="myButton" label="Create Lead" type="submit"/>
        </lightning:recordEditForm>
    </lightning:card>
</aura:component>
 
JS:
({
    
    doSubmit: function ( component, event, helper ) {
        
        console.log( 'Inside Submit' );
        event.preventDefault();
        let fields = event.getParam( 'fields' );
        fields = Object.assign( { 'sobjectType': 'Lead' }, fields );
        console.log( 'Fields are ' + JSON.stringify( fields ) );
        let action = component.get( "c.insertRecord" );
        action.setParams( {            
            record: fields
            
        } );        
        action.setCallback( this, function( response ) {
            
            document.dispatchEvent(new Event( "grecaptchaReset" ) );
            let myButton = component.find( "myButton" );
            myButton.set( 'v.disabled', true );            
            let state = response.getState();
            
            if ( state === "SUCCESS" ) {
                
                let result = response.getReturnValue();
                console.log( 'Result is ' + JSON.stringify( result ) );
                
                if ( result === 'Success' ) {
                    
                    let showToast = $A.get( "e.force:showToast" );
                    showToast.setParams( {
                        
                        title : 'Lead Creation',
                        message : 'Lead Submitted Sucessfully.' ,
                        type : 'success',
                        mode : 'dismissible'
                        
                    } );
                    showToast.fire();
                    
                }
                
            } else {
                
                let errors = response.getError();
                if ( errors ) {
                    
                    console.log( errors[ 0 ] );
                    
                }
                    
                let showToast = $A.get( "e.force:showToast" );
                showToast.setParams( {
                    
                    title : 'Lead Creation',
                    message : 'Lead is not Submitted due to some error.' ,
                    type : 'error',
                    mode : 'dismissible'
                    
                } );
                showToast.fire();
                
            }
            
        });        
        $A.enqueueAction(action);
        
    }
    
})
 
Apex Class:
public class SampleAuraController {
    
    @AuraEnabled
    public static String insertRecord( SObject record ) {   
        
        try {
            
            insert record;
            return 'Success';
            
        } Catch( Exception e ) {
            
            return 'Failed';
            
        }
        
    }
    
}
 
Output:
 

Lead Creation with Captcha in Salesforce Experience Cloud using Lightning Web Component LWC

1. Complete steps 1 through 10 from the following.
 
2. Use the same Apex Class from the above link.
 
Solution:
1. googleCaptcha is a re-usable LWC. This will fire events when the users click I'm not a robot and when the Captcha expires.
2. leadCreationForm is the parent LWC. This will handle the events from the googleCaptcha child component. When the Captcha verification is successful, the Create Lead Button will be enabled. If the Captcha verification fails or expires, the Create Lead Button will be disabled.
 

Sample Code:

googleCaptcha LWC:
HTML:
<template>
    <div class="recaptchaCheckbox"></div>
</template>
 
JS:
import { LightningElement } from 'lwc';

export default class GoogleCaptcha extends LightningElement {

    connectedCallback() {

        console.log( 'Inside Google Captcha Connected Callback' );
        document.addEventListener( "grecaptchaVerified", ( e ) => {

            console.log( 'Captcha Response from Verification is ' + e.detail.response );
            let detailPayload = { value : false, response : e.detail.response };
            this.dispatchEvent( new CustomEvent( 'captcha', { detail : detailPayload } ) );

        });

        document.addEventListener( "grecaptchaExpired", () => {

            console.log( 'Listener Expired' );
            this.dispatchEvent( new CustomEvent( 'captcha', { detail : { value : true } } ) );

        } );
        
    }

    renderedCallback() {

        console.log( 'Inside Google Captcha Rendered Callback' );
        let divElement = this.template.querySelector( 'div.recaptchaCheckbox' );
        console.log( 'Div Element is ' + JSON.stringify( divElement ) );
        let payload = { element: divElement };
        document.dispatchEvent(new CustomEvent( "grecaptchaRender",  { "detail": payload } ) );
        
    }

}

 
JS-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
</LightningComponentBundle>

 
leadCreationForm LWC:
HTML:
<template>
    <lightning-card title="Lead Creation">
        <lightning-record-edit-form object-api-name="Lead" onsubmit={handleSubmit}>
            <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 field-name="Email"></lightning-input-field>
            <lightning-input-field field-name="Phone"></lightning-input-field>
            <lightning-input-field field-name="Company"></lightning-input-field>
            <c-google-captcha oncaptcha={handleUpdate}></c-google-captcha><br/>
            <lightning-button type="submit" label="Create Lead" variant="brand" disabled={verifiedBool}></lightning-button>        
        </lightning-record-edit-form>
    </lightning-card>
</template>

 
JS:
import { LightningElement } from 'lwc';
import insertRecord from '@salesforce/apex/RecaptchaController.insertRecord';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class LeadCreationForm extends LightningElement {

    verifiedBool = true;
    captchaResponse
    
    handleUpdate( event ) {

        console.log( 'Updated value is ' + JSON.stringify( event.detail ) );
        this.verifiedBool = event.detail.value;

        if ( event.detail.response ) {

            console.log( 'Response is ' + event.detail.response );
            this.captchaResponse = event.detail.response;

        }

    }

    handleSubmit( event ) {

        let fields = event.detail.fields;
        fields = Object.assign( { 'sobjectType': 'Lead' }, fields );
        console.log( 'Fields are ' + JSON.stringify( fields ) );
        console.log( 'Captcha Response is ' + JSON.stringify( this.captchaResponse ) );
        event.preventDefault();

        insertRecord( { record : fields, recaptchaResponse : this.captchaResponse } )
        .then( result => {

            this.isLoaded = false;
            window.console.log('result ===> '+result);
            this.strMessage = result;
            this.dispatchEvent(
                new ShowToastEvent( {
                    title: 'Lead Submission Result',
                    message: 'Lead ' + ( result.includes( 'Success' ) ? '' : 'not ' ) + 'Submitted Successfully',
                    variant: result.includes( 'Success' ) ? 'success' : 'error',
                    mode: 'sticky'
                } )
            );

        })
        .catch( error => {

            this.dispatchEvent(
                new ShowToastEvent( {
                    title: 'Error',
                    message: JSON.stringify( error ),
                    variant: 'error',
                    mode: 'sticky'
                } )
            );     

        } )

    }

}

 
JS-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Lead Creation Form</masterLabel>
    <targets>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
</LightningComponentBundle>

 
Output: