Blog

Salesforce Lightning Components Tutorial

  • (4.0)
  • | 3753 Ratings

Introduction

Salesforce is a Cloud based Customer Relationship Management (CRM) platform. Its CRM applications are used for sales, service, marketing, and many more. As Salesforce is a cloud based platform, it is easy to implement and manage it. The Salesforce applications doesn’t require IT experts to manage or even setup them. You can just simply login and connect with your customers. Salesforce also has a vast and diverse community which helps companies with all the support required, starting from the development of application to its customization.

It has three major advantages, and they are:

  • Fastness: Salesforce will take few months to get the application deployed whereas custom built CRM may take years to get it deployed.
  • Easy to use: Salesforce is simple to use compared to complex custom CRM platform.
  • Effective: It is effective as it is more customizable according to the need.

In Salesforce, we have two methods to build an application, and they are:

Classic Salesforce Application Architecture: It is a client application by which you can use it over mobiles. Salesforce uses wireless carrier networks which will connect or exchange data from users to Salesforce. All the data is stored in the mobile, and data sent to mobile application depends on the configuration of the mobile.

Enthusiastic about exploring the skill set of Salesforce Lightning? Then, have a look at the Salesforce Lightning Training together additional knowledge.

Lightning Application Architecture: It is  a new approach towards application development. Using Lightning, we can develop an application which supports any device like mobile, desktops, or Tabs. Lightning application is moreover a dynamic approach towards application development where single page application will interact according to the user.

Due to its advantages, Salesforce lightning application’s  usage is more compared to Salesforce Classic. Slowly, all applications are moving from Salesforce Classic to Lightning application. As the trend has changed now, which is to have more easy and interactive application approach, companies are giving more importance to modern and dynamic approaches of the CRM application, which are fulfilled by the lightning application. Using Lightning application, you can get all the dynamism and easy-to-go approach for your CRM  application.

This Salesforce Tutorial will help you learn about the Lightning Component Architecture, creation of Lightning application and Lightning Component, and many other topics related to the Lightning Experience. 


Salesforce Lightning is a Component based framework from Salesforce for design simplified processes for business users. Next big thing in Salesforce is the Lighting Component Architecture. Lightning Component Framework is one of the methods in Salesforce which is used to develop user interface. It is used to create a dynamic web application for both mobiles and desktops.

Salesforce Lightning Architecture uses Single page Application Architecture.  Single Page Applications are web applications which use single HTML page and update dynamically when user interacts with the page. In this tutorial, we will follow a modern approach to build the single web application using Salesforce Lightning Component.

Below figure shows how Lightning Component framework looks. We have three components here:

  • Client Side: Which is handled by JavaScript
  • Salesforce Cloud to connect both server and client side.
  • Server Side: Which is handled by Apex Controller.

Client-Server Controller

Salesforce Lightning Component is built over Aura Component, Using Aura component enables to develop dynamic web pages with scalable lifecycle to support building apps designed for growth.

Aura Components are reusable components and represent reusable section of the UI. Usage of Aura Components can range from single line to complete app. Salesforce Lightning Component is built over Aura Component. Aura Component enables to develop dynamic web pages with scalable lifecycle to support apps designed for growth. You can find more about Aura component from this link ithub.com/forcedotcom/aura.

Aura Component has multi-tier partitioned component that connects the server and client. As it is developed over Aura framework, it uses the responsive design - In this method, lightning component uses same codebase for all desktops, mobile, and tablets but displays according to the screen. This tutorial will show how you can reuse the same codes for different applications’ development.

Salesforce lightning component architecture has the advantage of using components like HTML, CSS, JavaScript, and many other web enabled codes, providing the sophisticated user interface. Lightning component is flexible, interactive, and helps to focus on the visualization of the business. Lightning component uses different technology at both server and client side - JavaScript is used at client side and apex is used at server side.

As the lightning in real life strikes fast and does not repeat its pattern, Salesforce lightning design system also is quick in use and does not repeat the same design for different service users. It helps to provide customer support, product knowledge, different cases in single environment.

