- Salesforce Blogs -

Salesforce Lightning Tutorial For Beginners

The topics that we are going to cover in this blog will help you understand the new approach of Salesforce, Salesforce Lightning Component using which you can built easy and interactive CRM applications. Before getting started to the tutorial, let us understand-

Why should you learn Salesforce Lightning?

Salesforce Lightning includes Lightning component framework, which includes really exciting tools for the Salesforce developers. It makes it easier to build responsive applications for any device within fewer amounts of time and effort. Also, it provides a client-server framework that speeds up the development and improvise the application performance. On the other hand, the Salesforce Lightning App Builder gives you the power to build visual applications without using code, which is quicker than ever before using custom-built Lightning components. Lightning components can be used in Lightning App Builder so that admin can build custom user interface without using code.

Now, you must be wondering why Salesforce Lightning component is so popular and why everyone is talking about it? Well, here is your answer-

Salesforce Lightning is-

  • Out-of-the-box component set
  • Performance
  • Event-driven architecture
  • Faster development
  • Device-aware
  • Cross-browser compatibility, etc.

Introduction to Salesforce Lightning Platform

Salesforce Lightning is the upgraded version of Salesforce classic. It combines Lightning Design System (LDS), Lightning Tap Builder, and Lightning Components to create modern enterprise applications. It can be very useful in the generation of leads, improving sales, closure of deals, marketing domain, customer service analysis, etc.

Salesforce Lightning Layout in Salesforce is given below: -

Salesforce Lightning has three main types. Salesforce 1 was introduced for mobile application and two-user interface for the desktop version, whereas, Salesforce Classic and Salesforce Lightning Experience has been introduced by Salesforce dot com.

Salesforce Lightning Classic

Actually, Salesforce Lightning Classic is an older UI of Lightning. Here, SF developer can get customized dashboards and landing page components.

Salesforce Lightning Experience

Salesforce Lightning Experience or LEX, in short, brings an entirely new client-side architecture which departs from server-side rendering for its predecessor (that is Salesforce Classic) and Visualforce. It is for the first time, Salesforce developers can now use the same technology, and theme Salesforce has used to build their LEX based applications, known as the Lightning Framework. Salesforce has also chosen to open source their styling framework used by Lightning, which is known as the Lightning Design System (LDS).

Features of Salesforce Lightning Experience (LEX)

  • Salesforce Lightning Experience is a modern, fast, and intelligent user interface
  • It is built with a sales-centric mindset, focusing on helping sales representatives work more naturally daily
  • With Lightning Experience, Salesforce users will get an intuitive and intelligent user interface
  • Lightning Experience is built with proven Salesforce1 Mobile App technology
  • Sales representatives can use mobiles to enter customers details like log tasks and notes after client meetings, run reports and dashboards, and many more. All these features from the mobile are being brought into the computer web browser by Salesforce Lightning Experience

Salesforce Lightning Component

Components are said to be self-contained and reusable units of an application. Any lighting application built using these small Salesforce Lightning Components and these components is reusable. But remember-

  • Lightning components have .cmp extensions
  • Lightning components are based on the concept of web components
  • It uses Apex, JavaScript, HTML, and CSS to build Salesforce lightning app

What is Lightning in Salesforce?

Lightning in Salesforce is a component-based framework for application development using SFDC that is used to design processes for business users who do not have any prior programming experience. Lightning contains a collection of tools and technologies afterward upgrade to the Salesforce1 platform.

