Newer Version Available

This content describes an older version of this product. View Latest

Lightning Data Service Example

Here’s a longer, more detailed example of using Lightning Data Service to create a Quick Contact action panel.

Example

This example is intended to be added as a Lightning action on the account object. Clicking the action’s button on the account layout opens a panel to create a new contact.Example of Lighning action using Lightning Data Services

This example is similar to the example provided in Configure Components for Record-Specific Actions. Compare the two examples to better understand the differences between using @AuraEnabled Apex controllers and using Lightning Data Service.

ldsQuickContact.cmp
1<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">
2
3    <aura:attribute name="account" type="Object"/>
4    <aura:attribute name="simpleAccount" type="Object"/>
5    <aura:attribute name="accountError" type="String"/>
6    <force:recordData aura:id="accountRecordLoader"
7        recordId="{!v.recordId}"
8        fields="Name,BillingCity,BillingState"
9        targetRecord="{!v.account}"
10        targetFields="{!v.simpleAccount}"
11        targetError="{!v.accountError}"
12    />
13
14    <aura:attribute name="newContact" type="Object" access="private"/>
15    <aura:attribute name="simpleNewContact" type="Object" access="private"/>
16    <aura:attribute name="newContactError" type="String" access="private"/>
17    <force:recordData aura:id="contactRecordCreator"
18        layoutType="FULL"
19        targetRecord="{!v.newContact}"
20        targetFields="{!v.simpleNewContact}"
21        targetError="{!v.newContactError}"
22        />
23
24    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
25
26    <!-- Display a header with details about the account -->
27    <div class="slds-page-header" role="banner">
28        <p class="slds-text-heading_label">{!v.simpleAccount.Name}</p>
29        <h1 class="slds-page-header__title slds-m-right_small
30            slds-truncate slds-align-left">Create New Contact</h1>
31    </div>
32
33    <!-- Display Lightning Data Service errors, if any -->
34    <aura:if isTrue="{!not(empty(v.accountError))}">
35        <div class="recordError">
36            <ui:message title="Error" severity="error" closable="true">
37                {!v.accountError}
38            </ui:message>
39        </div>
40    </aura:if>
41    <aura:if isTrue="{!not(empty(v.newContactError))}">
42        <div class="recordError">
43            <ui:message title="Error" severity="error" closable="true">
44                {!v.newContactError}
45            </ui:message>
46        </div>
47    </aura:if>
48
49    <!-- Display the new contact form -->
50     <lightning:input aura:id="contactField" name="firstName" label="First Name"
51                     value="{!v.simpleNewContact.FirstName}" required="true"/>
52  
53    <lightning:input aura:id="contactField" name="lastname" label="Last Name"
54                  value="{!v.simpleNewContact.LastName}" required="true"/>
55            
56    <lightning:input aura:id="contactField" name="title" label="Title"
57                  value="{!v.simpleNewContact.Title}" />
58    
59    <lightning:input aura:id="contactField" type="phone" name="phone" label="Phone Number"
60                     pattern="^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$"
61                     messageWhenPatternMismatch="The phone number must contain 7, 10, or 11 digits. Hyphens are optional."
62                   value="{!v.simpleNewContact.Phone}" required="true"/>
63    
64    <lightning:input aura:id="contactField" type="email" name="email" label="Email"
65                value="{!v.simpleNewContact.Email}" />
66        
67    <lightning:button label="Cancel" onclick="{!c.handleCancel}" class="slds-m-top_medium" />
68    <lightning:button label="Save Contact" onclick="{!c.handleSaveContact}"
69               variant="brand" class="slds-m-top_medium"/>
70     
71    
72</aura:component>
ldsQuickContactController.js
1({
2    doInit: function(component, event, helper) {
3        component.find("contactRecordCreator").getNewRecord(
4            "Contact", // objectApiName
5            null, // recordTypeId
6            false, // skip cache?
7            $A.getCallback(function() {
8                var rec = component.get("v.newContact");
9                var error = component.get("v.newContactError");
10                if(error || (rec === null)) {
11                    console.log("Error initializing record template: " + error);
12                }
13                else {
14                    console.log("Record template initialized: " + rec.sobjectType);
15                }
16            })
17        );
18    },
19
20    handleSaveContact: function(component, event, helper) {
21        if(helper.validateContactForm(component)) {
22            component.set("v.simpleNewContact.AccountId", component.get("v.recordId"));
23            component.find("contactRecordCreator").saveRecord(function(saveResult) {
24                if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
25
26                    // Success! Prepare a toast UI message
27                    var resultsToast = $A.get("e.force:showToast");
28                    resultsToast.setParams({
29                        "title": "Contact Saved",
30                        "message": "The new contact was created."
31                    });
32
33                    // Update the UI: close panel, show toast, refresh account page
34                    $A.get("e.force:closeQuickAction").fire();
35                    resultsToast.fire();
36
37                    // Reload the view so components not using force:recordData
38                    // are updated
39                    $A.get("e.force:refreshView").fire();
40                }
41                else if (saveResult.state === "INCOMPLETE") {
42                    console.log("User is offline, device doesn't support drafts.");
43                }
44                else if (saveResult.state === "ERROR") {
45                    console.log('Problem saving contact, error: ' +
46                                 JSON.stringify(saveResult.error));
47                }
48                else {
49                    console.log('Unknown problem, state: ' + saveResult.state +
50                                ', error: ' + JSON.stringify(saveResult.error));
51                }
52            });
53        }
54    },
55
56    handleCancel: function(component, event, helper) {
57        $A.get("e.force:closeQuickAction").fire();
58    },
59})

The callback passed to getNewRecord() must be wrapped in $A.getCallback() to ensure correct access context when the callback is invoked. If the callback is passed in without being wrapped in $A.getCallback(), any attempt to access private attributes of your component results in access check failures.

Even if you’re not accessing private attributes, it’s a best practice to always wrap the callback function for getNewRecord() in $A.getCallback(). Never mix (contexts), never worry.

Note

ldsQuickContactHelper.js
1({
2    validateContactForm: function(component) {
3        var validContact = true;
4
5         // Show error messages if required fields are blank
6        var allValid = component.find('contactField').reduce(function (validFields, inputCmp) {
7            inputCmp.showHelpMessageIfInvalid();
8            return validFields && inputCmp.get('v.validity').valid;
9        }, true);
10
11        if (allValid) {
12            // Verify we have an account to attach it to
13            var account = component.get("v.account");
14            if($A.util.isEmpty(account)) {
15                validContact = false;
16                console.log("Quick action context doesn't have a valid account.");
17            }
18        	return(validContact);
19            
20        }  
21	}
22       
23})