ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Lightning Data Service

Home / Article & Blogs / Salesforce / Lightning / Lightning Data Service
By rawatharsh inLightning

Overview

One of the big changes developers face when moving from the Visualforce world into Lightning components is how to communicate with the server. Up until the Summer ’17 release, this meant creating an Apex class to do anything—even simple CRUD interactions that were handled “automagically” in Visualforce. With the Summer ’17 release and the introduction of Lightning Data Service, this all changed. So, for our component, we use Lightning Data Service to create a new property record—without writing Apex!

Goals

Perform SOQL and CRUD operation without help of APEX controller.

Description

Tag :-  force:recordData

Implements :- flexipage:availableForRecordHome, force:hasRecordId

Attributes :-

  1. aura:id : to identify the tag uniquely in js controller.
  2. recordId : to query the record we could pass the value over here
  3. layoutType : if we do not want to provide fields we could always use layout. It will identify the layout assigned to user profile and get the field values. Then it query all the fileds in layout. For layout there are two values:-
    1. COMPACT : The compact layout (popup layout) assigned to user.
    2. FULL : Actual record layout assigned to user.
  4. targetRecord : Component attribute in which we want to load the data. In other words lightning component variable.
  5. targetFields : Fields list to query (component object).
  6. fields : Fields list(comma separated) to query (hard coded).
  7. targetError : To show and handle error msgs
  8. recordUpdated : JS controller event to check the below events:
    1. LOADED : handle record load (SOQL)
    2. CHANGED : handle record change (onChange of data fields value)
    3. REMOVED : handle record removal (on delete the record)
    4. ERROR : handle error(We should handle this event first.)
  9. mode : EDIT to perform DML on record and VIEW to show record on UI.

Example :-

 

[code language=”html”]<force:recordData aura:id=”idToIdentifyTagUniquely”
recordId=”{!v.recordId}”
layoutType=”FULL”
targetRecord=”{!v.sObject_Attribut_Variable_to_hold_record}”
targetFields=”{!v.object_Attribut_Variable_contains_fields}”
targetError=”{!v.errorVariable}”
fields=”Id,Name,CreatedDate”
recordUpdated=”{!c.jsControllerMethod}”
/>[/code]

 

 

Actions

Creating a Record

To create a record using Lightning Data Service, declare force:recordData without assigning a recordId attribute value. If we also want to save the record we have to set the mode attribute value as EDIT.

  1. Events : Aura has defined below events:
    1. getNewRecord  : This event has been defined to create the variable in Component and init its value. It accepts below params.
      1. objectApiName : sObject API Name
      2. recordTypeId : recordTypeId if not applicable then “null”
      3. skipCache : true/false as required.
      4. callback : JS method to maintain callback.
    2. saveRecord : We will discuss this under save record section.

Loading a Record (in APEX language SOQL the record using Id)

To load a record in component variable we just need to specify the recordId attribute’s value. Along with id we could use targetFields attribute or layoutType attribute to specify the name of fields we want to SOQL.

Saving a Record (in APEX language UPSERT)

To save the record we have to load the recordData component in JS controller using aura Id and using that object we call saveRecord method.
SaveRecord method would be taking only callback method as parameter. In that method we would be having one parameter as saveResult, using the variable we could identify below states:

  1. SUCCESS : If the Upsert happened successfully.
  2. DRAFT : Its same as success.
  3. INCOMPLETE : User is offline, device doesn’t support drafts.
  4. ERROR : Problem saving record
  5. If no state is there we should handle that also.

saveResult object will contain below information:

  1. objectApiName : String – The object API name for the record.
  2. entityLabel : String – The label for the name of the sObject of the record.
  3. error : String – Error is one of the following:
    1. A localized message indicating what went wrong.
    2. An array of errors, including a localized message indicating what went wrong. It might also include further data to help handle the error, such as field- or page-level errors.
    3. error is undefined if the save state is SUCCESS or DRAFT.
  4. recordId : String – The 18-character ID of the record affected.
  5. state : String – The result state of the operation. We have already discussed the state values

Deleting a Record (in APEX language Delete)

To save the record we have to load the recordData component in JS controller using aura Id and using that object we call deleteRecord method.
DeleteRecord method would be taking only callback method as parameter. In that method we would be having one parameter as deleteResult, using the variable we could identify below states:

  1. SUCCESS : If the Delete happened successfully.
  2. DRAFT : Its same as success.
  3. INCOMPLETE : User is offline, device doesn’t support drafts.
  4. ERROR : Problem deleting record
  5. If no state is there we should handle that also.

Change Event Handler

To identify the changes made through data service we use change event handler.
For this we have to create one JS controller function and specify the function under recordUpdated attribute in force:recordData tag.
We have already discussed the events we need to handle in the Description section.

Example:

The UI :

212

The Lightning Page: ldsQuickContact.cmp

 

[code language=”html”]<aura:component implements=”force:lightningQuickActionWithoutHeader,force:hasRecordId”></pre>
<aura:attribute name=”account” type=”Object”/>
<aura:attribute name=”simpleAccount” type=”Object”/>
<aura:attribute name=”accountError” type=”String”/>
<force:recordData aura:id=”accountRecordLoader”
recordId=”{!v.recordId}”
fields=”Name,BillingCity,BillingState”
targetRecord=”{!v.account}”
targetFields=”{!v.simpleAccount}”
targetError=”{!v.accountError}”
/>

<aura:attribute name=”newContact” type=”Object” access=”private”/>
<aura:attribute name=”simpleNewContact” type=”Object” access=”private”/>
<aura:attribute name=”newContactError” type=”String” access=”private”/>
<force:recordData aura:id=”contactRecordCreator”
layoutType=”FULL”
targetRecord=”{!v.newContact}”
targetFields=”{!v.simpleNewContact}”
targetError=”{!v.newContactError}”
/>

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

