Friday, April 27, 2018

How to fetch and display list of records in Lightning Component


Now to accomplish the task of displaying a list of contacts we need to first analyse that how we can decompose this request into small components. i.e. a list of record will have detail of a single record in each line. Therefore each line of record can be an individual component and can be repeated and iterated over till the end of records.
To begin with we need to understand that how many fields we are going to display for each record, for this example we are going to display contact name, account name of the contact and email address of the contact. So for this we are going to create a component which will have 3 aura attribute’s namely contactName, accountName and email.
We then use these attributes to display the contact as a tile for each record. We are naming the component as eachContactCard. Below is the code of the component.
<aura:component implements=”flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes” access=”global” >
    <aura:attribute name=”contactName” type=”String” />
    <aura:attribute name=”accountName” type=”String” />
    <aura:attribute name=”email” type=”String” />    
  <div class=”demo-only” style=”width: 30rem;”>
    <article class=”slds-tile”>
        <h3 class=”slds-tile__title slds-truncate” title=”Contacts UX”><a href=”javascript:void(0);”>Contacts UX</a></h3>
        <div class=”slds-tile__detail”>
            <dl class=”slds-list_horizontal slds-wrap”>
                <dt class=”slds-item_label slds-text-color_weak slds-truncate” title=”First Label”>Contact Name:</dt>
                <dd class=”slds-item_detail slds-truncate” title=”Description for first label”>{!v.contactName}</dd>
                <dt class=”slds-item_label slds-text-color_weak slds-truncate” title=”Second Label”>Account Name:</dt>
                <dd class=”slds-item_detail slds-truncate” title=”Description for second label”>{!v.accountName}</dd>
                <dt class=”slds-item_label slds-text-color_weak slds-truncate” title=”Third Label”>Email:</dt>
                <dd class=”slds-item_detail slds-truncate” title=”Description for Third label”>{!v.email}</dd>           
                </dl>
    </div>
    </article>
  </div>
</aura:component>

Since this component will receive value of its attribute from the parent component, therefore we do not require any client side controller or server side controller for this component. Now we are going to create the parent component to hold and display the list of the contacts.
We are going to name this component as listOfContacts, this component will have attribute to hold a list of contacts and as this component is going to fetch records from server side we are going to mention the apex controller in this component and we also want to display the component therefore we create a client side controller and write an aura handler method which would run to initialise the component as shown below. We also create an aura iteration component which is going to iterate over the list of the contacts and will use the eachContactCard component to display each record. As shown below:
<aura:component controller=”fetchContactDetails” implements=”flexipage:availableForAllPageTypes” access=”global” >
    <aura:attribute name=”contactList” type=”contact[]” />
                <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” />   
     <aura:iteration items=”{!v.contactList}” var=”item”>
         <c:eachContactCard contactName=”{!item.Name}” accountName=”{!item.Account.Name}” email=”{!item.Email}”  />
         <br/>
    </aura:iteration>
</aura:component>

Apex Controller of this component is fetchContactDetails and its method fetchContactList returns the list of contacts, this method as it is going to be called in lightning component we have to declare this with annotation @AuraEnabled and any method which has @AuraEnabled attribute has to be declared as public static,  as shown below
public class fetchContactDetails {   
    @AuraEnabled
    public static list<Contact> fetchContactList(){
        return [select Id, name, Account.name, Email from contact limit 10];             
    }
}
The client side controller which displays the list of contact, in this controller we have declared a method doInit. This method calls the method declared in Apex controller and sets the view tiem value of the contactList attribute at the run time as shown below.
({
                doInit : function(component, event, helper) {
                                var action = component.get(“c.fetchContactList”);       
        action.setCallback(this, function(data){
            component.set(“v.contactList”,data.getReturnValue());
        });       
        $A.enqueueAction(action);
                }
})

Once you have created all the components then change the lightning application code as shown below
<aura:application extends=”force:slds” >
    <c:listOfContacts />
</aura:application>

Then click on the preview button to display the list of contacts.
Salesforce Lightning Tutorials

  1. What is Lightning ?
Lightning is the collection of tools and technologies behind a significant upgrade to the Salesforce platform. Lightning includes:
  • Experience: A set of modern user interfaces optimized for speed. This includes the Lightning Experience, Salesforce1 Mobile app and template-based communities.
  • Lightning Component Framework: A JavaScript framework and set of standard components that allow you to build reusable components to customize the Lightning Experience, Salesforce1 Mobile app and template-based communities and build your own standalone apps.
  • Visual Building Tools: Drag-and-drop technologies for fast and easy app building & customization’s. Use the Lightning App Builder to customize the Lightning Experience and Salesforce1 Mobile app. Use the Community Builder to customize template-based communities.
  • Lightning Exchange: A section of the AppExchange where you can find 70+ partner components to jump-start your development.
  • Lightning Design System: Style guides and modern enterprise UX best practices to build pixel perfect apps that match the look and feel of the Lightning Experience and Salesforce1 Mobile app.
2. How can we use Lightning Components with the Salesforce1 Mobile App ?
By Create a custom Lightning tab that points to our component and include that tab in our Salesforce1 Mobile navigation.
3. Can we make a Lightning Component that shows up in both the mobile and the desktop user interfaces ?
 We can use Lightning Components directly in Lightning Experience, the Salesforce1 Mobile app, template-based communities, and custom standalone apps. Additionally, we can include Lightning components in a Visualforce page, that allowing us to use them in Salesforce Classic, Console, and Visualforce-based communities.
4. Is Lightning an MVC framework ?
No, it’s a component-based framework.
5. Which parts of Lightning Components are server-side and which are client-side ?
Lightning Components are use JavaScript on the client side and Apex on the server side.
6Can we make one component inherit styles/CSS from a parent component, or must we always define it in the component ?
Yes, we can inherit styles from parent. there is no need to always defined in the component.
7. What is the use of the aura:method tag in Lightning ?
we can Use < aura:method > to define a method as part of a component’s API. This enables us to directly call a method in a component’s client-side controller instead of firing and handling a component event. Using simplifies the code needed for a parent component to call a method on a child component that it contains.
8. Can we Include One component to another ?
Yes, we can Include one lightning component to another lightning component
9. Is there any limit on how many component to have in one Application ?
there is no limit.
10. Is Lightning Components replacing Visualforce ? 
No.
11. What is Aura? Why do we use the aura: namespace in the code ?
Aura is the open source technology that powers Lightning Components. The aura: namespace contains all of the basic building blocks for defining components and applications.
12. Do we need a namespace to develop Lightning Components ?
No. Lightning Components used to require a namespace, but that is no longer a requirement.
13.What are the tools included in lightning ?
  •  Lightning Component Framework – Components and extensions that allow you to build reusable components, customize the Salesforce1 Mobile App, and build standalone apps.
  • Lightning App Builder – A new UI tool that lets you build apps lightning fast, using components provided by Salesforce and platform developers.
  • Lightning Connect – An integration tool that makes it easier for your Force.com app to consume data from any external source that conforms to the OData spec.
  • Lightning Process Builder – A UI tool for visualizing and creating automated business processes.
  • Lightning Schema Builder – A UI tool for viewing and creating objects, fields, and relationships.
14.What is difference between Visualforce Components and Lightning Components ?
Visualforce components are page-centric and most of the work is done on the server. Lightning is designed from the component up, rather than having the concept of a page as its fundamental unit. Lightning Components are client-side centric, which makes them more dynamic and mobile friendly.
15. Does Lightning work with Visualforce ?
yes Lightning work with Visualforce.
16.Are there any CSS (styles) provided by salesforce.com as part of the supported Lightning Components ?
Yes. Salesforce Lightning Design System.
17. Are Lightning Components intended only for mobile apps ?
Components have been built to be mobile first, but with responsive design in mind. With Lightning we can build responsive apps fast for desktop, mobile and tablets.
18. What are the advantages of lightning ?
The benefits include an out-of-the-box set of components, event-driven architecture, and a framework optimized for performance.
  • Out-of-the-Box Component Set -: Comes with an out-of-the-box set of components to kick start building apps. You don’t have to spend your time optimizing your apps for different devices as the components take care of that for you.
  •  Rich component ecosystem-: Create business-ready components and make them available in Salesforce1, Lightning Experience, and Communities.
  • Performance – :Uses a stateful client and stateless server architecture that relies on JavaScript on the client side to manage UI, It intelligently utilizes your server, browser, devices, and network so you can focus on the logic and interactions of your apps.
  • Event-driven architecture -: event-driven architecture for better decoupling between components
  • Faster development – : Empowers teams to work faster with out-of-the-box components that function seamlessly with desktop and mobile devices.
  • Device-aware and cross browser compatibility – : responsive design,supports the latest in browser technology such as HTML5, CSS3, and touch events.
 19. Can we integrate Lightning components with another framework, such as Angular?
Yes. we can include the working 3rd party code inside a Visualforce Page, embed the Visualforce Page inside a Lightning Component. This Lightning Component can be used as any other Lightning Component in various environments.
20. Can we include external JavaScript/CSS libraries in components ?
Yes ! we can use multiple libraries in our lightning component like JQuery, Bootstrap, custom CSS and custom Javascript libraries from a local resource (static resource).
21. What happens with existing Visualforce Pages in Lightning Experience ?
They’ll continue to be supported in the current UI and Lightning Experience.
22. Where we can display lightning component ?
There are a number of possibilities for display lightning component..
  •  Lightning Experience: We can display component in the Lightning Experience using the App Builder.we can edit the home page, edit a record detail page or create/edit a new app page to include it.
  •  Salesforce1 Mobile app: We can display component in the Salesforce1 Mobile app by creating a custom Lightning tab that references it and adding that tab in mobile navigation.
  • Template-based community: we can display component in template-based (e.g. Napili) community using the Community Builder.
  • Standalone Lightning app: By create a standalone Lightning app (e.g. myapp.app) and include component in this app. Access Lightning app by URL.
23. Do I always create an app bundle first when develop lightning component ?
Not necessarily, We can start with a Component bundle.
24. How can we  deploy components to production org ?
we can deploy component by using managed packages, Force.com IDE, Force.com Migration Tool or Change Sets.
25. What is Lightning Experience?

Lightning Experience is the name for the all new Salesforce desktop app, with over 25 new features, built with a modern user interface and optimized for speed.
-------------------------------------------------------------------------------------------------------------------------

1. WHAT IS AURA FRAMEWORK

Aura is an open-source UI framework built by Salesforce for developing dynamic web apps for mobile and desktop devices. Salesforce uses Aura to build apps, such as Lightning Experience and Salesforce1.

2. WHAT IS DIFFERENCE BETWEEN APPLICATION EVENT AND COMPONENT EVENT

Component event: Component event is used to communicate with parent component using bubble event.

Application event: Application events: to broadcast to other components and not exclusively ancestors. Applications events can talk to many components that can be interested by the event.

3. WHAT IS THE USE OF IMPLEMENTS IN LIGHTNING COMPONENT

implement is used to implement multiple interface in lightning component. e.g. flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId

4. WHAT IS AURA:REGISTEREVENT IN LIGHTNING COMPONENT

A component registers that it may fire an event by using <aura:registerevent>

5. HOW CAN WE SUBSCRIBED TO AN EVENT IN LIGHTNING COMPONENT.

Use  <aura:handler> in the markup of the handler component.

6. HOW CAN WE COMMUNICATE BETWEEN TWO COMPONENT.

Lightning component can communicate using event communication framework. Read more about component communication patterns

7. HOW TO ADD LIGHTNING COMPONENT IN VISUALFORCE PAGE.

Lightning component can be added to visualforce page using ltng:outApp

8. WHAT IS AURA DEFINITION BUNDLE

Aura definition bundle contains following items
Component : UI for lightning component
controller.js : Contains client-side controller methods to handle events in the component.
helper.js: JavaScript functions that can be called from any JavaScript code in a component’s bundle
style: Contains styles for the component.
design: File required for components used in Lightning App Builder, Lightning pages, or Community Builder.
renderer: Client-side renderer to override default rendering for a component.
documentation: A description, sample code, and one or multiple references to example components
SVG: Custom icon resource for components used in the Lightning App Builder or Community Builder.

9. WHAT IS AURA:ATTRIBUTE

Attributes are like member variables on a class in Apex. They are typed fields that are set on a specific instance of a component, and can be referenced from within the component’s markup using an expression syntax.

10. WHAT IS LIGHTNING: OR UI: IN ANY LIGHTNING COMPONENT?

lightning: and ui: are two namespaces for core lightning component. The lightning namespace components are optimized for common use cases. 

11. HOW CAN WE EXTEND ANY COMPONENT

Lighting component can be extended using extensible=”true” attribute in aura:component 
Resources: 

Tuesday, April 3, 2018

Component events vs Application events (component.getEvent vs $A.get)


I am new to lightning experience and components. I have been through some blogs and code that guide through the basics, but other than that I haven't had much hands-on experience.
My question is:
When to use component events vs application events? If I have nested components (parent & child) and if the events are of type Component, will the parent be able to handle events fired from child, and vice versa?
Also, I've noticed there are two ways to get an instance of an event (say TestEvent) -
    component.getEvent("TestEvent");
and
    $A.get("e.c:TestEvent");
Is there any difference between the both? What do "$A" & "e" in the second form, represent?
12down voteaccepted
Component events: to talk to a parent using the capture and bubbling mechanism, like with DOM events. Usually, one component is interested by the event, like an event aggregator.
Application events: to broadcast to other components and not exclusively ancestors. Applications events can talk to many components that can be interested by the event. The broadcast can be boxed to an area of the DOM (everything below a DIV for example).
About $A.getEvt() & cmp.getEvent():
Events have been seriously revamped, and the distinction between Component and Application events has been reduced. However, this rework has not yet been translated into an updated API.
I need to remove references to the $A.getEvt() and cmp.getEvent() API because we are still working on a new version of the API. My apologies for the confusion.
About value providers:
Lightning has various value providers: "v" for attributes, "c" for controller, and "e" for events.
Application Event API:
Those are obtained from the global (hence $A.get()) event value provider:
var evt = $A.get("e.myNamespace:myEvent");
Component Event API:
Component must reference events by name, much like an aura:id, and retrieve them from its component (hence cmp.get()) value provider:
var evt = cmp.get("e.myEvent");
You would then declare myEvent on the component as:
<aura:registerEvent name="myEvent" type="namespace:eventName"/>
Why dow have this API? Declaring events on a component allows other components to call controller methods. You had to declare a handler:
<aura:handler name="myEvent" action="{!c.myEventHandler}"/>
That allowed you to call myEventHandler from another component and respect the interface:
cmp.get("e.myEvent").fire();

Component Events follow Event Bubbling Mechanism .
Lets understand with an example component from salesforce docs
<!--c:eventBubblingParent-->
<aura:component>
  <c:eventBubblingChild>
    <c:eventBubblingGrandchild />
  </c:eventBubblingChild>
</aura:component>
In the above example lets say eventBubblingGrandchild component fired an event ,the event then bubbles up and can be handled by a component in the containment hierarchy that receives the bubbled event.
The syntax to handle this is
 component.getEvent("TestEvent");
A containment hierarchy in this case is not c:eventBubblingChild instead it is c:eventBubblingParent .The event is not handled by c:eventBubblingChild as c:eventBubblingChild is in the markup for c:eventBubblingParent but it's not a facet value provider as it's not the outermost component in that markup.
Application events can be handled by any component and does not depend on hierarchy .
The syntax to handle for this is
 $A.get("e.c:TestEvent");
