Salesforce Certified Application Architect

Friday 16 March 2018

Type of events into Salesforce Lightning component

1. What are the type of events into Salesforce Lightning component?
a. Application Event – Scope of this event is throughout the lightning App and any component which has registered for this event would get a notification.
b. Component Event– Scope of this event is within itself or the parent component of this event, all the components declared within the parent component would get notified of this event.
c. System Event- these are the events fired by Salesforce’s system during the lifecycle of the lightning app.
2. What are the basic differences between Application Event and Component Event?
Component events are used to do communication between child and parent. They use bubbling and capture same as used in DOM events. A change in a child component can be communicated to the parent component via component event.
Application events are used to communicate any change in the component to a broader audience. Any component who has registered for this event will get a notified.
To use Component Event API we use the below syntax

Thursday 8 February 2018

System.LimitException: Apex CPU time limit exceeded

The Apex CPU time limit exceeded error is a standard Salesforce error which occurs when the salesforce governor limit to run the Apex code has exceeded.The maximum CPU time to run the Apex code on the Salesforce servers is:
  • ​10,000 milliseconds (Synchronous limit)  
  • 60,000 milliseconds (Asynchronous limit)
below are the methods where we can get the CPU time and CPU limit.

Limits.getCPUTime() - Returns the CPU time(in milliseconds) accumulated on the salesforce.com server in the current transaction.

Limits.getLimitCPUTime() - Returns the total CPU time (in milliseconds) accumulated on the salesforce.com servers in the current transaction.


Example :

 Below code error is coming due to FOR inside FOR loop.
Set<String> setDependantValue = new Set<String>();
        for(Payment_Process__c objPicklistValues : lstProduct_Line){
            setDependantValue.add(objPicklistValues.Payment_Name__c);
        }
        Map<String, List<String>> mapDependantControllingValue = new Map<String, List<String>>();
        for(String objDepVal : setDependantValue){
            List<String> lstControllingValues = new List<String>();
            for(Payment_Process__c objPicklistValues : lstProduct_Line){
                if(objDepVal == objPicklistValues.Payment_Name__c){
                    lstControllingValues.add(objPicklistValues.Product_Family_Name__c);
                }
            }
            mapDependantControllingValue.put(objDepVal, lstControllingValues);
        } 


Solution : 
 Issue is resolved by following optimized code.
 Map<String, List<String>> mapDepValContVal = new Map<String, List<String>>();
        for(Payment_Process__c prdLine : lstProduct_Line){
            List<String> lstControllingValues = mapDepValContVal.get(prdLine.Line__c);
            if(lstControllingValues == null)
                lstControllingValues = new list<String>();
            lstControllingValues.add(prdLine.Family__c);
            mapDepValContVal.put(prdLine.Line__c, lstControllingValues);
        } 

How to register, fire and handle a component and application event?

We register an event by by using the following code:

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

We fire event as shown below:
var compEvent = cmp.getEvent(“sampleComponentEvent”);

compEvent.fire();

Handle component event as below :

<aura:handler name=”sampleComponentEvent” event=”ns:eventName”

    action=”{!c.handleComponentEvent}” phase=”capture” />

Handle Application event as below:
<aura:handler event=”c:appEvent” action=”{!c.handleApplicationEvent}”/>





Lightening interview questions 2018

Please refer below link :
http://www.salesforcenextgen.com/salesforce-lightning-interview-questions-2018/amp/

Tuesday 6 February 2018

Lightening Component Demo

Please refer below link :
https://lightningdart.com/demo.html

Building Custom “Loading..” Spinners In Lightning Components

Please refer Salesforce Developers Blog link :

https://developer.salesforce.com/blogs/developer-relations/2015/06/svg.html

Salesforce Lightning Interview Questions

1. What are the different types of Lightning events?

  • Browser: browser notifications that are triggered by user interaction with an element. Eg. onClick
  • System: fired by LC framework during LC lifecycle. They notify component states. Eg. init, render, afterRender
  • Navigation: force:navigateToURL, force:createRecord, force:editRecord
  • Component: A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.
  • Application: Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.