<!– Display a header with details about the account –>
<div class=”slds-page-header” role=”banner”>
<p class=”slds-text-heading_label”>{!v.simpleAccount.Name}</p>

<h1 class=”slds-page-header__title slds-m-right_small
slds-truncate slds-align-left”>Create New Contact</h1>
</div>
<!– Display Lightning Data Service errors, if any –>
<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>

<!– Display the new contact form –>
<lightning:input aura:id=”contactField” name=”firstName” label=”First Name”
value=”{!v.simpleNewContact.FirstName}” required=”true”/>

<lightning:input aura:id=”contactField” name=”lastname” label=”Last Name”
value=”{!v.simpleNewContact.LastName}” required=”true”/>

<lightning:input aura:id=”contactField” name=”title” label=”Title”
value=”{!v.simpleNewContact.Title}” />

<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.simpleNewContact.Phone}” required=”true”/>

<lightning:input aura:id=”contactField” type=”email” name=”email” label=”Email”
value=”{!v.simpleNewContact.Email}” />

<lightning:button label=”Cancel” onclick=”{!c.handleCancel}” class=”slds-m-top_medium” />
<lightning:button label=”Save Contact” onclick=”{!c.handleSaveContact}”
variant=”brand” class=”slds-m-top_medium”/>

</aura:component>[/code]

JS Controller : ldsQuickContactController.js

 

[sourcecode language=”javascript”]

({
doInit: function(component, event, helper) {
component.find(“contactRecordCreator”).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);
}
})
);
},

handleSaveContact: function(component, event, helper) {
if(helper.validateContactForm(component)) {
component.set(“v.simpleNewContact.AccountId”, component.get(“v.recordId”));
component.find(“contactRecordCreator”).saveRecord(function(saveResult) {
if (saveResult.state === “SUCCESS” || saveResult.state === “DRAFT”) {

// Success! Prepare a toast UI message
var resultsToast = $A.get(“e.force:showToast”);
resultsToast.setParams({
“title”: “Contact Saved”,
“message”: “The new contact was created.”
});

// Update the UI: close panel, show toast, refresh account page
$A.get(“e.force:closeQuickAction”).fire();
resultsToast.fire();

// Reload the view so components not using force:recordData
// are updated
$A.get(“e.force:refreshView”).fire();
}
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));
}
});
}
},

handleCancel: function(component, event, helper) {
$A.get(“e.force:closeQuickAction”).fire();
},
})
[/sourcecode]

JS Helper : ldsQuickContactHelper.js

 

[sourcecode language=”javascript”]

({
validateContactForm: function(component) {
var validContact = true;

// Show error messages if required fields are blank
var allValid = component.find(‘contactField’).reduce(function (validFields, inputCmp) {
inputCmp.showHelpMessageIfInvalid();
return validFields inputCmp.get(‘v.validity’).valid;
}, true);

if (allValid) {
// Verify we have an account to attach it to
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);

}
}

})

[/sourcecode]

Example use :

We could use above component as a quick contact creator in Account detail page:

Untitled

Considerations

Lightning Data Service is powerful and simple to use. However, it’s not a complete replacement for writing your own data access code. Here are some considerations to keep in mind when using it.

Lightning Data Service is only available in Lightning Experience and the Salesforce app. Using Lightning Data Service in other containers, such as Lightning Components for Visualforce, Lightning Out, or Communities isn’t supported. This is true even if these containers are accessed inside Lightning Experience or the Salesforce mobile app, for example, a Visualforce page added to Lightning Experience.

Lightning Data Service supports primitive DML operations—create, read, update, and delete. It operates on one record at a time, which you retrieve or modify using the record ID. Lightning Data Service supports spanned fields with a maximum depth of five levels. Support for working with collections of records or for querying for a record by anything other than the record ID isn’t available. If you must support higher-level operations or multiple operations in one transaction, use standard @AuraEnabled Apex methods.

Lightning Data Service shared data storage provides notifications to all components that use a record whenever a component changes that record. It doesn’t notify components if that record is changed on the server, for example, if someone else modifies it. Records changed on the server aren’t updated locally until they’re reloaded. Lightning Data Service notifies listeners about data changes only if the changed fields are the same as in the listener’s fields or layout.

Lightning data service
101
Like this post
1 Post
rawatharsh

Search Posts

Archives

Categories

Recent posts

How To Upload A File To Google Drive Using LWC

How To Upload A File To Google Drive Using LWC

How To  Generate A PDF Using JSPDF In LWC

How To  Generate A PDF Using JSPDF In LWC

Create a No-Code Facebook Messenger Channel in the Service Cloud

Create a No-Code Facebook Messenger Channel in the Service Cloud

Salesforce Sales Cloud Features & Pricing

Salesforce Sales Cloud Features & Pricing

Salesforce Service Cloud: What Is It? And Its Features

Salesforce Service Cloud: What Is It? And Its Features

  • Previous PostReusable Lightning Notification On Record Update (Backend/API/UI) using Lightning Data service
  • Next PostCONGA-DOCUSIGN FOR SALESFORCE INTEGRATION WITH OUTBOUND MESSAGE

Related Posts

How Do We Import an External Library into Salesforce Lightning?
Lightning Salesforce

How Do We Import an External Library into Salesforce Lightning?

Difference Between Lightning Components and Lightning Web Components
Lightning Salesforce

Difference Between Lightning Components and Lightning Web Components

jQuery DataTable in Salesforce Lightning Component
Jquery Lightning Salesforce

jQuery DataTable in Salesforce Lightning Component

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE | CANADA

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT