Standard Controller For Lightning Component Part II

In this tutorial, we will learn how to create, update and delete records using Lightning Data Services.

Creating Records

To create an empty record, leave the recordId attribute in force:recordData undefined.

We will create a Quick Contact Using LDS in this example we will not Link this contact with any account but you can Link this contact using 2 force:recordData tags in same component one for Account and one for Contact and Component must be placed into Account Layout either as Quick Action or into detail page.

Create a new Lightning Component and name it ldsCreateRecord.cmp and paste the below code.

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

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

<force:recordData aura:id="contactRecordCreator"
targetFields ="{!v.simpleNewContact}"

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

<!-- Display a header -->
<div class="slds-page-header" role="banner">
<p class="slds-text-heading--label">Create Contact</p>

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

<!-- Display the new contact form -->
<div class="slds-form--stacked">
		<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:button label="Save contact" onclick="{!c.handleSaveContact}"
variant="brand" class="slds-m-top--medium"/></div>

Save, Click on Controller from right side and then paste the below code.


doInit: function(component, event, helper) {
// Prepare a new record from template
"Contact", // sObject type (entityAPIName)
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") {
// record is saved successfully
var resultsToast = $A.get("e.force:showToast");
"title": "Saved",
"message": "The record was saved."

} 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: ' +
} else {
console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));


