Getting started with basics of Lightning Component

As you might already know that next big change in Salesforce is introduction to lightning components. As technology is changing rapidly and to take advantage of cutting edge innovations in web technology, Salesforce doesn’t want to stay behind. If we see trend, all major platform has introduced component based design like Polymer, React, Web Components, Angular 2.

We will be discussing basics of Lightning components in this post and how Lightning application, component, controller, helpers and Apex controllers are connected with each other.

Lightning components are based on open source UI framework for web development. Every Salesforce organization already has aura documents available in their instance and can be opened by navigating to http://instance.salesforce.com/auradocs. You can also visit my other blog post explaining FAQ of lightning and Lightning Trailhead module.

In below image, I have tried to explain at high level, how different JavaScript files are related in Lightning components, there are many other parts as well, but I tried to keep it short and simple.

Getting started with lightning components
Getting started with lightning components

Component Bundles

Lightning components consists of many resources as explained in below table.

ResourceResource NameUsage
Component or Applicationsample.cmp or sample.appThe only required resource in a bundle. Contains markup for the component or app. Each bundle contains only one component or app resource.
CSS Stylessample.cssStyles for the component.
ControllersampleController.jsClient-side controller methods to handle events in the component.
Designsample.designRequired for components used in the Lightning App Builder or Lightning Pages.
HelpersampleHelper.jsJavaScript functions that can be called from any JavaScript code in a component’s bundle.
Documentationsample.auradocA description, sample code, and one or multiple references to example components.
RenderersampleRenderer.jsClient-side renderer to override default rendering for a component.
SVGsample.svgCustom icon resource for components used in the Lightning App Builder.

Lightning Application

Lightning applications are standalone page, which contains many other lightning components. Its mark up is similar to HTML as shown in above image. To create Lightning application, open developer console, navigate to “File | New | Lightning Application”. It will prompt for “Name” and “Description”, provide proper information.

This post is written in order of “execution flow” as depicted in above image. However, to save code in your Salesforce instance, you need to create it in opposite direction. So, basically you need to start with step 5.

AllContacts.app

<aura:application >
    <link href='/resource/bootstrap/' rel="stylesheet"/>
    <c:AllContactsComp />
</aura:application>

In above lightning application, I have used Bootstrap to style my application, saved in static resource by name “bootstrap”. This application has only one Lightning component named “AllContactsComp”.

Lightning Component

Lightning components can be created by navigating to “File | New | Lightning Component” in developer console. It can contain “HTML + Aura components” supported by Salesforce.

Lightning Components
Lightning Components – Image 2

As shown in above image, Lightning component consists of Controller ( JS ), Helper ( JS ), Style ( CSS ), Documentation, Rerenderer, design and SVG. We will be using only Controller and Helper in this post.

AllContactsComp.cmp

<aura:component controller="ContactAura">
    <aura:attribute name="contactRows" type="Object[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <div class="container">
        <p>
        	<b> List of Contacts </b>
        </p>
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th><strong> Id </strong></th>
                    <th> <strong>  Name </strong> </th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration var="cell" items="{!v.contactRows}">
                    <tr>
                        <td> <a href="{! '/'+cell.Id}"> {!cell.Id} </a> </td>
                        <td> {!cell.Name}  </td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
 	</div>
</aura:component>
  • Above component is using Apex class “ContactAura”, which I will explain in later part of this post.
  • Attribute of type Object[] defined as name “contactRows”.
  • Its calling method doinit() in handler file. “c” stands for “Controller” and “v” stands for “View” in Aura syntax.
  • Later part of code is iterating over variable “contactRows” and displaying ID and name.

JavaScript Controller

We can click on “Controller” link available on right of component (image 2). It will create new file by name “[component]Controller.js” , in this case file “AllContactsCompController.js” will be created.

AllContactsCompController.js

({
    doInit : function(component, event, helper){
        helper.getAllContacts(component);
    }
})

this method “doInit()” is called by Component. This method is calling method in helper file.

JavaScript Helper

click on “Helper” link available on right of component (image 2). It will also create new JavaScript file which will be used by Component. This file mostly interacts with Apex method defined in @AuraEnabled static public method.

AllContactsCompHelper.js

({
	getAllContacts : function(component, event, helper) {
		var action = component.get("c.get10COntacts");
        action.setCallback(this, function(a){
            component.set("v.contactRows", a.getReturnValue());
        });
        $A.enqueueAction(action);
	}
})

This helper file is calling method “get10Contacts” defined in Apex controller. After successful callback, it is setting variable “contactRows” defined in “View” of component. It is very important to enqueueAction so that it can be processed.

Apex Controller

ContactAura

public class ContactAura {
    @AuraEnabled
    public static List<Contact> get10COntacts()
    {
        return [SELECT Id, NAME FROM Contact Limit 10] ;
    }
}

This apex controller is just querying 10 contacts to show on component.

Output

You can check final output by clicking on “Preview” on right of Lightning App file explained in step 1 of image.

Getting started with Lightning component Output
Getting started with Lightning component Output

I would recommend to check this cheat-sheet by Salesforce for lightning components.

 

Posted

in

,

by


Related Posts

Comments

11 responses to “Getting started with basics of Lightning Component”

  1. Manjit Singh Avatar
    Manjit Singh

    Hi Jitendra,

    Thanks for the blog. It was very informative. I had a question about app.css which is loaded by default and overrides the CSS of LDS (ui:button in my case). Is there a way to prevent that.

    I am using SLDS104.

    1. Jitendra Zaa Avatar

      Hi Manjit, I would recommend writing custom CSS in bundle of lightning component itself.

  2. sravani Avatar
    sravani

    Hi Jitendra,
    Helpful blog. I’m customizing my napili template for business purpose . and hence have to redirect to /profiles/userid — > to utilise the standard functionality.
    So my query is how to use “action” which contains my userid to url . My Page is unable to load if i use-
    window.open(“/profiles/” + {!v.userid} );
    to my url. kindly suggest.

  3. sheetal Avatar
    sheetal

    hi Jitendra,
    is it possible to refresh the whole page on click of a lightning component

    1. Priyanka Singh Avatar
      Priyanka Singh

      yes..use $A.get(‘e.force:refreshView’).fire();

  4. Chiranjeevi Avatar
    Chiranjeevi

    HI,

    This is very useful to understand the basics of lightning, Please keep blogging about the lightning architecture.

    Thank you.

  5. Menand Modhvadiya Avatar
    Menand Modhvadiya

    Hi Jitendra

    Pleas Can you tell me how to Crete below Lighting Component for page layout.

    Salesforce Lightening As: Dynamically fields in lightening component

    Steps to follow:
    1. Create one custom object, add atleast one field with each datatype and add all fields in Page Layout in your salesforce dev org.
    2. Create one lightening component that will show all fields from page layout and we can update those fields from that component.

    Regards,
    Menand

  6. Durgaprasad Avatar
    Durgaprasad

    Hi Jitendra

    Pleas Can you tell me how to assign page layouts to specific users dynamically in lighting

  7. techtrainingteks Avatar

    Hi Jitendra
    Awesome post about the basics of lightning.

    thank you
    katherine

  8. ganesh e patil Avatar
    ganesh e patil

    Hi Jitendra,

    Please make a blog/video on complete process of how to use lightning:container tag, by hosting third party application.

    Thank you
    Ganesh P

  9. purushotham G Avatar
    purushotham G

    The AllContactsComp.cmp has an error in the syntax of action where action should come first and then value should come

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading