Ad
Ad
Ad
Tag

Slider

Browsing

 Dev Tip 3: Execute Batchjob from Anonymous Window/Dev Console

In this post, we will try to understand how to execute a Batch job from Dev Console. We could use the below command in the Execute Anonymous tab of Dev Console.

You could use any of the below Commands

Database.executebatch(new BatchjobName);

Database.executebatch(new BatchjobName,Size);

Example: We have a batch job AccountProcessBatch that needs to be executed with a default size.

Database.executebatch(new AccountprocessBatch());

Note: Default size for Batch job is 200.

Example: If we want our batch job (AccountProcessBatch)  to be executed with the desired size such as 500 then we will use the below command.

Database.executebatch(new AccountprocessBatch(),500);

In this post, We will try to understand what is recursion and how to solve recursion in Salesforce. Recursion is caused when the same code is executed multiple times which results in an Infinite loop execution. This, in turn, causes the Governor limits to be hit and the code/execution will result in an error.

Scenario: We want to update an Email field on Lead Object through the trigger(After update event) and if there is already an existing process builder/workflow with Same Email Field update then this results in Recursion.

How to Avoid Recursion: In order to avoid recursion, we need to Create a Static Variable with a Boolean flag and check the value in the trigger code.

public class recursionUtility{

     public static boolean isInitialrun =true;

}

In Lead trigger, we will try to use the utility code and skip the execution after the first run.

trigger LeadTrigger on Lead (after update){

    List<String>emailIdList =new List<String>();

     //Verify if the trigger already ran once

    if(recursionUtility.isInitialrun){

            //After the run set the isInitialrun flag to false as we do not want it to be executed multiple times.

        recursionUtility.isInitialrun =false;

        for(Lead ld : Trigger.New){

            if(ld.Email !=”){

                emailIdList.add(ld.Email);

            }

        }

        Update emailIdList;

    }

}

In this post, We will try to populate Map with List of Values. Whether we write a trigger, Apex class, or Batch Apex we encounter this Scenario.

Scenario 1:
We want to populate a Map with Account Id as the key and List of Contacts as Values. We will be iterating against the contact object and populating this map.

Note: We are populating a Map with List of Subject.

Map> AccountIdToContacts = new Map>();

for(Contact newCont : [SELECT AccountId FROM Contact LIMIT 50000]) {
if(AccountIdToContacts.containsKey(newCont.AccountId)) {
List conts = AccountIdToContacts.get(newCont.AccountId);
conts.add(newCont);
AccountIdToContacts.put(newCont.AccountId, conts);
} else {
AccountIdToContacts.put(newCont.AccountId, new List { newCont });
}
}

Scenario 2:
We want to populate a Map with Account Id as the key and List of Opportunities as Values.
We will be iterating against the Opportunity object and populating this map.
Note: We are populating a Map with List of String.

Map> AccountIdToOppIds = new Map>();
for(Opportunity newOpp : [SELECT AccountId FROM Opportunity LIMIT 50000]) {
if(AccountIdToOppIds.containsKey(newOpp.AccountId)) {
List oppIds = AccountIdToOppIds.get(newOpp.AccountId);
oppIds.add(newOpp);
AccountIdToOppIds.put(newOpp.AccountId, oppIds);
} else {
AccountIdToOppIds.put(newOpp.AccountId, new List { newOpp.Id });
}
}


31.  What is the difference between trigger.old and trigger.new?

Trigger.old contains lists of old records(old field values) and Trigger.new contains list of new records(new field values). Ex: If we have written a trigger on Account, trigger.new contains list of new Account records and trigger.old contains list of old Account records.

32. What is the difference between trigger.oldmap and trigger.newmap?

Trigger.oldmap contains map of oldSobjectrecords with key as Id’s and Trigger.newmap contains map of  Id’s of sobjectrecords.

Note: Trigger.oldmap is only available in update and delete Triggers. Trigger.newmap is only available in before update, after insert, after update, and after undelete triggers.

33. What are the different types of events in the trigger?

A trigger can be invoked with 7 events

Before insert, Before Update, After insert, After update, Before delete,After delete,After undelete

34. Explain best practices in Trigger?

We should write one trigger per object by defining all events. We should call a class from trigger to handle processing logic so that we can control the execution. Optionally we could also write event-based triggers per object but maintaining this would be difficult. Since we have 7 events we can have 7 triggers per object.

35. What is the default size of records that a trigger can process?

