Вы находитесь на странице: 1из 24

Salesforce Lightning Components Tutorial

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:

1. Fastness: Salesforce will take few months to get the application deployed whereas custom built
CRM may take years to get it deployed.
2. Easy: Salesforce is simple to use compared to complex custom CRM platform.
3. 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:

1. 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, as it depends on configuration of mobile it may affect the
quality of data.

2. Lightning Application Architecture.: It is a new approach towards application development.


Using Lightning application, 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 change 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 dynamicness
and easy to go approach of 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.
Table Of Contents
1. Introduction(Getting Started with Lightning Components)
2. Lightning Components Basics
3. Create and Edit Lightning Components
4. Attributes and Expressions
5. Handle Actions with Controllers
6. Input Data Using Forms
7. Connect to Salesforce with Server-Side Controllers
8. Connect Components with Events
9. Discover Next Steps

Introduction
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:

1. Client Side: Which is handled by JavaScript


2. Salesforce Cloud to connect both server and client side.
3. Server Side: Which is handled by Apex Controller.

Fig1: 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.

Fig2: Components of Lightning Application Architecture.

Basic components of Lightning component architecture are explained below.

1. 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.
2. 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.
3. 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

4. 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.

5. 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.

To create Apex Controller:


· From the component Bundle, enter apex classes in quick find box and select apex Classes
· Click New.
· Now set apex version in the version setting.

6. 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.

1. Go to this link https://developer.Salesforce.com/signup?d=70130000000td6N


2. Fill the fields required.
3. In the email field, provide public address so that you can access it easily from the web browser.
4.Provide username which is easy to remember, and in the pattern of your mail. For example,
firstname@lastname.com.
5. Read and select the checkbox for the subscription agreement.
6.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

Fig1: Screen Shot from the Salesforce Lightning Experience web page

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


Fig2: 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.

Fig3: 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.
Fig4: Lightning Component Page and Component Bundle.

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

<aura:component >
<h1>Lightning Application Tutorial</h1>
<p>Mindnmajix.com</p>
<p>Ghost</p>
</aura:component>

Bundle of components shown in the screenshot contain all components of lightning application.
So, now, you have built a lightning component, but to run this, you will need to build lightning
Application.

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
Fig1: Opening Lightning Application.

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

Fig2: 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.
Fig3: 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.

<aura:application >
<h1>My first lightning application</h1>
<c:My_first_lightcomponent.cmp/>
</aura: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.

Fig : 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 <Aura:attribute>

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.

1. Basic types.
2. Function type.
3. Object Type.
4. Standard and Custom type.
5. Collection Type.
6. Custom Apex Class type.
7. 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.

<aura:component>
<aura:attribute name="yourName" type="String" default="Ghost" description="Using For
tutorial Name"/>
</aura:component>

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.

<aura:component>
<aura:attribute name="FirstName" type="String" default="Ghost" />
<aura:attribute name="Age" type="Integer" default="1000"/>
<aura:attribute name="isMale" type="Boolean" default="true"/>
<p>Name of Unknown is {!v.FirstName}</p>
<p>{!v.FirstName} is {!v.Age} Years Old.</p>
<p>{!v.FirstName} is male? = {!v.isMale}</p>
</aura:component>

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.
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.

Fig: 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 <!v.name> is a Dynamic output expression and using
it in next tag <p> {!v.name } is of age {!.age} <p> makes it value provider expression.

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.

<lightning:button label = "Click Me" onclick = "{!c.handleClick}" />

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,


1. cmp→ Lightning component having a controller.
2. Event→ To handle action.
3. 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.
Once clicked on the tab, it will create the page, as shown below.

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

<aura:component>
<aura:attribute name="text" type="String" default="Just a string. Waiting for change."/>
<input type="button" value="Flawed HTML Button"
onclick="alert('this will not work')"/>
<br/>
<lightning:button label="Framework Button" onclick="{!c.handleClick}"/>
<br/>
{!v.text}
</aura:component>
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..

({
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"));
}
})

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.

<aura:application extends="force:slds">
<!-- This component is the real "app" -->
<!-- c:expenses/ -->
</aura:application>

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

<aura:component>
<!-- PAGE HEADER -->
<lightning:layout class="slds-page-header slds-page-header--object-home">
<lightning:layoutItem>
<lightning:icon iconName="standard:scan_card" alternativeText="My Expenses"/>
</lightning:layoutItem>
<lightning:layoutItem padding="horizontal-small">
<div class="page-section page-header">
<h1 class="slds-text-heading--label">Expenses</h1>
<h2 class="slds-text-heading--medium">My Expenses</h2>
</div>
</lightning:layoutItem>
</lightning:layout>
<!-- / PAGE HEADER -->
<!-- NEW EXPENSE FORM -->
<lightning:layout>
<lightning:layoutItem padding="around-small" size="6">
<!-- [[ expense form goes here ]] -->
</lightning:layoutItem>
</lightning:layout>
<!-- / NEW EXPENSE FORM -->
</aura:component>

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

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 -->
<div aria-labelledby="newexpenseform">
<!-- BOXED AREA -->
<fieldset class="slds-box slds-theme--default slds-container--small">
<legend id="newexpenseform" class="slds-text-heading--small
slds-p-vertical--medium">
Add Expense
</legend>

