Saturday, November 10, 2018

Lightning Components Tutorial : Easy way to become Lightning developer

In this blog, I am going to share all lightning components concept which is required for Lightning developer starting from basics to advance topics.

You can learn lightning by following below blogs related to lightning.
  1. Lightning Component Basics: Lightning Component Framework
  2. Lightning Components Basics : Attributes, Expressions and Value Providers
  3. Lightning Components Basics : Handling Actions in Controller.js
  4. How to set or get picklist (drop down) values in Lightning Components
  5. Lightning Components Basics : Considerations while calling server-side controller actions
  6. Application Events : Way to Communicate Between Different Lightning Components
  7. Component Events: Way to Communicate Between Components in Containment Hierarchy
  8. Raising and Handling Custom Events in Salesforce Lightning
  9. Salesforce Lightning Events : Hands on Training Guide
  10. Salesforce 1 Events in Lightning Experience and Salesforce 1 app
  11. Lightning Data Services : Way to perform operation on records without using server-side Apex class
  12. Lightning Data Services : Hands on Training Guide
  13. Creating Lightning Components Dynamically
  14. Dynamically Creating and Destroying Lightning Button(ui:button)
  15. Adding Lightning Components in VF Page and Passing Values from URL
  16. Inheritance in Lightning Components
  17. Firing Event from Lightning Component and Passing Parameter to VF Page
  18. How to Fire Lightning Events from VF Page in Lightning
  19. Custom Component to show Loading Spinner in Lightning during Server or Client side Operations
  20. Why to use design resource in Lightning bundle and how to add dynamic Options in datasource for Design Component
  21. Formatting and Localizing dates in javascript in Lightning
  22. Using Chartjs in Lightning Components
  23. Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject
  24. Lightning:treegrid - Displaying Account hierarchy using treegrid
  25. Aura.Action : Lightning Framework Specific Attributes Type
  26. Aura.Component[] : Lightning Framework Specific Attributes Type

Hope this will help!!

Tuesday, November 6, 2018

Aura.Action : Lightning Framework Specific Attributes Type

In this blog, I am going to explain "Aura.Action" attribute type and its usage.

There is another Lightning Framework specific attribute "Aura.Component[]". If you want to learn more about this then refer below blog:

Aura.Component[] : Lightning Framework Specific Attributes Type


Aura.Action

Use this type of attribute if you want to pass the reference of parent lightning component controller.js function to nested/child lightning component. This will help to invoke parent component JS function from child component markup.

Below is syntax to define this kind of attribute:

<aura:attribute name="parentJSFunction" type="Aura.Action"/>

This is useful if you want to make reusable component to appear based on values passed from parent and close/hide the component by invoking parent lightning component JS function.

I have created a sample component to explain how to invoke parent component function and child component function by passing "Aura.Action" attribute to child component.

Below is snapshot of Lightning component ("SK_AuraActionDemoCmp")  UI which contains child component ("SK_AuraActionChildCmp")  inside it.


Child component contains 2 buttons which will invoke JS function of parent and same component. Child component contains an attribute of type "Aura.Action" through which we will parent parent component JS function reference.

<aura:attribute name="closeChildDivFunction" type="Aura.Action" default="{!c.defaultCloseAction}"/>

If you don't pass JS function from parent component then child component will invoke its own JS function "defaultCloseAction".

If user click on these 2 buttons, then below things will happen:

  • If user clicks on "Close via Parent JS function" button,then complete content will also get removed and ltnguserActionMessage will display message saying "Close via Parent JS function button clicked. Please refresh your browser if you again want to load this demo component"

  • If user clicks on "Close via ChildCmp JS function" button,then only child component body will be removed and ltnguserActionMessage  will display message saying "Close via ChildCmp JS function button clicked.Please refresh your browser if you again want to load this demo component"



Please find below complete code reference:

Hope this will help!!


Thursday, November 1, 2018

Lightning:treegrid - Displaying Account hierarchy using treegrid

Salesforce has introduced new tag called lightning:treegrid which can be used to display tree structure in tabular form. Lightning:tree can be used to display the hierarchy but if you want to display additional information then lightning:treegrid becomes useful.

If you want to lean how to use lightning:tree tag to display hierarchy for any record then refer below URL:

Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject

If you have to display account hierarchy along with another fields information as displayed in below image, then use treegrid.


Below is complete code to display account hierarchy. Just pass account record Id and lightning component will display complete hierarchy.


Hope this help!!!

Tuesday, October 30, 2018

Aura.Component[] : Lightning Framework Specific Attributes Type

We know that there are different attribute types supported for attribute in lightning like Boolean, date, datetime, decimal, double, integer, long, string, collections (list,set,map), sobjects, user defined data types(wrapper class) etc.

Below are 2 different types which are supported as attribute type and specific to lightning framework:
  • Aura.Component[]
  • Aura.Action
In this blog, we are going cover all aspect of Aura.Component[] attribute type. If you are interested in learning more about Aura.Action, then refer below blog:

Aura.Action : Lightning Framework Specific Attributes Type

Aura.Component[]

An attribute of this type is considered as facet. You can use this in order to set markup to use it in multiple places.
You can consider it some what similar to defining templates with <apex:composition> in VF pages.

To set a default value for "Aura.Component[]", specify the default markup in the body of aura:attribute. For example:

<!--aurafacet.cmp-->
<aura:component>
<aura:attribute name="MarkupDetail" type="Aura.Component[]">
<p>Aura.Component[] default value</p>
</aura:attribute>
</aura:component>

So when this facet attribute(MarkupDetail) value is not set in component, then this default mark up will apear.

<aura:component>
    <c:aurafacet >        
        <!--we are not setting MarkupDetail attribute value so this will display 
default body specified in MarkupDetail attribute--> 
    </c:aurafacet>
</aura:component>

Output will be:

Aura.Component[] default value

Below is sample code which include different components and usage of Aura.Component[] in it. Also it will explain how to reuse the component body.

Below is output snapshot:

Points to be noted:

  • When we didn't set the attribute value of type Aura.Component[], then it display default body specified within Aura.Component[].
  • When we set attribute value of type Aura.Component[], component will render based on given values.
  • Different div are being getting created with different content in that.

Hope this helps!!!

Monday, October 29, 2018

Way to get complete RecordType Information (like DeveloperName) using describe

In summer'18 release, new methods have been introduced through which we can retrieve all recordtype info using describe information. Below are 2 methods introduced in summer'18:

  • Schema.DescribeSObjectResult.getRecordTypeInfosByDeveloperName()
  • Schema.RecordTypeInfo.getDeveloperName()

Suppose you want to retrieve all recordtype information for account object then use below code:

Below is console output

Hope this help!!

Thursday, October 4, 2018

Lightning Component Basics: Lightning Component Framework

In this blog, I am going to provide basic overview of lightning component framework.

Lightning component framework is being referred as MVCC modal.

  • Modal
  • View
  • Client-Side Controller
  • Server-Side Controller
In lightning components, Lightning bundle which contains component markup, controller.js (client-side), helper.js (for utility or reusable code) etc acts as primary interface and from client side controller, we can perform server side calls(apex class method invocations).

All calls from Lightning components to server are asynchronous call and we capture the response using callback function.

Below diagram will help you to understand Lightning component framework:


Hope this will help!!!

More Blogs:



Saturday, September 29, 2018

Lightning Components Basics : Considerations while calling server-side controller actions

In this blog, we will cover how to call apex class method from Lightning component and different considerations that we need to consider while performing server side call. Actually all calls to server for apex class routed through controller.js function. From lightning component, you can call controller.js function from where you can call apex method.

First of all in order to associate an apex class with lightning component, you have to specify apex class name in controller attribute.

Also remember that all apex methods or apex member variables needs to annotated with @AuraEnabled.

Below is sample apex class which will be called from lightning:

public class SK_LightningBasicsSSController {
    @AuraEnabled
    public static List<Account> findRecentAccounts(){
        return [select id,name,type from Account 
                order by LastmodifiedDate DESC Limit 10];
    }
}

In order to associated this class with lightning component, use below syntax:

<aura:component controller="SK_LightningBasicsSSController">
    <!-- you code-->