By default, the processing size of trigger is 200. But there are exceptions to this rule. For example: If we are loading records through data loader and you have changed the record size to 500 then the trigger will fire for 500 records at a time.

36. What are the operations that don’t invoke triggers?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_ignoring_operations.htm

37. What is bulkification?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bulk_idioms.htm

38. Can I perform DML Operations on trigger.new and trigger.old context variable?

No, you cannot perform DML Operations on trigger.new and trigger.old context Variable.

39. Explain Sample trigger code with different trigger events?

trigger myAccountTrigger on Account(before delete, before insert, before update, 

                                    after delete, after insert, after update) {

if (Trigger.isBefore) {

    if (Trigger.isDelete) {

        // In a before delete trigger, the trigger accesses the records that will be

        // deleted with the Trigger.old list.

        for (Account a : Trigger.old) {

            if (a.name != ‘okToDelete’) {

                a.addError(‘You can\’t delete this record!’);

            } 

        }

    } else {

    // In before insert or before update triggers, the trigger accesses the new records

    // with the Trigger.new list.

        for (Account a : Trigger.new) {

            if (a.name == ‘bad’) {

                a.name.addError(‘Bad name’);

            }

    }

    if (Trigger.isInsert) {

        for (Account a : Trigger.new) {

            System.assertEquals(‘xxx’, a.accountNumber); 

            System.assertEquals(‘industry’, a.industry); 

            System.assertEquals(100, a.numberofemployees);

            System.assertEquals(100.0, a.annualrevenue);

            a.accountNumber = ‘yyy’;

        }

// If the trigger is not a before trigger, it must be an after trigger.

} else {

    if (Trigger.isInsert) {

        List<Contact> contacts = new List<Contact>();

        for (Account a : Trigger.new) {        

            if(a.Name == ‘makeContact’) {

                contacts.add(new Contact (LastName = a.Name,

                                          AccountId = a.Id));

            }

        } 

      insert contacts;

    }

  }

}}}

  1. How can we call multiple methods in desired order in Lightning Component?

We can achieve these requirements in two ways.

  1. Using Callback for each method
  2. Using Javascript Promises
  3. What type of Interface is required in Lightning component to enable as Tab?

In order to add Lightning Component as a Tab, My domain needs to be enabled in the org.We have to use force:appHostable interface to a Lightning Component to allow it to be used as Custom tab

  1. What type of interface is required in Lightning component to be used as Quickaction?

We can use force:lightningQuickAction interface to a Lightning Component to allow it to be used as a Custom action in Lightning Experience or mobile app. These components can be used object-specific or global actions in both Lightning Experience/Mobile app

  1. How are Lightning Components migrated between the environments?

Lightning components can be deployed using Changesets,Eclipse Ide,Metadata API and ANT Migration Tool.

  1. What is the purpose of aura:method in Salesforce Lightning?

The main purpose of  aura:method is to define a method as part of a component’s API. This enables you to directly to call a method in a component’s client-side controller instead of firing and handling a component event. Using aura:method simplifies the code needed for a parent component to call a method on a child component that it contains.

26.How to access Apex methods in Lightning Component?

We have to use @AuraEnabled  method in the Apex class to be accessible in Lightning Component

27. How to bind Apex class with Lightning Component?

We have to specify Apex class name in the Lightning Component. For example if we have created “opportunityController” Apex class and want to bind with Lightning Component then we will have to specify the below statement in the Lightning Component.

28. Can we enforce Field level Security in Lightning Component?

Field Level Security and CRUD permissions are not automatically enforced in Lightning component when Apex classes are referenced. But FLS and CRUD are automatically enforced through Lightning Data Service.

11. What is Lightning Data Service?

Lightning data service helps you to perform CRUD(Create/Read/Update/Delete) operations on a record without Apex code. It will honor Field level security and sharing rules for us without any additional processing.

12.How to create components using Lightning Data Service?

We could use lightning:recordForm(Display/Create/Edit record) or lightning:recordEditForm (Create or edit Records with lightning:inputField) or lightning:recordViewForm(Display records with lightning:outputField) to create components. If we need additional customization then we can use force:recordData

13. What is the major limitation with Lightning Data Service?

We could use Lightning Data Service for only Single Record. It does not support multiple records.

14. What is Component Event propagation?

Component uses capture and Bubble phases for event propagation. These phases are similar to DOM handling patterns and interested components can interact with the event.