Benefits of Salesforce Lightning

  • Grouped Record View: Drive the right behaviors at every stage of your sales process with a Grouped view for record pages. Reps work their deals more efficiently with opportunities that promote the right action at the right time. Accounts and contacts drive customer insights, easy access to details, and clean data with field-level duplicate matching.
  • Activity Timeline: See open tasks, planned meetings, and accomplishments in the activity timeline on activity-enabled objects. Quickly log calls, create tasks, send emails, and more from the handy composer.
  • Task Lists: See details about specific tasks alongside the full list of open tasks, tasks due today, and closed tasks. Managers see tasks assigned to people below them in the role hierarchy.
  • Enhanced Notes: Take better notes with auto-save, rich text capabilities, inline images, and versioning. Relate a note to multiple records and share notes with teammates or Chatter groups.
  • Integrated Email: Related email messages to multiple contacts, leads, and users, and to a single opportunity, campaign, case, account, or person account. Send an email through Gmail or Office 365 accounts with your Salesforce email. And see the email messages you’ve sent in your Gmail or Office 365 Sent Items folder for flawless integration.
  • Composer Windows: Breeze through those minor but important activities that inevitably crop up during the day without switching context. Quickly log calls, create tasks and events, and jot down notes, all from windows that open on the current page.
  • File Preview Player: Enjoy a richer file preview experience that doesn’t require Adobe Flash Player. Vector-based preview images render in higher quality and don’t degrade on high-resolution screens, plus they load faster. Scroll through multi-page documents, preview animated GIFs, give full-screen presentations, and access file actions.
  • Live Feeds: See live posts in group feeds and live comments in all feeds without refreshing the page. See who’s commenting while they’re typing.
  • Post Pinning: Highlight high-impact posts that otherwise get buried in a busy feed by pinning them to the top of group and topics feed.
  • Draft Posts: Draft posts are automatically saved to the My Drafts feed every seven seconds. Review, edit, post, or delete drafts.
  • Reports and Dashboards: Get more from your data. The report run page is easy to read and filter. Animated, interactive charts bring your company’s data to life. And a new dashboard editor supports flexible layouts and components that span columns and rows.
  • Favorites: Create shortcuts to frequently accessed pages, including records, lists, and groups.
  • List Views: Seamlessly create and edit custom list views to quickly find relevant data. Search on-the-fly for specific list views. Visualize data with handy list view charts, or apply filters to slice the data as needed.
  • Search: Find records faster with improved global search, which includes top results and recent records.
  • Setup Tree and Object Manager; Navigate setup pages with a simplified organization and a cleaner look and feel. Use the Object Manager, which combines all standard and custom objects into a single list that’s easier to search.

Salesforce Lightning Framework

Salesforce Lightning Component is a User Interface (UI) based framework developed to create dynamic Salesforce web applications for mobile and desktop devices. Lightning components are built by a Salesforce Developer, and those components are then assembled by Salesforce administrator to form a Salesforce Lightning page. The Salesforce Lightning Framework is most popular because of the following reasons: -

  1. Salesforce Lightning component Framework provides the components to build applications faster. No need to begin from scratch.
  2. Salesforce Lightning component Framework tacks browser outlets when a user clicks a button, scrolling, and many more.
  3. Our components can be published and shared with other Salesforce users.
  4. It used JSON to exchange data between the server and the client.
  5. Salesforce Lightning Component Framework supports the latest browser technologies like HTML5, CSS3, and touch events.

Salesforce Lightning Component

Let me clear here that Salesforce Lightning Component Framework is build using open source Aura framework. Open Source means something that has free availability. Whilst building Salesforce Lightning application, Aura keyword is used many times. See example below:-

Read: How to Merge Accounts & Duplicate Contacts in Salesforce lightning?

Salesforce Lightning Component

Salesforce Lightning Page

Salesforce Lightning page is a custom layout that lets you design pages for the use in the Salesforce mobile app or Salesforce Lightning Experience.

Salesforce Lightning pages occupy a middle ground between page layouts and Visualforce pages. Like a page layout, Lightning pages allow you to add custom items to a page. However, these items, instead of being fields or Visualforce components, are Lightning components, which allow much more flexibility.

The structure of a Lightning page revamps for the device on which it is viewed. The Lightning page’s template divides the page into various regions-

Salesforce Lightning Page