Now to answer your question on parent to child as you can see you cannot use component events to fire from parent and handle in child while vise versa is true but the event bubbles only to the top containment .
----------------------------------------------------------------------------------------------------------

How to navigate from one lightning component to another lightning component?

You could move between view states by creating and replacing components.
Server-side Controller
public class LightningController {

    @AuraEnabled
    public static list<Account> getAccounts(){
        return [SELECT Id, Name FROM Account LIMIT 10];
    }

    @AuraEnabled
    public static list<Opportunity> getOpportunities(Id AccountId){
        return [SELECT Id, Name FROM Opportunity WHERE AccountId = :AccountId];
    }

}
App
<aura:application controller="LightningController" >
    <aura:attribute type="Account[]" name="AccountList" />
    <aura:handler name="init" value="{!this}" action="c.doInit" />
    <aura:handler event="analysis:ATOEvent" action="{!c.ato}" />
    <aura:handler event="analysis:OTAEvent" action="{!c.ota}" />
    {!v.body}
</aura:application>
App client-side controller
({
    doInit : function(component, event, helper){
        var action = component.get("c.getAccounts");
        action.setCallback(this,function(response){
                if (response.getState() === "SUCCESS"){
                    component.set("{!v.AccountList}",response.getReturnValue());
                    helper.generateAccountList(component);
                }
            }
        );
        $A.enqueueAction(action);
    },
    ato : function(component, event, helper){
        var action = component.get("c.getOpportunities");
        action.setParams({"AccountId" : event.getParam("AccountId")});
        action.setCallback(this,function(response){
                if (response.getState() === "SUCCESS"){
                    helper.generateOpportunityList(component, response.getReturnValue());
                }
            }
        );
        $A.enqueueAction(action);
    },
    ota : function(component, event, helper){
        helper.generateAccountList(component);
    }
})
App helper
({
    generateAccountList : function(component) {
        $A.createComponent(
            "analysis:AccountList",
            {
                "AccountList" : component.get("{!v.AccountList}")
            },
            function(newComponent){
                component.set("v.body",newComponent);
            }
        )    
    },
    generateOpportunityList : function(component, OpportunityList){
        $A.createComponent(
            "analysis:OpportunityList",
            {
                "OpportunityList" : OpportunityList
            },
            function(newComponent){
                component.set("v.body",newComponent);
            }
        )
    }
})
AccountList
<aura:component >
    <aura:registerEvent name="ATOEvent" type="analysis:ATOEvent" /> 
    <aura:attribute name="AccountList" type="Account[]" />
    <aura:iteration items="{!v.AccountList}" var="Account">
        <ui:outputText value="{!Account.Name}" />
        <ui:button label="go" press="c.fireato" buttonTitle="{!Account.Id}" />
        <br/>
    </aura:iteration>
</aura:component>
AccountListController
({
    fireato : function(component, event, helper) {
        var action = $A.get("e.analysis:ATOEvent");
        action.setParams({"AccountId" : event.getSource().get("{!v.buttonTitle}")});
        action.fire();
    }
})
OpportunityList
<aura:component >
    <aura:registerEvent name="OTAEvent" type="analysis:OTAEvent" /> 
    <aura:attribute type="Opportunity[]" name="OpportunityList" />
    <ui:button label="Go Back" press="c.fireota" />
    <aura:iteration items="{!v.OpportunityList}" var="Opportunity" >
        <br />
        <ui:outputText value="{!Opportunity.Name}" />
    </aura:iteration>
</aura:component>
OpportunityListController
({
    fireota : function(component, event, helper) {
        var action = $A.get("e.analysis:OTAEvent");
        action.fire();
    }
})
ATOEvent
<aura:event type="APPLICATION" description="ATOEvent" >
    <aura:attribute name="AccountId" type="Id" />
</aura:event>
OTAEvent
<aura:event type="APPLICATION" description="OTAEvent" />