Reasons to use Lightning component are mentioned below.

  • Out of box component sets.
  • Ecosystem in use have rich components.
  • Fast and better performance.
  • Event driven architecture.
  • Responsive design with reusability.
  • Advantage of cross browsability.
  • Beautiful user interface.
  • Driven towards visualization.
  • More user interactive.

Salesforce lightning design system is used in many ways, we will learn this different ways of Salesforce lightning design in this tutorial. This Salesforce developer guide will help in organized way of developing the lightning component.

As we talk about where the Salesforce lightning component ecosystem can be used, we can get a long list. Lightning component can be deployed in the following.

  • Lightning experience.
  • Salesforce1 app.
  • Lightning pages.
  • Lightning apps.
  • Visualforce pages.
  • Apps with lightning out.
  • Standalone apps in Salesforce.
  • Community builder.
  • Lightning tabs.
  • Mobile Hybrid SDKs

But, lighting component cannot be deployed or used in external sites.

Salesforce Lightning Experience Basics

Lightning component architecture consists of lightning application, component, controller, helpers and Apex controller. Lightning components are based on open source UI for web development. Below figure will help you understand.

Components of Lightning Application Architecture

Components of Lightning Application Architecture

Basic components of Lightning component architecture are explained below.

  • Lightning application: These are standalone pages containing many lightning components. Markup code used in the lightning application is similar to HTML to create lightning application, we use developer console.
  • Lightning Component: These are Markup components present in the application. It consists of helper(JS), Controller (JS), Style(CSS), Documentation, SVG, Re-Renderer and Design. Also it can have HTML+ Aura Component supported by Salesforce. Lightning component can be created in developer console.
  • Controller (JavaScript): Controller is a resource made up of JavaScript which defines functionality of all components in the action. Clicking the controller link present in the component will create controller.js file. JavaScript is used for controller as shown in below example.?

Controller Source

({
handleClick : function(cmp, event) {
var attributeValue = cmp.get("v.text");
console.log("current text: " + attributeValue);
var target = event.getSource();
cmp.set("v.text", target.get("v.label"));
}})

Example: Controller.js

  • Helper(JavaScript): Helper is another JavaScript resource which helps to connect both Apex side and Application side. It is like controller we will have the link to create the helper which will give Helper.Js file.
  • Apex Controller: Apex Controller is a custom Controller which implements all the logic of the page. This is of apex class which doesn’t have argument constructor for the output. Apex Classes is similar to Java classes where it defines functions of code.

Checkout SalesForce Tutorial

To create Apex Controller:

  1. From the component Bundle, enter apex classes in quick find box and select apex Classes
  2. Click New.
  3. Now set apex version in the version setting.
  • CSS style: This is basic CSS styling as used in the HTML. It is used for styling and coloring of the page.

Create and Edit Lightning Components.

Before Starting building application in Salesforce lightning Component creation, we need some setups. To develop the lightning application, you need org setup which are as follows.

  • Go to this link https://developer.Salesforce.com/signup?d=70130000000td6N
  • Fill the fields required.
  • In the email field, provide public address so that you can access it easily from the web browser.
  • Provide username which is easy to remember, and in the pattern of your mail. For example, firstname@lastname.com.
  • Read and select the checkbox for the subscription agreement.
  • After this, you will get an email notification and for the password change. Change the password.

Quick Start: Lightning Components

In this section, we will create your first Lightning Component. We can say it as a combination of Markup, JavaScript and CSS. We will approach it with step wise.

Step 1: Open Your Console.

Go to your Salesforce domain and select Developer Console as marked in the below picture.

Link:  https://ap8.lightning.force.com/lightning/setup/SetupOneHome/home

Screen Shot from the Salesforce Lightning Experience web pageScreen Shot from the Salesforce Lightning Experience web page

Step 2: Go to File-->New--> Lightning Component.