Lightning pages are built using Lightning components—compact, configurable, and reusable elements that you can drag and drop into regions of the page in the Lightning App Builder.

You can use Salesforce Lightning page to create an application page which you can add to the Salesforce mobile application navigation list or a Lightning application’s navigation bar. An application page gives quick access to the objects and items that are most important in the Salesforce application.

You can also use a Salesforce Lightning page to create a customized record or homepage for Salesforce Lightning Experience. If you have integrated Salesforce with Microsoft Outlook or Gmail, you can create a customized email application pane.

If you have a console app, you can create a Lightning page with pinned regions to let your users view and work with records while navigating between subtabs.

Salesforce Lightning Page

Lightning pages support the following components:

Standard Components

Standard components are Lightning components built by Salesforce.

  • Required Editions-
  • Lightning App Builder available in: both Salesforce Classic and Lightning Experience
  • Lightning record, Home, and utility bar pages available in Lightning Experience
  • Lightning app pages available in: both the Salesforce mobile app and Lightning Experience
  • Email application pane pages available in: both Salesforce Classic and Lightning Experience

Available in: GroupProfessionalEnterprisePerformanceUnlimited, and Developer Editions

Custom Components

Custom components are Lightning components that you or someone else has created. With some configuration, custom Lightning components can work in the Lightning App Builder.

Read: Salesforce CRM vs. SAP CRM- Which One is Better?

Required Editions-

  • Lightning App Builder is available in both Salesforce Classic and Lightning Experience
  • Lightning record, Home, and utility bar pages are available in Lightning Experience
  • Lightning app pages are available in both the Salesforce mobile app and Lightning Experience
  • Email application pane pages are available in both Salesforce Classic and Lightning Experience

Available in: GroupProfessionalEnterprisePerformanceUnlimited, and Developer Editions

Third-Party Components on AppExchange

The AppExchange provides a marketplace for Lightning components. You can find packages containing components already configured and ready to use in the Lightning App Builder.

Let’s play with some Salesforce Lightning miscellaneous code

Lightning App Builder

It represents a responsive grid system for the arrangement of containers on a page. A lightning:layout is a flexible grid system for arranging containers within a page or inside another container. The default layout is mobile-first and it can be easily configured to work on different devices.

Sample Code:

<aura:component implements="flexipage:availableForAllPageTypes" >
<div class="c-container">
<lightning:layout horizontalAlign="center">
<lightning:layoutItem flexibility="auto" padding="around-small">
<ui:inputSelect multiple="false">
<ui:inputSelectOption label="All Types" text="" value="true"/>
</ui:inputSelect>
</lightning:layoutItem>
<lightning:layoutItem flexibility="auto" padding="around-small">
<button class="slds-button slds-button_brand">Search</button>
</lightning:layoutItem>
<lightning:layoutItem flexibility="auto" padding="around-small">
<ui:button label="New"/>
</lightning:layoutItem>
</lightning:layout>
</div>

</aura:component>

Output:

Salesforce Lightning Page

Lightning datatable in Salesforce Lightning Component

AccountList.cmp:

<aura:component controller="AccountListController"
implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable" >

<aura:attribute type="Account[]" name="acctList"/>
<aura:attribute name="mycolumns" type="List"/>

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

<lightning:datatable data="{! v.acctList }"
columns="{! v.mycolumns }"
keyField="id"
hideCheckboxColumn="true"/>

</aura:component>

AccountListController.js

