Sunday, November 17, 2019

TOP 20 Salesforce Lightning Interview Questions

In this blog post, I am going to discuss "TOP 20 Salesforce Lightning Interview Questions" for Salesforce developers.

You can also visit my other "Salesforce Lightning Interview Questions" series using the below link.

Salesforce Lightning Interview Questions.

You can also visit my  "Scenario-Based Salesforce Lightning Interview Questions" series using the below link.

Scenario Based Interview Questions


1) What is  Lightning Component Framework and What is Aura Framework?


  • A lightning Component framework is a UI framework for developing single-page applications for mobile and desktop devices.
  • It uses JavaScript on the client-side and Apex on the server-side. 
  • The lightning Component framework makes developing apps that work on both mobile and desktop devices far simpler than many other frameworks.
  • The lightning component Framework is based on Aura Framework.
  • Aura Framework is designed by Salesforce which is open-source framework for creating UI components.

2) What are the different types of pages we can create using the lightning component and what are the different types of components supported in lightning pages?

  We can create different types of pages using lightning app builder as below,

1)App Page
2)Home Page
3)Record Page

Components type supported in Lightning pages:

1) Standard Components:

Standard components are Lightning components that are built by Salesforce.

2) Custom Components:

Custom components are Lightning components we create.

3) Third-Party Components on AppExchange

On AppExchange we can find packages containing components that are ready to use in the lightning app builder.


 3) What is the use of interface force:hasRecordId and How to obtain the id of the current record in lightning component?

By using force:hasRecordId interface in lightning component we can assigned the id of the current record to a lightning component. This interface adds an attribute named "recordId" to the component. The type of attribute is a string and has an 18-character Salesforce record ID.


4) What is the use of interface Lightning:actionOverride in Salesforce Lightning component?

Lightning:actionOverride  interface enables a component to be used as an override for a standard action. We can override the View, New, Edit, and Tab standard actions on most standard and all custom components. The component needs to implement the interface Lightning:actionOverride after which the component appear in the Lightning Component Bundle menu of an object action Override Properties panel.


5) What is the use of interface force:appHostable in Salesforce Lightning component?

Interface force:appHostable in component allow it to be used as a custom tab in Lightning Experience or the Salesforce mobile app.


6)  On a load of lightning component, you are required to execute some action what you will do to achieve this?

   We will use the "Init" Event which is also called the constructor of lightning component. The init event is called once the component construction is over.

   Basic Syntax:

<aura:handler  name="init" value="{!this}" action="{!c.doinit}"/>


7) you are asked to execute some action when value change is detected in one of the attribute what will you do?

  We will use the "change" Event.

  The change event is called when the value in one of the attribute changes.
  As an Example If i am having  attribute " Anyname", on change of attribute "Anyname" if i want to call javascript method i can do this as:

Syntax:

<aura:attribute name="Anyname" type="String" />
<aura:handler  name="change" value="{!v.Anyname}" action="{!c.doinit}"/>


8) What is component event in Salesforce Lightning component?

Component Events are fired by the child components and handled by the parent component.
We require parent-child relationship between two components if we want to use component event between them for communication.


9) What is application event in Salesforce Lightning component?

Application event is the event handle by any component no matter what relationship between them but they should be inside single application.


10) Explain Bound and Unbound expressions in Salesforce Lightning component?

We have two types of expression Bound expression and Unbound expression which we use to perform data binding in lightning components.

Let see two examples:

<c:ChildComp childAttributeName="{!v.parentAttributeName}" />   <!--Bound Expression-->

childAttributeName="{!v.parentAttributeName}" is a bound expression. Any change to the value of the childAttributeName attribute in child component also changes the value of parentAttributeName attribute in parent component and vice versa.

<c:ChildComp childAttributeName="{#v.parentAttributeName}" />    <!--Unbound Expression-->

childAttributeName="{#v.parentAttributeName}" is a Unbound expression. Any change to the value of the childAttributeName attribute in child component has no effect on the value of parentAttributeName attribute in parent component and vice versa.


11) What is Aura:method in Salesforce Lightning component?

We can directly call a child component controller method from the parent component controller method using Aura:method. This method is used to pass value from parent component controller to child component controller.


12)Whatis Lightning:recordForm, Lightning:recordEditForm, Lightning:recordViewForm in Salesforce Lightning component?

Lightning:recordForm

Lightning:recordViewForm

Lightning:recordEditForm


13) Explain Standard controller of lightning component (force:recordData)?

Lightning Data Service (LDS) act as the data layer for Lightning.
If we are not using LDS, every component within our app makes independent calls to the server to perform operations on a record, even if all components within our app are dealing with same record data. These are independent server calls which reduces performance.LDS identifies and eliminates requests that involve the same record data, sending a single shared data request that updates all relevant components,  it also provides a way to cache data to work offline in case the user gets disconnected, intelligently syncing the data once the connection is restored.If we have a Lightning application that creates, reads, updates, or deletes records, LDS is the best, most efficient way to do CRUD operations.

14) What is Lightning out ?

Lightning out is a feature by which we can use our lightning component inside of an external site. One of the best advantage is we can use our lightning component inside visualforce page.


15) How to use lightning component with Salesforce mobile app?

Make a tab for lightning component and include this tab in Salesforce1 mobile navigation.


16) What are the requirement to call a server side controller method from Javascript controller?

Method should be static and must be Aura enabled using @AuraEnabled.


17) What are different component bundles in Salesforce Lightning component?

A component bundle contains a component or an app and all its related resources.

When you build lightning component you deal with the following component bundles,


  • Component

  1.  Components contains markup for component or app.
  2.  The only required resource in a bundle.
  3. Each bundle contains only one component or app resource.
Ex: 

Mycomp.cmp(Sample component)

 or 

MycompApp.app(Sample app)
  • Controller
Controller is used to handle client side events in components.

Ex:

Mycontroller.js
  • Helper
Contains Javascript functions to handle logic.

Ex: Myhelper.js
  • Style
Contains styles for the component.

Ex: Mycomp.css
  • Documentation
Documentation includes description and example to demonstrate the use of component.

Ex: MyComp.auradoc
  • Renderer
Contains default rendering behavior for component, We can override this by custom renderer.

Ex: MyCompRenderer.js
  • SVG
It is a  custom icon resource for components that get displayed before the component name in lightning app builder or community builder.

Ex: MyComp.svg
  • Design
File required for components used in Lightning App Builder, Lightning pages, Community Builder, or Flow Builder.
  • App
App is used to run the component.


18) What is the difference between <lightning:input> and <ui:input> in Salesforce Lightning component?

<lightning:input> are equipped with Lightning Design System Stylling whereas <ui:input> is not equipped with Lightning Design System Stylling.


19) Explain the syntax to register the Component event?


Component:

<aura:component >

<!--Name is used to give some name say "registrationInChild" to event during registration and in the type we specify the event-->
    <aura:registerEvent name="registrationInChild" type="c:CompEvent"/> 
    <aura:attribute name="textMessage" type="String" default="Part from child comp"/>
    <lightning:button label="Click To Fire" onclick="{!c.doHandleEvent}"/>
</aura:component>


Component Event: (Name=CompEvent)

<aura:event type="COMPONENT" description="Event template" >

    <aura:attribute name="storeMessage" type="String"/>


</aura:event>


20) Explain the syntax to register the Application event? Is it compulsory to register the application event?

Component:

<aura:component >
<!--Name is used to give some name say "registrationInChild" to event during registration and in the type we specify the event-->
    <aura:registerEvent name="regInChild" type="c:AppEvent"/>
    <aura:attribute name="textMessage" type="String" default="Part from child comp"/>
    <lightning:button label="Click To Fire" onclick="{!c.doHandleEvent}"/>

</aura:component>

Application event:

<aura:event type="APPLICATION" description="Event template" >

  <aura:attribute name="storeMessage" type="String"/>
    

</aura:event>

No, It is not necessary to register the application event. It is optional. You can directly fire the event without registering.

TAGS:

salesforce interview questions,salesforce interview questions and answers,salesforce interview questions pdf,salesforce interview questions and answers,salesforce interview questions for experienced,salesforce interview questions for experienced developer,Salesforce lightning interview questions,salesforce lightning interview questions,salesforce lightning interview questions for experience,salesforce lightning interview questions and answers for experienced pdf,salesforce lightning admin interview questions,salesforce lightning scenario based interview questions,salesforce lightning mcq questions.

Monday, October 28, 2019

HOW TO CALL BATCH APEX CLASS FROM APEX TRIGGER IN SALESFORCE


Is it possible to call a batch apex from the trigger?

Yes it is possible, we can call a batch apex from trigger but we should always keep in mind that we should not call batch apex from trigger each time as this will exceeds the governor limit this is because of the reason that we can only have 5 apex jobs queued or executing at a time.

Now let’s see how we can call a batch apex from the trigger.

SCENARIO:  We are having the requirement that whenever a contact record is inserted we want a welcome email to be sent to contact email address and for this, we are asked to write a batch apex class which will be called from the trigger on “after insert “ event  on the contact record and will send emails to contact.

APEX TRIGGER:

trigger maintrigger on Contact (after insert) {
    Map<id,contact> IdContactMap=new Map<Id,contact>();
    for(Contact con:trigger.new){
        if(con.email!=Null){
            IdContactMap.put(con.id,con);
        }
    }
    if(IdContactMap.size() > 0){
        database.executeBatch(new MailToNewContact(IdContactMap)); // Calling batch class.
    }

}

BATCH APEX:

global class MailToNewContact implements Database.Batchable<sObject>
{
    Map<id,contact> IdContactMapBatch=new Map<id,contact>();
    global MailToNewContact(Map<id,contact> IdContactMap){
        IdContactMapBatch=IdContactMap;
    }
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator([SELECT id,firstname,email from contact where id in:IdContactMapBatch.keySet()]);
    }
    global void execute(Database.BatchableContext BC, List<Contact> scope) {     
        for(Contact con : scope)
        {    
           Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();
               email.setToAddresses(new string[] {con.email});
               email.setSubject('Welcome Mail');
               email.setPlainTextBody('Welcome Your Contact Is Created Successfully In Salesforce');
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
    }
    global void finish(Database.BatchableContext BC)
    {
    }
}

Now, let's try to insert 2 contacts at a time using .csv file as shown in the below image.

HOW TO CALL BATCH APEX CLASS FROM APEX TRIGGER IN SALESFORCE

can we call scheduled apex from trigger

call batch class from trigger

HOW TO DO CALLOUTS FROM APEX TRIGGER


In this blog post, we are going to see how we can do callouts from apex trigger.
As we know that trigger runs synchronously  we cannot make a callout to external system from trigger, this is because a trigger cannot wait for the execution to complete as this can cause performance issue, however an apex trigger can invoke a callout when the callout is made from a method which is defined as asynchronous.

Below is the sample structure to call Apex class method from trigger which makes callouts.

APEX TRIGGER:

trigger checkMeaningTrigger on checkMeaning__c (after insert) {
     if(avoidRecursionClass.booleanvar){
        avoidRecursionClass.booleanvar=false;     // Avoid recursion.
        populateMeaning.findMeaning(trigger.newmap.keyset()); // Passing ids of records.
     }
}

APEX CLASS:

public class populateMeaning {
    // Callout from trigger should be asynchronous
    @future(Callout=True)
    // Future method is always static
    // Getting the ids of the account
    public static void findMeaning(Set<id> IdSet){
        // CALLOUT CODE
    }
}   
 



SCENARIO: We are having the requirement that whenever a contact record is inserted in “Salesforce ORG1” we have to write a trigger on “After Insert” event on contact record which will call the apex class method and the method will do callout to other Salesforce org i.e (“Salesforce ORG2”) webservice. This webservice will insert the contact record in “Salesforce ORG2” with the information receives from “Salesforce ORG1”.

First of all, we have to create a connected app in “Salesforce ORG2” as shown in the below image. Also, create a remote site setting in “Salesforce ORG1” with URL of “Salesforce ORG2.