New Lightning Component

 New Lightning Component.

Step3: After clicking on lightning component, give the name for your component like Myfirst_lightcomponent and submit the form, as shown in below screenshot.

Naming The Lightning Component.

Naming The Lightning Component.

Step4: Once you submit, you will get two tabs opened, one is myfirst_lightcomponent component bundle and the other is myfirst_lightcomponent.cmp tab. Close the myfirst_lightcomponent tab and keep myfirst_lightcomponent.cmp opened, as shown below.

 Lightning Component Page and Component Bundle

Lightning Component Page and Component Bundle.

Step5: Now, you can edit with markup code, for example you can write sample code shown below.

Creating New Lightning Application 

Below steps will help to create new lighting application.

Step1: Go to file-->new--> Lightning application

Link: https://ap8.salesforce.com/_ui/common/apex/debug/ApexCSIPage

Opening Lightning Application

 Opening Lightning Application

Step2:  Give the name for the application, like myfirst_lightapp and Submit the form.

Naming Lightning application

Naming Lightning application.

After the submission, a page will open with new myfirst_lightapp bundle and myfirst_lightapp.app page. Close bundle page and continue with the. app page as shown in the below screenshot.

Application Page.

Application Page.

Step3: Now, with heading, embed the component name in the file, as shown in below code and save the file. C tag in the code is default namespace to access the  lightning component.

My first lightning application

Step4:  Now, go to lightning application component bundle and click it on preview, it will show the output of the lightning component. Below shows the output of the lightning component.

Output of the Lightning Component

Output of the Lightning Component.

Attributes and Expressions

While creating the Lightning Component, we use Attributes and Expressions to make the component more dynamic.  Its is mostly used for holding a value and reusing it in the code. Thus, Attribute and Expressions are essential aspects in the lightning component.

Attribute is like a variable where we store a value which can be used again and again in the code. Using attributes in lighting component will increase dynamicness of the code. Attributes can be added using tag

Attribute has rules for naming, and they are:

  1. Should start with alphabet or underscore.
  2. Should contain only alphanumeric or underscore character.

Expression: This field is actually used for calculation, using property values and other information in the markup. It used for giving output dynamically or getting values in the component dynamically.
Expressions can be any literal values, sub expressions, variables, and operators. Expression can only be declared inside the attribute as a field, which can be declared by tag {!v.whom}. Expression can be only case sensitive and should be maintained like that.

Attribute Types

We have different types of attributes, and they are.

  • Basic types.
  • Function type.
  • Object Type.
  • Standard and Custom type.
  • Collection Type.
  • Custom Apex Class type.
  • Framework Specific Type.

How to declare an Attribute?

Attribute use in Lightning component is similar to any markup language, here we define attribute under aura component tag. You can see the attribute declaration below.

Here, we have many component which declare the Attribute, and they are:

Name: Which is the name given to an attribute.
Type: Its datatype to which it belongs like string or number.
Default: If left null what value should be filled to the attribute by default choice.
Description: The Description of attribute for which it is used.
Access:  It determines whether it is Global attribute or Private attribute.
Required: Whether the attribute is mandatory or not.

Let us see an example code for the attribute Declaration.

Name of Unknown is {!v.FirstName}

{!v.FirstName} is {!v.Age} Years Old.

{!v.FirstName} is male? = {!v.isMale}


Now, open your Developer Console and type the above code in lightning Component, and save it by any name like my_first_attribute. Now, create a lightning application and embed your component in the lightning application.


Attribute Declaration

After this, go to Developer Console and press preview, and you will be able to see your output as shown below. In the above code, we have used three attributes, name, age, and Gender.

Output of the attribute

 Output of the attribute

As you observe in the code, we have used the tag {!v. Name}, this tag is the example for Expression . As we enter the value of attribute dynamically, the Tag{!v.Name} is the function of expression. There are different types of Expressions used in the lightning component, and they are:

  1. Dynamic Output Expression.
  2. Conditional Expression.
  3. Data binding between component.
  4. Value provider.
  5. Expression Evaluation.
  6. Expression operators Reference.
  7. Expression Function Reference.