2. How to register, fire and handle a component and application event?
<aura:registerEvent name="componentEventFired" type="c:compEvent"/>
<aura:registerEvent name="appEvent" type="c:appEvent"/>

var compEvents = cmp.getEvent("componentEventFired");
compEvents.setParams({ "context" : parentName });
compEvents.fire();

var appEvent = $A.get("e.c:appEvent");
appEvent.setParams({ "context" : parentName });
appEvent.fire();
...
...
...
...
...
<aura:handler event="c:appEvent" action="{!c.handleApplicationEventFired}"/>
<aura:handler name="componentEventFired" event="c:compEvent" 
 action="{!c.handleComponentEventFired}"/>

{
 handleComponentEventFired : function(cmp, event) {
  var context = event.getParam("context");
 },

 handleApplicationEventFired : function(cmp, event) {
  var context = event.getParam("context");
 }
}
For more details, check the link below:
http://hellosnl.blogspot.in/2017/06/lightning-advanced-events-example.html


3. Let's say that you have an app myApp.app that contains a component myCmp.cmp with a ui:button component. During initialization, the init() event is fired in what order?
Answer: ui:button, ui:myCmp, and myApp.app.


4. Why do we use @AuraEnabled annotation?
  • Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning components.
  • Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is returned as data from a server-side action

5. Why do we use $A.enqueueAction(action)?
It adds the server-side controller action to the queue of actions to be executed. Rather than sending a separate request for each individual action, the framework processes the event chain and batches the actions in the queue into one request. The actions are asynchronous and have callbacks.


6. What is Namespace?
It is used to group related components together.


7. What is LockerService?
It enhances security by isolating Lightning components in their own namespace. A component can only traverse the DOM and access elements created by a component in the same namespace.


8. Examples of how to use some of the out-of-the-box events to enable component interation within your Lightning components?
$A.get("e.force:refreshView").fire(): reloads all data for the view.

createRecord : function (component, event, helper) {
    var createRecordEvent = $A.get("e.force:createRecord");
    createRecordEvent.setParams({
        "entityApiName": "Contact"
    });
    createRecordEvent.fire();
}

editRecord : function(component, event, helper) {
    var editRecordEvent = $A.get("e.force:editRecord");
    editRecordEvent.setParams({
         "recordId": component.get("v.contact.Id")
   });
    editRecordEvent.fire();
}


9. What is Lightning CLI?
It is a Heroku Toolbelt plugin that lets you scan your code for general JavaScript coding issues and lightning-specific issues.


10. Difference between bound and unbound expressions.
Bound expression {!expression}
  • Any change to the value of the childAttr attribute in c:child also affects the parentAttr attribute in c:parent and vice versa.
  • When you use a bound expression, a change in the attribute in the parent or child component triggers the change handler in both components.