<!-- CREATE NEW EXPENSE FORM -->


<form class="slds-form--stacked">
<lightning:input aura:id="expenseform" label="Expense Name"
name="expensename"
value="{!v.newExpense.Name}"
required="true"/>
<lightning:input type="number" aura:id="expenseform" label="Amount"
name="expenseamount"
min="0.1"
formatter="currency"
step="0.01"
value="{!v.newExpense.Amount__c}"
messageWhenRangeUnderflow="Enter an amount that's at least $0.10."/>
<lightning:input aura:id="expenseform" label="Client"
name="expenseclient"
value="{!v.newExpense.Client__c}"
placeholder="ABC Co."/>
<lightning:input type="date" aura:id="expenseform" label="Expense Date"
name="expensedate"
value="{!v.newExpense.Date__c}"/>
<lightning:input type="checkbox" aura:id="expenseform" label="Reimbursed?"
name="expreimbursed"
checked="{!v.newExpense.Reimbursed__c}"/>
<lightning:button label="Create Expense"
class="slds-m-top--medium"
variant="brand"
onclick="{!c.clickCreate}"/>
</form>
<!-- / CREATE NEW EXPENSE FORM -->

</fieldset>
<!-- / BOXED AREA -->
</div>
<!-- / CREATE NEW EXPENSE -->

Step4: Now, go to Lightning application component bundle and click preview tab. You get output
as below.
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.

public with sharing class SimpleServerSideController {


//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);
}
}

Creating an Apex Server-Side Controller

Step1: Open your Developer Console.


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

Step3: Enter a name to the controller.

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.

<aura:component controller="Myfirst_servercon">

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:

1. Simple.
2. Sobject.
3. Apex.
4. Collection.

Returning Apex Object.

Example code to return the object:

public with sharing class SimpleAccountController {


@AuraEnabled
public static List<SimpleAccount> getAccounts() {
// Perform isAccessible() check here
// SimpleAccount is a simple "wrapper" Apex class for transport
List<SimpleAccount> simpleAccounts = new List<SimpleAccount>();
List<Account> 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.

1. User clicks on action, triggering browser event.


2. Action clicked will invoke client side controller providing custom logic and invokes the
helper.
3. Helper improves the code reuse.
4. Helper calls the Apex server side controller. This can be done by client side controller also.
5. Apex controller invokes Apex method and returns the data.
6. JavaScripts callback is invoked.
7. Callback evaluates the logic and updates the UI.
8. User views updated data.

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.

<aura:component>
<aura:attribute name="text" type="String" default="Just a string. Waiting for change."/>
<input type="button" value="Flawed HTML Button"
onclick="alert('this will not work')"/>
<br/>
<lightning:button label="Framework Button" onclick="{!c.handleClick}"/>
<br/>
{!v.text}
</aura:component>

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.
<!--c:compEvent-->
<aura:event type="COMPONENT">
<!-- Add aura:attribute tags to define event shape.
event.setParam("message", "event message here");
<aura:attribute name="message" type="String"/>
</aura:event>

Step3: The event fired can set the data to which we need attribute. For this, we will use
event.setParam(). This will set the attribute. Now, we are set to fire the event.

Step4: Now, to fire this event, we need to register the event. We will use a tag to register as shown
below.

<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>

Step4: Now, finally, we fire the event by creating a component and adding our component in it
and fire it. Below code will show how it is done.

var compEvent = cmp.getEvent("samComponentEvent");


compEvent.setParams({"myParam" : myValue });
compEvent.fire();

Discover Next Steps


This is our last topic for the salesforce lightning tutorial for beginners here we just glance through
the topic which you can explore to improve your knowledge or grip on salesforce lightning
application.

Topics which will help you to gain more confidence in the Salesforce.

1. Other components in the Bundle.


2. Navigation.
3. Dynamically creating the Component.
4. Error Handling and Debugging the Code.
5. NameSpace Component and Other Different Types of events and Action.
6. Styling the app.

Conclusion
Salesforce is a new day UI development software which helps you to build more dynamic and most
interactive CRM application. Salesforce CRM application are one of the most used application in the world.
Salesforce Lightning Component architecture is Salesforce new approach towards building more dynamic
CRM application and easy to interact UI to use in either desktop, Mobiles or Tablets. Now a days use of
Lightning application is more and customers are moving or upgrading their old CRM to Salesforce CRM.
It provides Outbox components, Architecture driven framework, event driven architecture and better
optimization option compared to older version.
This Salesforce lightning application helps to provide insight over it Components, events which help to
build an application. Topics covered helps to understand and build Lightning application, How it works and
what it uses for to become more dynamic.

Оценить