Creating a Record using Lightning Data Service

Creating a Record using Lightning Data Service

To create a record using Lightning Data Service, declare force:recordData without assigning a recordId. Next, load a record template by calling the getNewRecord function on force:recordData. Finally, apply values to the new record, and save the record by calling the saveRecord function on force:recordData.

QuickCreateAccount.cmp:
<aura:component implements=”force:lightningQuickAction”>
    
    <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>
    
    <aura:attribute name=”newAccount” type=”Object”/>
    <aura:attribute name=”newAccountError” type=”String”/>
    <aura:attribute name=”simpleNewAccount” type=”Object”/>


<force:recordData aura:id=”accountRecordCreator”
                      layoutType=”FULL”
                      targetRecord=”{!v.newAccount}”
                      targetFields=”{!v.simpleNewAccount}”
                      fields=”Name,Industry,Type”
                      targetError=”{!v.newAccountError}”
                      mode=”New”/>
    <div class=”slds-page-header” role=”banner”>
        <p class=”slds-text-heading_label”>Create Account</p>
    </div>


    <!– Display Lightning Data Service errors –>
    <aura:if isTrue=”{!not(empty(v.newAccountError))}”>
        <div class=”recordError”>
            <ui:message title=”Error” severity=”error” closable=”true”>
                {!v.newAccountError}
            </ui:message>
        </div>
    </aura:if>


    <!– Display the new Account form –>
    <div class=”slds-form_stacked”>
        <lightning:input name=”name” label=”Name”
                         value=”{!v.simpleNewAccount.Name}” required=”true”/>
      
        <lightning:input name=”industry” label=”Industry”
                      value=”{!v.simpleNewAccount.Industry}” required=”true”/>
                
        <lightning:input name=”type” label=”Type”
                      value=”{!v.simpleNewAccount.Type}” />
                      
        <lightning:button label=”Save Account” onclick=”{!c.handleSaveAccount}”
                   variant=”brand” class=”slds-m-top_medium”/>
   </div>


</aura:component>

QuickCreateAccountController.js:

({
    doInit: function(component, event, helper) {
        // Prepare a new record from template
        component.find(“accountRecordCreator”).getNewRecord(
            “Account”, // sObject type 
            null,      // recordTypeId
            false,     // skip cache?
            $A.getCallback(function() {
                var rec = component.get(“v.newAccount”);
                var error = component.get(“v.newAccountError”);
                if(error || (rec === null)) {
                    console.log(“Error initializing record template: ” + error);
                    return;
                }
                console.log(“Record template initialized: ” + rec.sobjectType);
            })
        );
    },


    handleSaveAccount: function(component, event, helper) {
        component.find(“accountRecordCreator”).saveRecord(function(saveResult) {
            if (saveResult.state === “SUCCESS” || saveResult.state === “DRAFT”) {
                // handle the successful create
            } else if (saveResult.state === “INCOMPLETE”) {
                // handle the incomplete state
                console.log(“User is offline, device doesn’t support drafts.”);
            } else if (saveResult.state === “ERROR”) {
                // handle the error state
                console.log(‘Problem saving contact, error: ‘ + JSON.stringify(saveResult.error));
            } else {
                console.log(‘Unknown problem, state: ‘ + saveResult.state + ‘, error: ‘ + JSON.stringify(saveResult.error));
            }
        });
    }
})

Quick Action Button in Account:

1. Add the Quick Action to the Account Page Layout.

2. Open an Account record.

3. Click Quick Create Account.

Output:


Leave a Reply