journey2salesforce

Create Record By Lightning Data Service

Create Record By Lightning Data Service

In this section, we will create a Contact Record from Account using Lightning Data Service(LDS) in Lightning Experience.

Step 1: Create a component bundle named “createContactByLDS”.

createContactByLDS.cmp | to create Contact record from Account by LDS

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:availableForFlowScreens">

    <aura:attribute name="account" type="Object"/>
    <aura:attribute name="loadedAccountFields" type="Object"/>
    <aura:attribute name="accountError" type="String"/>

    <aura:attribute name="newContact" type="Object"/>
    <aura:attribute name="newContactFields" type="Object"/>
    <aura:attribute name="newContactError" type="String"/>
    

    <force:recordData aura:id="accountRecordLoaderId"
        recordId="{!v.recordId}"
        fields="Name"
        targetRecord="{!v.account}"
        targetFields="{!v.loadedAccountFields}"
        targetError="{!v.accountError}"
    />

    <force:recordData aura:id="contactRecordCreatorId"
        layoutType="FULL"
        targetRecord="{!v.newContact}"
        targetFields="{!v.newContactFields}"
        targetError="{!v.newContactError}" 
    /> 

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <div class="slds-page-header" role="banner">
        <p class="slds-text-heading_label">{!v.loadedAccountFields.Name}</p>
        <h1 class="slds-page-header__title slds-m-right_small
            slds-truncate slds-align-left">Create New Contact</h1>
    </div>
    <lightning:card >
        <aura:if isTrue="{!not(empty(v.accountError))}">
            <div class="recordError">
                <ui:message title="Error" severity="error" closable="true">
                    {!v.accountError}
                </ui:message>
            </div>
        </aura:if>
        <aura:if isTrue="{!not(empty(v.newContactError))}">
            <div class="recordError">
                <ui:message title="Error" severity="error" closable="true">
                    {!v.newContactError}
                </ui:message>
            </div>
        </aura:if>

        <lightning:layout multiplerows="true" verticalalign="center">
            <lightning:layoutItem padding="around-small" size="12">
                <lightning:input aura:id="contactField" 
                                 name="firstName" 
                                 label="First Name"
                                 value="{!v.newContactFields.FirstName}"/>
              
                <lightning:input aura:id="contactField" 
                                 name="lastname" 
                                 label="Last Name"
                                 value="{!v.newContactFields.LastName}" 
                                 required="true"/>
                        
                <!--<lightning:input aura:id="contactField" 
                                 type="phone" 
                                 name="phone" 
                                 label="Phone Number"
                                 pattern="^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$"
                                 messageWhenPatternMismatch="The phone number must contain 7, 10, or 11 digits. Hyphens are optional."
                                 value="{!v.newContactFields.Phone}" 
                                 required="true"/>-->
                
                <lightning:input aura:id="contactField" 
                                 type="email" 
                                 name="email" 
                                 label="Email"
                                 value="{!v.newContactFields.Email}" />
                
                <div class="slds-float_right">
                    <lightning:button label="Reset" onclick="{!c.doReset}" class="slds-m-top_medium" />
                    <lightning:button label="Save" onclick="{!c.saveContact}"
                                      variant="brand" class="slds-m-top_medium"/>
                </div>                
           </lightning:layoutItem>
       </lightning:layout>    
    </lightning:card>
</aura:component>

createContactByLDSController.js | to call the standard Save operation by LDS

({
    doInit: function(component, event, helper) {
        helper.openNewContact(component);
    },

    saveContact: function(component, event, helper) {
        if(helper.validateContactForm(component)) {
            component.set("v.newContactFields.AccountId", component.get("v.recordId"));
            component.find("contactRecordCreatorId").saveRecord(function(saveResult) {
                if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {

                    var resultsToast = $A.get("e.force:showToast");
                    resultsToast.setParams({
                        "title": "Success! ",
                        "message": "The new contact was created.",
                        "type":"success"
                    });

                    $A.get("e.force:closeQuickAction").fire();
                    resultsToast.fire();

                    $A.get("e.force:refreshView").fire();
                    helper.openNewContact(component);
                }
                else if (saveResult.state === "INCOMPLETE") {
                    console.log("User is offline, device doesn't support drafts.");
                }
                else if (saveResult.state === "ERROR") {
                    console.log('Problem saving contact, error: ' +
                                 JSON.stringify(saveResult.error));
                }
                else {
                    console.log('Unknown problem, state: ' + saveResult.state +
                                ', error: ' + JSON.stringify(saveResult.error));
                }
            });
        }
    },

    doReset: function(component, event, helper) {
        //$A.get("e.force:closeQuickAction").fire();
        helper.openNewContact(component);
    },
})

createContactByLDSHelper.js | to reset and validate the form of the Contact

({
    
    openNewContact: function(component){
        component.find("contactRecordCreatorId").getNewRecord(
            "Contact", // objectApiName
            null, // recordTypeId
            false, // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.newContact");
                var error = component.get("v.newContactError");
                if(error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                }
                else {
                    console.log("Record template initialized: " + rec.sobjectType);
                }
            })
        );
    },


    validateContactForm: function(component) {
        var validContact = true;
        var allValid = component.find('contactField').reduce(function (validFields, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validFields && inputCmp.get('v.validity').valid;
        }, true);

        if (allValid) {
            var account = component.get("v.account");
            if($A.util.isEmpty(account)) {
                validContact = false;
                console.log("Quick action context doesn't have a valid account.");
            }
        	return(validContact);
            
        }  
	}
       
})

We have used openNewContact form to instantiate the Contact record means every time it will open the blank Contact template at the time of loading contact or at the time of doReset function is called from controller.js file.

We are validating the contact by using standard javascript reduce function. The standard showHelpMessageIfInvalid() throws the error message for the lightning:input where value is missing or pattern is not matched.

You can get the details in the reference link: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/data_service_example.htm#data_service_example

Step 2: That’s it. Now just add this component into the Lightning record Page of an Account.

Results

Notes

1.

<force:recordData aura:id="accountRecordLoaderId"
        recordId="{!v.recordId}"
        fields="Name"
        targetRecord="{!v.account}"
        targetFields="{!v.loadedAccountFields}"
        targetError="{!v.accountError}"
    />

This is responsible to collect account name with respect to record Id.

2.

<force:recordData aura:id="contactRecordCreatorId"
        layoutType="FULL"
        targetRecord="{!v.newContact}"
        targetFields="{!v.newContactFields}"
        targetError="{!v.newContactError}" 
    /> 

This is responsible to create contact record. Please notice that, we have used layoutType instead of using fields. So, at the time of definition of Contact fields in the form, we can use any field resides on the Contact Object.

3. In createContactByLDSController.js file, we have set the Account Id of Contact just like component.set(“v.newContactFields.AccountId”, component.get(“v.recordId”)).

4. In createContactByLDSHelper.js file, we need to declare the instantiation of the Contact Record in the “openNewContact” function at Client Side for Lightning Data Service.

In the same file, we have used “validateContactForm” function to validate the Contact form.

1,044 total views, 4 views today

Rating: 5.0/5. From 1 vote.
Please wait...

You may also like...