validateContactForm: function (cmp) {
var allValid = cmp.find('contactField').reduce(function (validSoFar, inputCmp) {
return validSoFar &amp;amp;amp;amp;&amp;amp;amp;amp; inputCmp.get('v.validity').valid;
}, true);
if (allValid) {
//alert('All form entries look valid. Ready to submit!');
return allValid;
} else {
//alert('Please update the invalid form entries and try again.');
return false;


Deleting Records

Finally, to delete a record, specify the recordId with the fields attribute set to “Id” at a minimum.


<aura:component implements=”flexipage:availableForRecordHome,force:hasRecordId”>

<aura:attribute name=”recordError” type=”String” access=”private”/>

<force:recordData aura:id=”recordHandler”

<!– Display Lightning Data Service errors, if any –>
<aura:if isTrue=”{!not(empty(v.recordError))}”>



<!– Display the delete record form –>

label=”Delete Record”
variant=”brand” />




handleDeleteRecord: function(component, event, helper) {
component.find("recordHandler").deleteRecord($A.getCallback(function(deleteResult) {
if (deleteResult.state === "SUCCESS" || deleteResult.state === "DRAFT") {
console.log("Record is deleted.");
else if (deleteResult.state === "INCOMPLETE") {
console.log("User is offline, device doesn't support drafts.");
else if (deleteResult.state === "ERROR") {
console.log('Problem deleting record, error: ' + JSON.stringify(deleteResult.error));
else {
console.log('Unknown problem, state: ' );


Standard Controller For Lightning Component Part I

What Is Lightning Data Service?

Lightning Data Service (LDS) to serve as the data layer for Lightning. LDS is the Lightning Components. We can compare LDS with Visualforce standard controller, providing access to the data displayed on a Component. Without LDS, each component within an app makes independent calls to the server to perform CRUD operations on a record, even if all components in the app pull from the same record data

Without LDS, each component within an app makes independent calls to the server to perform CRUD operations on a record, even if all components in the app pull from the same record data and making server class reduces the performance of the page.

Using LDS we can eliminate requests that involve the same record data, sending a single shared data request that updates all relevant components.

  • Minimize XMLHttpRequests (XHR’s)
  • Fetch records once, reducing network transfers, app server load, and database server load
  • Cache record data on the client, separate from component metadata
  • Share record data across components
  • Enable progressive record loading, caching, and merging more fields and layouts into the cache
  • Enable proactive cache population
  • Promote consistency by using only one instance of the record data across multiple components
  • Create notifications when record data changes

Enough is Enough we have done a lot of theory and it’s time to do some magic with LDS 🙂 🙂

Meet Lightning Component Standard Controller (force:recordData): –

So, how do you access benefits of LDS? Simple all you need is just to include force:recordData in your component OK!

<force:recordData aura:id=”forceRecordCmp”

Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of the tag.
fields ArrayList Specifies which of the record’s fields to query.  The layoutType and/or fields attribute must be specified.
layoutType String Name of the layout to query, which determines the fields included. Valid values are FULL or COMPACT.  The layoutType and/or fields attribute must be specified.
mode String The mode in which to load the record: VIEW (default) or EDIT.
recordId String The record Id Populated with the loaded record
targetError String Will be set to the localized error message if the record can’t be provided.   Populated with any errors
targetFields Object A simplified view of the fields in targetRecord, to reference record fields in component markup.  Populated with the simplified view of the loaded record
targetRecord Object This attribute will contain only the fields relevant to the requested layoutType and/or fields attributes.

Below is Sample Code of display record using LDS. Create a Lightning Component and paste the below code add this component into any object Details Page.

<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId"> <!--inherit recordId attribute-->

<aura:attribute name="record" type="Object"
description="The record object to be displayed"/>
<aura:attribute name="simpleRecord" type="Object"
description="A simplified view record object to be displayed"/>
<aura:attribute name="recordError" type="String"
description="An error message bound to force:recordData"/>

<force:recordData aura:id="record"
targetFields ="{!v.simpleRecord}"
<!-- Display a header with details about the record -->
<div class="slds-page-header" role="banner">
<p class="slds-text-heading--label">{!v.simpleRecord.Name}</p>

<h1 class="slds-page-header__title slds-m-right--small
lds-truncate slds-align-left">{!v.simpleRecord.BillingCity},
<!-- Display Lightning Data Service errors, if any -->
<aura:if isTrue="{!not(empty(v.recordError))}">
<div class="recordError">
<ui:message title="Error" severity="error" closable="true">


Here’s a quick overview of the methods you can use in your JavaScript component controllers.

  • saveRecord() inserts or updates the record loaded into the force:recordData component.
  • deleteRecord() deletes the loaded record.
  • getNewRecord() loads a new record template that performs an insert when saved.
  • reloadRecord() reruns the loading code to overwrite the current targetRecord with the current attribute values.



Create First Lightning Component

Create Your First Lightning Component

In this article, we will learn how to create a first lightning component with all the basic component description.

Prerequisite: – 

  1. Lightning Experience must be enabled.
  2. My Domain Must be enabled and deployed. Click here to set up one if you do not already have one.

As most of you know that lightning is future of salesforce and sometimes we need the customized solution in order to achieve our business requirement. Lightning Component basically runs on Aura framework. So, Follow the below steps to create your own lightning component.

Step 1- Click on your name and then Open Developer Console into New Window

Step 1

Step 2 – Click on File -> New -> Lightning Component -> Name it FirstComponent and Click Submit. It will open a development workspace where we can develop/put HTML or predefined aura tags.

Setp 2

Step 3 – Files that each component includes

  • Component – Component is Client side XML markup which we use to display the details to our users using different aura tags or with the help of standard HTML tags.
  • Controller – Controller is Javascript file which is being used as Client side controller and this is middleware between apex controller and component.
  • Helper – Helper is also a javascript and work in client-side, we put those methods in the helper that are reusable like putting validation or any method which we are calling from multiple components. One helper can be used in between multiple components you can also say it like utility class.
  • Style – Style is used to put all our CSS here that we may use to styling our lightning component.
  • Documentation – A description, sample code, and one or multiple references to example component.
  • Renderer  – Client-side renderer to override default rendering for a component.
  • Design – If we want some predefined attribute values while using our component in Community, lightning App builder then we use Design attribute.
  • SVG – Custom icon resource for components used in the Lightning App Builder or Community Builder.

Step 3

Step 4 –  Write Static text into your Component. Put “This is My First Lightning Component” between <aura:component> opening and closing tags.

Step 4

Step 5 – Test your component, to test we will create a Lightning App. File -> New -> Lightning Application -> Name it FirstComponentApp -> Submit. Incorporate you component into app and Click preview to see the output. Put <c:FirstComponent></c:FirstComponent> between <aura:application> openting tags, save and Click Preview.

Step 4

Step 5

Step 5

Woohoo, you have just created your first lightning component. In next blog, we will learn how to use variables in lightning component and dynamic variable bindings.

Use Your component as Record, Home and App page

Until Summer 17 we can only use Standard Lightning pre define Templates as Record Detail Page, Homepage, and App home page. And now the big news coming after Winter 18 release, you can use your own custom Component as Homepage, Record Details page, and App homepage by adding new interfaces to your components!

Yeaahh! You can use your own custom solution now!

The following interfaces are new and can be used as per requirement: –

  • lightning:appHomeTemplate – Enables a component to be used as a custom Lightning page template for pages of type App Page. for Example <aura:component implements=”lightning:appHomeTemplate“> </aura:component>
  • lightning:homeTemplate – Enables a component to be used as a custom Lightning page template for the Lightning Experience Home page. Example: –  <aura:component implements=”lightning:homeTemplate“> </aura:component>
  • lightning:recordHomeTemplate – Enables a component to be used as a custom Lightning page template for record pages. Example: –  <aura:component implements=”lightning:recordHomeTemplate“> </aura:component>


Reference: – New and Changed Lightning Interfaces