({
fetchAccounts : function(component, event, helper) {
component.set('v.mycolumns', [
{label: 'Account Name', fieldName: 'Name', type: 'text'},
{label: 'Industry', fieldName: 'Industry', type: 'text'},
{label: 'Type', fieldName: 'Type', type: 'Text'}
]);
var action = component.get("c.fetchAccts");
action.setParams({
});
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.acctList", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})

AccountListController Apex Class:

public class AccountListController {
@AuraEnabled
public static List < Account > fetchAccts() {
return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
}
}

Output:

Salesforce Lightning Page

Sorting or Data Table in Salesforce

AccountList.cmp

Read: Difference Between Salesforce and Servicenow
<aura:component controller="AccountListController"
implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable" >

<aura:attribute type="Account[]" name="acctList"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:attribute name="sortedBy" type="String" default="Name"/>
<aura:attribute name="sortedDirection" type="String" default="asc"/>

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

<lightning:datatable data="{!v.acctList}"
columns="{!v.mycolumns}"
keyField="id"
hideCheckboxColumn="true"
onsort="{!c.updateColumnSorting}"
sortedBy="{!v.sortedBy}"
sortedDirection="{!v.sortedDirection}"/>
</aura:component>

AccountListController.js

({
fetchAccounts : function(component, event, helper) {
component.set('v.mycolumns', [
{label: 'Account Name', fieldName: 'Name', type: 'text', sortable: true},
{label: 'Industry', fieldName: 'Industry', type: 'text'},
{label: 'Type', fieldName: 'Type', type: 'Text'}
]);
var action = component.get("c.fetchAccts");
action.setParams({
});
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.acctList", response.getReturnValue());
helper.sortData(component, component.get("v.sortedBy"), component.get("v.sortedDirection"));
}
});
$A.enqueueAction(action);
},
updateColumnSorting: function (cmp, event, helper) {
var fieldName = event.getParam('fieldName');
var sortDirection = event.getParam('sortDirection');
cmp.set("v.sortedBy", fieldName);
cmp.set("v.sortedDirection", sortDirection);
helper.sortData(cmp, fieldName, sortDirection);
}
})

AccountListHelper.js:

({
sortData: function (cmp, fieldName, sortDirection) {
var data = cmp.get("v.acctList");
var reverse = sortDirection !== 'asc';
data.sort(this.sortBy(fieldName, reverse))
cmp.set("v.acctList", data);
},
sortBy: function (field, reverse, primer) {
var key = primer ?
function(x) {return primer(x[field])} :
function(x) {return x[field]};
reverse = !reverse ? 1 : -1;
return function (a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
})

AccountListController apex class:

public class AccountListController {
@AuraEnabled
public static List < Account > fetchAccts() {
return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
}
}

Output:

How to handle attribute value modification in Salesforce Lightning Components

The aura:valueChange event is used to handle attribute value change in lightning components in Salesforce.
Component:

<aura:component implements="force:appHostable">
<aura:handler name="change" value="{!v.strText}" action="{!c.handleValueChange}"/>
<aura:attribute name="strText" type="string" default="Sample"/>
<div class="slds-box slds-theme_default">
<lightning:input value="{!v.strText}" type="text" label="Text"/><br/>
<lightning:button variant="brand" label="Update" onclick="{!c.clickIt}"/>
</div>
</aura:component>

Controller:

({
clickIt : function(component, event, helper) {
component.set("v.strText", "Changing");
},

handleValueChange : function (component, event, helper) {
alert("Changed strText " + component.get("v.strText"));
}
})

Output: 

How to Display a Wrapper Class List in Salesforce Lightning Component?

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" controller="DPLightningHandler" >
<aura:attribute name="listVehicles" type="WrapperClass.VehicleWrapper[]" />

<ui:inputSelect aura:Id="makeId" multiple="false" label="Select Make">
<ui:inputSelectOption label="Acura" text="acura"/>
<ui:inputSelectOption label="Audi" text="Audi"/>
<ui:inputSelectOption label="BMW" text="bmw"/>
<ui:inputSelectOption label="Honda" text="honda"/>
<ui:inputSelectOption label="Hyundai" text="hyundai"/>
<ui:inputSelectOption label="Mercedes Benz" text="merc"/>
<ui:inputSelectOption label="Nissan" text="nissan"/>
</ui:inputSelect><br/><br/>
<ui:button label="Find Vehicles" press="{!c.findVehicles}"/><br/><br/>
<aura:renderIf isTrue="{!v.listVehicles.length > 0}">
<aura:if isTrue="{!v.listVehicles.length > 0}">
<table class="slds-table slds-table--bordered slds-table--cell-buffer slds-max-medium-table--stacked">
<thead>
<tr>
<th><h2>Vehicle Name</h2></th>
<th><h2>Vehicle Type</h2></th>
<th><h2>Make Id</h2></th>
<th><h2>Make Name</h2></th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.listVehicles}" var="veh">
<tr>
<td class="slds-truncate" data-label="Vehicle Name">{!veh.VehicleTypeName} </td>
<td class="slds-truncate" data-label="Vehicle Type">{!veh.VehicleTypeId}</td>
<td class="slds-truncate" data-label="Make Id">{!veh.MakeId}</td>
<td class="slds-truncate" data-label="Make Name">{!veh.MakeName}</td>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:if>
</aura:renderIf>
</aura:component>

Lightning Controller:

({
findVehicles : function(component, event, helper) {
var action = component.get("c.fetchInventory");
action.setParams({
vehicleMake : component.find("makeId").get("v.value")
});
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.listVehicles", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})

Apex Lightning Controller:

public with sharing class DPLightningHandler {

@AuraEnabled
public static List < WrapperClass.VehicleWrapper > fetchInventory(String vehicleMake) {
List < WrapperClass.VehicleWrapper > listVehicles = new List < WrapperClass.VehicleWrapper >();
HTTPRequest req = new HTTPRequest();
req.setEndPoint('https://vpic.nhtsa.dot.gov/api/vehicles/GetVehicleTypesForMake/' + vehicleMake + '?format=json');
req.setMethod('GET');
HTTP objHTTP = new HTTP();
HTTPResponse res = objHTTP.send(req);
system.debug('Response is ' + res.getBody());
JSONParser parser = JSON.createParser(res.getBody());
System.JSONToken token;
String text;
parser.nextToken(); // Eat first START_OBJECT {
parser.nextToken(); // Eat token = FIELD_NAME; text = postalcodes
parser.nextToken(); // Eat first START_ARRAY [
parser.nextToken(); // Eat the first object's START_OBJECT {
WrapperClass.VehicleWrapper obj;
while ( ( token = parser.nextToken()) != null ) {
if ( ( token = parser.getCurrentToken() ) != JSONToken.END_OBJECT ) {
text = parser.getText();
if ( token == JSONToken.FIELD_Name && text == 'MakeId' ) {
token = parser.nextToken();
obj = new WrapperClass.VehicleWrapper();
obj.MakeId = parser.getText();
} else if (token == JSONToken.FIELD_Name && text == 'MakeName' ) {
token = parser.nextToken();
obj.MakeName = parser.getText();
} else if ( token == JSONToken.FIELD_Name && text == 'VehicleTypeId' ) {
token = parser.nextToken();
obj.VehicleTypeId = parser.getText();
} else if ( token == JSONToken.FIELD_Name && text == 'VehicleTypeName' ) {
token = parser.nextToken();
obj.VehicleTypeName = parser.getText();
listVehicles.add(obj);
}
}
}
system.debug('listVehicles are ' + listVehicles);
return listVehicles;
}
}

Apex Wrapper Class:

public class WrapperClass {
public class VehicleWrapper {
@AuraEnabled
public String MakeId {get;set;}
@AuraEnabled
public String MakeName {get;set;}
@AuraEnabled
public String VehicleTypeId {get;set;}
@AuraEnabled
public String VehicleTypeName {get;set;}
}
}

Output:

Salesforce Lightning Page

Conclusion

Salesforce is the dynamic provider of CRM applications in the world. The applications developed using Salesforce Lighting are easy to interact and are screen friendly as they can be used on desktop, mobile, or in tablets. It provides out-of-the-box components, event-driven architecture, architecture-driven framework, and better optimization option as compared to the older versions of Salesforce.

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course