Lightning Components in Salesforce With Example

Lightning Components in Salesforce With Example

Lightning Components in Salesforce With Example

Lightning Components are the UI Framework provided by Salesforce to build Apps which are responsive i.e. can be used on Desktop as well as mobile devices. It Uses a Javascript Controller on the client side and Apex on the server side.

Lightning Component Overview
To understand better , lets build a lightning component to fetch the list of Contacts,

Step 1: Creating the Apex Controller

Go to developer console and click File-->New --> Apex Class. Enter the bundle name as ContactlistController and press ok.

Paste the below code to the class and  Save.

public with sharing class ContactListController {

    public static List<Contact> fetchContacts() {
        return [SELECT id, name, phone FROM Contact LIMIT 50];

Step 2: Creating Lightning Component

Go to developer console and click File-->New --> Lightning Component. Enter the bundle name as Contact list and press Submit.

once you are in the Component , paste the below code:

<aura:component controller="ContactListController" implements="force:appHostable">
    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
        <aura:iteration items="{!v.contacts}" var="contact">
                <a href="{! '#/sObject/' + contact.Id + '/view'}">
                    Name: {!contact.Name} Phone:{!contact.Phone}
The Controller mentioned in the first line is the apex class which we created in the first step.

Step 3: Creating Client Side Controller

To Create client side controller click on the Controller option shown in the right side panel of your component. Refer image below:
Copy the below code and paste . The code has only one function which is called when the component is initialized.
This function inturn calls the Apex controller method "fetchContacts" to fetch the list of contacts.

    doInit : function(component, event) {
        var action = component.get("c.fetchContacts");
        action.setCallback(this, function(a) {
            component.set("v.contacts", a.getReturnValue());
Finally : Test the Lightning Component

Now finally to test this component let's create a tab to launch the component. Click setup --> Create -->Tab-- Lightning component Tab and select the component just created. Add this component to the application and click to run it.

Still Facing Issues , watch the video below for step by step guidance

About Saurabh Dua


Powered by Blogger.