HOW TO DO CALLOUTS FROM APEX TRIGGER


REMOTE SITE Setting IN “Salesforce ORG1”.


how to call webservice from trigger in salesforce
Now the question is what is connected app?

For external application that needs to authenticate with Salesforce we need to create a connected app so as to inform Salesforce about the new authentication entry point. Connected app use standard OAuth 2.0 protocol to authenticate.

Note down the Consumer key, Consumer secret (We have to provide this information to “Salesforce ORG1”  for authentication purpose along with username, password, security token of user which “Salesforce ORG1”  will be using for authentication).

Now let’s create a trigger in “SALESFORCE ORG1” as shown below.

APEX TRIGGER:

trigger maintrigger on Contact (after insert) {
    Set<id> conIdSet=new Set<id>();
    for(Contact con:trigger.new){
        if(con.email!=Null){
            conIdSet.add(con.id);
        }
    }
    if(conIdSet.size() > 0){
        callWebserviceClass.getConList(conIdSet); // Calling apex class method
    }
}

Now let’s create a apex class “callWebserviceClass” in “SALESFORCE ORG1”.

APEX CLASS:

public class callWebserviceClass {
    private string cKey =’XXXXXXXXXXXXXXXXXXXXXX’;
    private string cSecret = ' XXXXXXXXXXXXXXXXXXXXXX ';
    private string uName = ‘XXXXXXXXXXXXXXXXXXXXXX’;
    private string passwd = ‘PASSWORD+SECURITYTOKEN’;
   
    public class responseWrapper {
        public string id;
        public string access_token;
        public string instance_url;
    }
    public string getRequestToken() {
        string reqBody = 'grant_type=password&client_id=' + cKey + '&client_secret=' + cSecret + '&username=' + uName + '&password=' + passwd;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqBody);
        req.setMethod('POST');
        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
        HttpResponse hresp = h.send(req);
        responseWrapper wResp = (responseWrapper) JSON.deserialize(hresp.getBody(), responseWrapper.class);
        system.debug('Instance url' + wResp.instance_url);
        system.debug('session id' + wResp.access_token);
        return wResp.access_token;
    }
    @future(callout = true)
    public static void getConList(Set < id > conIdSet) {
        String accToken;
        string responseBody;
        string endPoint = 'https://ap5.salesforce.com/services/apexrest/createContactRecord';
        callWebserviceClass obj = new callWebserviceClass();
        accToken = obj.getRequestToken();
        system.debug('access token' + accToken);
        if (accToken != '') {
            for (Contact con: [SELECT id, firstName, lastName, email from contact where id in: conIdSet]) {
                 system.debug('JSON' + JSON.serialize(con));
                Http h1 = new Http();
                HttpRequest req1 = new HttpRequest();
                req1.setHeader('Authorization', 'Bearer ' + accToken);
                req1.setHeader('Content-Type', 'application/json');
                req1.setMethod('POST');
                req1.setBody(JSON.serialize(con));
                req1.setEndpoint(endPoint);
                HttpResponse hresp1 = h1.send(req1);
                system.debug('hresp1' + hresp1);
            }
        }
    }
}

Now create a WEBSERVICE in “SALESFORCE ORG2” as  below.

@RestResource(urlMapping='/createContactRecord/*')
   global with sharing class createContactRecordCLass {
     @HttpPost
      global Static string fetchAccount(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
      Contact obj=new Contact();
      obj.firstName=wResp.FirstName;
      obj.lastName=wResp.LastName;
      obj.email=wResp.email;
      Insert obj;
       
        return 'Success';
      }
      global class responseWrapper{
       global string FirstName;
       global string LastName;
       global string email;
      }
   }


Now let’s try to upload  a  .csv file containing 2 contact records in “SALESFORCE ORG1” as shown in the below image.

how to call webservice from trigger in salesforce

HOW TO DO CALLOUTS FROM APEX TRIGGER
Now let’s see the result from “SALESFORCE ORG2” we have two contacts created in ORG2 as well.