</aura:component>

Now we will call apex method on load of lightning component and will display returned list of accounts.

Below is process to call apex method from controller.js

//Create instance of apex method by using c. annotation followed by method name.
var actionName= component.get("c.findRecentAccounts");
//Specify the callback function as all calls are asynchronous. this callback will be invoked once //response is returned by apex class
actionName.setCallback(this, function(response) {
var state = response.getState();
 //Check response state for SUCCESS and ERROR
if (state === "SUCCESS") {
  //store the response in variable
var apexResponse=response.getReturnValue();
console.log('***'+JSON.stringify(apexResponse));
                //set response to attribute value
component.set("v.ltngAccountList",apexResponse);
}else if(state === "ERROR"){
var errors = response.getError();
console.error(errors);
alert('Problem with connection. Contact your system administrator.');
}
});
//do not forget to add below line as this put this request in queue for asynchronous call
$A.enqueueAction(actionName);

Below is complete code snippet:



Important Points to remember:

How to call apex method which contains parameters


If you have method defined with some parameter, for example search string to search account as mentioned below:

@AuraEnabled
Public static List<Account> SearchAccounts(string searchString){
       //your logic
}

So in order to pass parameters to apex class method, create a JSON as mentioned below:
Suppose you have an attribute defined to take input from user say AccName:

<aura:attribute name="AccName" type="string"/>

var actionName= component.get("c.SearchAccounts");
var params = {
                         "searchString" :component.get("v.AccName")
                      };
actionName.setParams(params);

Note:
  • While creating JSON for parameters, key Value should be similar to parameter name in apex method. In our case the apex method parameter name was "searchString" so while creating JSON we specified first key Value as "searchString".
  • If you have multiple parameters, then create JSON as mention below:
          var params ={
                                 "param1":"param value1",
                                 "param2": "param value2",
                                 "param3": "param value3"
                               };

Create helper function which can be reused for different apex method calls

Instead of writing same piece of code to call different apex methods, we can write function in helper.js which can be invoked from controller.js function by passing the parameters to it.

I have created a helper function which takes 4 parameters:
  • Component reference
  • apex class method name
  • callback function name
  • param (to specify parameters if apex method expect some parameters or arguments)
Below is helper function "callToServer"

({
callToServer : function(component, method, callback, params) {
        var action = component.get(method);
        if(params){
            action.setParams(params);
        }
        console.log('****param to controller:'+JSON.stringify(params));
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                callback.call(this,response.getReturnValue());
            }else if(state === "ERROR"){
                var errors = response.getError();
                console.error(errors);
                alert('Problem with connection.'+errors);
            }
        });
        $A.enqueueAction(action);
    }
})

Now if you have to call apex class method from controller.js then use below syntax:

({
    doInit : function(component, event, helper) {
        var params = {
                                 "searchString" :component.get("v.AccName")
                              };
        helper.callToServer(
            component,
            "c.SearchAccounts",
            function(response)
            {
                console.log('apex response :'+JSON.stringify(response));
                component.set("v.ltngAccountList",response);
            }, 
            params
        );
    }
})

How to call different apex methods in sequential order

All calls to apex methods are asynchronous so if there is need to first call a apex method and based on response call another apex method, then you need to make sure that you perform second call to server after getting the response from first function.
So always perform second call to server from inside the callback function which get invoked when asynchronous call finished on server. 

If you use helper function approach to call apex methods then you can use below syntax to call 2 different (searchAccounts and findAccountdetails) apex method in sequential order.

var param1= {
                         "searchString" :component.get("v.AccName")
                     };
helper.callToServer(
component,
"c.SearchAccounts",
function(response)
{
component.set("v.ltngAccountList",response);
var selectedId = response[0].id;
var param2 = {
"ltngAccId": selectedId
}
//creating component dynamically using helper function
helper.callToServer(
component,
"c.findAccountdetails",
function(response)
{
   //your logic
},
param2
);
}, 
param1
);

Use Wrapper to get all data in single call

Avoid multiple calls to server in order to fetch information as it will degrade the performance.
Use wrapper (user defined data types) to return complete information in single server call.


Hope this will help!!!