In the above code, we have used both value provider expression and Dynamic Output expression.  The expression used with the tag is a Dynamic output expression and using it in next tag {!v.name } is of age {!.age} makes it value provider expression. 

Checkout Salesforce Interview Questions

Handle Actions with Controllers

Actions are any function or working of code which are handled by the controller on specific operation. Like in web browser when we click on new tab and a new tab for browsing is created, likewise we can have an action button in lightning component which will perform such operations on click go. 

Action: Actions are operation or any function which performs any specific task in the application.

The above mentioned tag is click tag which upon clicking it will perform a specific action. 

Event: Any action like notification given to a user on performing an action is called an event.  These events are controlled by client side controller which is basically written in JavaScript.

Below examples show the action created with the event in a  controller.

({
    myAction : function(cmp, event, helper) {
        // add code for the action
    },
    anotherAction : function(cmp, event, helper) {
        // add code for the action
    }
})

Each function above contains three components,

cmp→ Lightning component having a controller.
Event→ To handle action.
helper→ This is optional which can be reused in the component bundle.

Now, to handle the action, we need the controller from the client side. Controller is a part of the component bundle. To create Controller, click controller option in component bundle. The component bundle is shown below.

component bundle

component bundle

Once clicked on the tab, it will create the page, as shown below.

Handle Actions with Controllers

Once controller page is shown we write down the below code , which will create the two action.

<input type="button" value="Flawed HTML Button" />

{!v.text}

Observer the below example to create two actions with button. Clicking on this buttons will update the text component of attribute with specified values. Here, we have used lightning button which is a standard lightning component.

Lightning framework has its own event system called DOM (Documented Object Model) event. Events that are mapped to lightning events as HTML tags are mapped to lightning component. All the browsers can be mapped with Onkeys and Onclick which are then mapped to lightning component. After that, onclick button is mapped to lightning button component to handle click action.

The below-mentioned code is for the client side controller source which will help us to use onclick button created in the above code in the application.

<input type="button" value="Flawed HTML Button" />

{!v.text}

handleclick function in the above is the action which uses event getSource(). getSource() is a built-in event of lightning component which helps to determine from which component an event is fired. Lightning button in markup is the source component. When button is pressed, text is set to  attribute value for the label which is declared as v.label. To execute this again, go to previewer and click the button, and it will do the work.

Input Data Using Forms

Now, let us continue with the form building and inputting the data. For this topic, we will consider building a form for expense calculation. This form will create new expenses. For this, we will proceed with the steps as followed.

Step1: Pull Salesforce lightning design system (SLDS), and activate this in Lightning Component. We will get SLDS automatically inside. This SLDS is not available in the stand alone app.

Now create a lightning application named myexpenseapp.app with following mark up.

extends=“Force:slds” will activate SLDS in the application, C:expenses will embed component in the application.

Step2: Now, create a component with the name expense and write down below markup

The above code is to create grid layout.  When you preview it, you will get the output as below.

create grid layout

As you can see it is blank, now we have to add the form fields .

Step3: Now, you have to add fields to the empty form. In the above code, we have commented line number 18. Now replace that line with the below code. Now, without SLDS and Classes, it's just a 
series of input fields. 

<!-- CREATE NEW EXPENSE -->
Add Expense
    <!-- / CREATE NEW EXPENSE -->

Step4: Now, go to Lightning application component bundle and click preview tab. You get output as below.

Application Component Bundle 

Application Component Bundle

Connect to Salesforce with Server-Side Controllers

Till now, we were playing at the client side , and we have not connected to server yet. An event is wired to client side controller action which can call server side controller action. We have methods to connect to Salesforce, and you can see them below.

Apex Server-Side Controller Overview

Server side controller is created in the apex and uses @auraenabled annotation for accessing the controller method. Only annotated methods are exposed, and are bounded to apex limits. Apex controller has this  server Echo action which adds a string to the value passed in.