Unbound expression {#expression}
  • Any change to the value of the childAttr attribute in c:child doesn’t affect the parentAttr attribute in c:parent and vice versa.
  • When you use an unbound expression, the change is not propagated between components so the change handler is only triggered in the component that contains the changed attribute.
For more details, check this link: http://hellosnl.blogspot.in/2017/05/data-binding-between-components.html


11. Use of THIS CSS class?
This adds namespacing to CSS and helps prevent one component's CSS from blowing away another component's styling.


12. How to set the value of an inherited attribute?
Use the <aura:set> tag.


13. What are the different ways to conditionally display markup, and what is the preferred approach?
Using the <aura:if> tag
Use CSS to toggle visibility of markup by calling $A.util.toggleClass(cmp, 'class') in JavaScript code.


14. What is $Resource global value provider? Is it possible to obtain a reference to a static resource in Javascript code?
It lets you reference images, style sheets, and JavaScript code you’ve uploaded in static resources.
To obtain a reference to a static resource in JavaScript code, use $A.get('$Resource.resourceName').
For more details, check this link http://hellosnl.blogspot.in/2017/04/lightning-using-static-resources.html


15. Let’s say you have several buttons that reuse the same onclick handler. How will you retrieve the name of the button that fired the event?
http://hellosnl.blogspot.in/2017/05/which-button-was-pressed.html


16. What are the names of interfaces that are added to a Lightning component to allow it to be used as custom tabs, and to be used in Lightning and Community builder?
http://hellosnl.blogspot.in/2017/05/configuring-lightning-components.html


17. What is the use of force:hasRecordId interface?
Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record.
The recordId attribute is set only when you place or invoke the component in a context of a record. For example, when you place the component on a record page, or invoke it as an action from a record page or object home. In all other cases, such as when you create this component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.


18. How to delete a design attribute for a component that implements the flexipage:availableForAllPageTypes or forceCommunity:availableForAllPageTypes interface?
First remove the interface from the component before deleting the design attribute. Then reimplement the interface. If the component is referenced in a Lightning page, you must remove the component from the page before you can change it.


19. How to add Lightning components to your Visualforce pages?
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_visualforce.htm

Access SOQL data in Lightning component

public class AccountContactController {
    @AuraEnabled
    public static List<Account> fetchAccount() {
        List<Account> listOfAccounts = [SELECT Name, AnnualRevenue, 
        BillingState, 
      (SELECT LastName FROM contacts) FROM Account LIMIT 10];
        return listOfAccounts;
    }
}
 
<aura:component controller="AccountContactController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="Accounts" type="Account[]"/>
    <ul>
        <aura:iteration items="{!v.Accounts}" var="account">
       <li>AccountName: {!account.Name}</li>
        <ul>
        <aura:iteration items="{!account.Contacts}" var="contact"  
        indexVar="index">
        <li>Contact {!index + 1} : {!contact.LastName}</li>
        </aura:iteration>
            </ul>
            <hr/>
        </aura:iteration>
    </ul>
</aura:component> 
 
 
 
({
    doInit: function(component, event, helper) {
        var action = component.get('c.fetchAccount');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
          component.set('v.Accounts', response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
}) 

AuraHandledException in Lightening

From Apex class:

    @AuraEnabled
    public static List<Account> fetchAccount() {
        throw new AuraHandledException('User-defined error');
    }
  From client-side controller:
  doInit: function(component, event, helper) {
        var action = component.get('c.fetchAccount');
        action.setParams({ firstName : cmp.get("v.firstName") });
        action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
        component.set('v.Accounts', response.getReturnValue());
        }
        else if (component.isValid() && state === "ERROR") {
     console.log("Error Message: ", response.getError()[0].message);
        }
        });
        $A.enqueueAction(action);
    } 

LockerService: DOM Access Containment

LockerService enhances security by isolating Lightning components in their own namespace. Due to this, a component can only traverse the DOM and access elements created by a component in the same namespace. Let’s look at a sample component that demonstrates DOM containment.


<!--c:domLocker-->
<aura:component>
    <div id="myDiv" aura:id="div1">
        <p>See how LockerService restricts DOM access</p>
    </div>
    <lightning:button name="myButton" label="Peek in DOM"  
    aura:id="button1" onclick="{!c.peekInDom}"/>
</aura:component>

({ /* domLockerController.js */
    peekInDom : function(cmp, event, helper) {
        console.log("cmp.getElements(): ", cmp.getElements());
        // access the DOM in c:domLocker
        console.log("div1: ", cmp.find("div1").getElement());
        console.log("button1: ", cmp.find("button1"));
        console.log("button name: ",
        event.getSource().get("v.name"));

        // returns an error
        //console.log("button1 element: ", 
         cmp.find("button1").getElement());
    }
})

You can't use cmp.find("button1").getElement() to access the DOM element created by <lightning:button>. LockerService doesn't allow c:domLocker to access the DOM for <lightning:button> because the button is in the lightning namespace and c:domLocker is in the c namespace.

So, use cmp.find("myInput").get("v.name") instead of cmp.find("myInput").getElement().name. The latter doesn’t work if you don’t have access to the component, such as a component in another namespace.

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...