Capture Phase:
The event is captured and trickles down from the application root to the source component. The event can be handled by a component in the containment hierarchy that receives the captured event. Event handlers are invoked in order from the application root down to the source component that fired the event. Any registered handler in this phase can stop the event from propagating, at which point no more handlers are called in this phase or the bubble phase.

Bubble Phase: 
The component that fired the event can handle it. The event then bubbles up from the source component to the application root. The event can be handled by a component in the containment hierarchy that receives the bubbled event. Event handlers are invoked in order from the source component that fired the event up to the application root. Any registered handler in this phase can stop the event from propagating, at which point no more handlers are called in this phase.

15. What is the sequence of Event propagation?

 Event Fired –A component event is fired.

Capture Phase–The framework executes the captured phase from the application root to Source component until all components are traversed. Any handling event can stop the event propagation by calling stopPropagation() on the event.

Bubble phase — The framework executes the bubble phase from the Source component to the application root until all components are traversed or stopPropagation() is called.

16. How to create custom component Event in aura framework?

Use tag in .evt resource to create a custom component Event. Events can contain attributes that can be set before the event is fired and read when the event is handled.

17.  How to handle component events in aura framework?

A component event can be handled by the component that fired the event(Source component) or by a component in the component hierarchy/Parent components. 

Use <aura:event> tag in the markup of handler component

The name attribute in must match the name attribute in the tag in the component that fires the event.

Note: Component Event handlers are associated with bubble phase by default. We can use Phase attribute to change the handler to Capture phase.

18. What are Application events in aura framework?

Application events follow traditional publish-subscribe model. Application event is fired from an instance of the component and all components that provide a handler for the event are notified.

In this article, We will try cover Salesforce Lightning Interview Questions in detail

1. What is Lightning?

Lightning is a component framework that was built on Aura framework. We can build reusable blocks that could be used in Lightning experience, communities, and mobile. Salesforce mobile app was created on Aura framework and released in Dreamforce 2013.

2. What are different types of Lightning Events?

Lightning uses event-driven programming.In Aura framework events are fired from Javascript     Controller Actions. Events can contain attributes that can be set before the event is fired and read  when the event is handled.

 We have three different types of Lightning Events.

  1. Component Event
  2. Application Event
  3. Standard Event

3. Define Lightning Bundle?

 Lightning bundle contains different elements such as

  1. Application
  2. Controller(JavaScript)
  3. Helper(Reusable JavaScript within the component)
  4. Style
  5. Documentation
  6. Renderer
  7. Svg

4. What is Lightning Out functionality?

 Lightning out functionality is used to display lightning components in the Salesforce classic on Visualforce Page. We can also display Lightning apps on the External site using Lightning out functionality.

5. What is Lightning Locker Service?

  Lightning Locker Service helps in eliminating Cross-site Scripting attacks. If there are multiple components in the Lightning app then each component will not be able to access each other JS Component and also will not be able to access Real Dom/Window. Salesforce authored components run in System/admin mode and has access to everything. Custom components can access other components DOM as long as they are in the same namespace but won’t be able to access other DOM if they are in the different namespace when Lightning locker service is enabled.

https://developer.salesforce.com/blogs/developer-relations/2016/04/introducing-lockerservice-lightning-components.html

6. Can we communicate with Visualforce or Lightning Aura/Web components?

 Yes, Salesforce introduced  Lightning Message Service Api(beta as of Spring 2020) to communicate among Salesforce User Interfaces(DOM, Aura Components, Visualforce Pages and Lightning Web Components). A Lightning Web component uses a Lightning Message Channel to access the Lightning Message Service API. Reference Lightning Message Channel with the scoped module @salesforce/messageChannel. In Visualforce, use the global variable $MessageChannel. In Aura, use lightning:messageChannel in your component.

https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_lc_message_channel.htm

7. Prior Lightning Message API how did the communication happen between Visualforce and   Lightning Aura/Web components in Lightning Experience?

 Earlier we have to implement a custom Publish-Subscribe(Pub-sub) solution to communicate between Visualforce and Lightning Aura/Web components in Lightning Experience.

8. What is Component Event in Lightning?

  A component event could be handled by Parent components or the components above the Hierarchy. A component event could also be consumed by the source component that fired the event.

9. Does Lightning Component run Synchronously or asynchronously?

 Salesforce Lightning components are executed asynchronously.

10. Can we Integrate Third party JavaScript frameworks with Lightning?

Yes we can integrate 3rd party applications like Angular JS, Node JS and other Java script frameworks with Lightning.