Aura enabled Annotation helps lightning component to connect to the apex methods and properties.  Aura enabled  annotation is used for two separate and distinct purposes. Use @AuraEnabled class static methods of Apex  to Access remote controllers in lightning component.. Use @AuraEnabled  instance methods and properties of Apex to serialize as data received from server side.

    //Use @AuraEnabled to enable client- and server-side access to the method
    @AuraEnabled
    public static String serverEcho(String firstName) {
        return ('Hello from the server, ' + firstName);
    }
}

Lightning application component bundle

Lightning application component bundle

Creating an Apex Server-Side Controller

Step1: Open your Developer Console.

Step2: Go to file-->New-->Apex Class

Apex Server-Side Controller

Apex Server-Side Controller

Step3: Enter a name to the controller.

New Apex Class

Step4: Now, enter method for each server-side controller. Add aura enabled so that methods get exposed.

Step5: Now, save the apex controller, after that open the component which you want to wire apex controller with. Now, add the controller to the component with below tag.

 

Returning an Apex Server-Side Controller

After creating the server side controller, we need to retrieve data from the server side to client side. This can be done by using return keyword in the component. The result must be serialized and should be in Json format. 

Return data type can be:

  • Simple.
  • Sobject.
  • Apex.
  • Collection.

Returning Apex Object.

Example code to return the object:

public with sharing class SimpleAccountController {
    @AuraEnabled
    public static List getAccounts() {
        // Perform isAccessible() check here
        // SimpleAccount is a simple "wrapper" Apex class for transport
        List simpleAccounts = new List();
        List accounts = [SELECT Id, Name, Phone FROM Account LIMIT 5];
        for (Account acct : accounts) {
            simpleAccounts.add(new SimpleAccount(acct.Id, acct.Name, acct.Phone));
        }
        return simpleAccounts;
    }
}

Connect Components with Events

Events: An event is a notification to an action which is performed in application. Browser events are controlled by client side controller which uses JavaScript.

When an action is performed, the following things happen.

  • User clicks on action, triggering browser event.
  • Action clicked will invoke client side controller providing custom logic and invokes the helper.
  • Helper improves the code reuse.
  • Helper calls the Apex server side controller. This can be done by client side controller also.
  • Apex controller invokes Apex method and returns the data.
  • Callback evaluates the logic and updates the UI.
  • User views updated data.
  • JavaScripts callback is invoked.

Handling Events with Client-Side Controllers

A client side controller handles the event in a component. It is a JavaScript which controls all functions to be happened. 

Now, follow the steps to create an event attached to a Component.

Step1: Create an event. Goto developer console and in component bundle, click on Controller, and write down below code.

({
    myAction : function(cmp, event, helper) {
        // add code for the action
    },

    anotherAction : function(cmp, event, helper) {
        // add code for the action
    }
})

Step2: Save the controller and now open the new component into which our event will be embedded.

Step3: Add this below code to attach our event to the component. Here, in the code, marked data, where we have used tag {!c.handleclick}, will wire our event into the component through a function.

    
    <input type="button" value="Flawed HTML Button" />
    

    {!v.text}

This will connect your event to the component.

In lightning application, we have a type of event called as a component event. This event is fired from instance of component. This makes both event and action fired from same component.

Component Event

We have another method where we can have our event handled by the component, and that is the Component event. Component Event is one such type of event which is defined inside the component itself which fires it. Both defining of event and firing of event happens in the same component. Below are the steps to create the Component Event. 

Step1:  Create a lightning component in the developer Console.

Step2: Use type=”Component” tag for the component event, Use below code.

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Arogyalokesh
About The Author

Arogyalokesh is a Technical Content Writer and manages content creation on various IT platforms at Mindmajix. He is dedicated to creating useful and engaging content on Salesforce, Blockchain, Docker, SQL Server, Tangle, Jira, and few other technologies. Get in touch with him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close