salesforce email service

salesforce email service

Salesforce Email service is automated process that use Apex class to process inbound email. When we set up an email service, we need to generate a special email address in which salesforce will receive your emails. We also need to create one apex class to implement Messaging.InboundEmailHandler interface . The email services will then invoke a handleInboundEmail method on the Apex class whenever an email is received on the email address.

salesforce email service example

Lets create very simple email service which will create contact when an email is sent to salesforce.

Steps to create email service

  1. First of all we need to create Apex class that implement the Messaging.InboundEmailHandler interface. Its necessary to implement Messaging.InboundEmailHandler interface. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions. This class will handle email message.
    global class CreateContactFrmEmail implements Messaging.InboundEmailHandler {
        global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
                                                        Messaging.InboundEnvelope envelope) {
            Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
            String subToCompare = 'Create Contact';
            List<Attachment> attachmentList = new List<Attachment>();
            if(email.subject.equalsIgnoreCase(subToCompare)) {
                Contact c = new Contact();
                c.LastName = email.plainTextBody;
                insert c;
                
                // Save attachments, if any
                if(email.textAttachments!=null) {
                    for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                        Attachment attachment = new Attachment();
                        attachment.Name = tAttachment.fileName;
                        attachment.Body = Blob.valueOf(tAttachment.body);
                        attachment.ParentId = c.Id;
                        attachmentList.add(attachment);
                    }
                }
    
                //Save any Binary Attachment
                if(email.binaryAttachments!=null){
                    for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
                        Attachment attachment = new Attachment();
                        attachment.Name = bAttachment.fileName;
                        attachment.Body = bAttachment.body;
                        attachment.ParentId = c.Id;
                        attachmentList.add(attachment);
                    }
                }
    
                if(!attachmentList.isEmpty()){
                    insert attachmentList;
                }
            }
            result.success = true;
            return result;
        }
    }
    

     

  2. Create email service:
    Go to setup -> Email Service -> New Email Service. Add following details as per this imagesalesforce email service

    Click on Save or Save and New email address.

  3. Generate an email address from email service record
    Create new email address and add all details as per this image:salesforce email service email address

     

    Click on save. New email address will be created in related list. We need to send email to generated email address to test email service. You can copy email address from email service related list so that we can use it for testing.

  4. Testing email service by sending email:
    For testing send an email to this email id with subject ‘Create Contact’ and add some body which will be saved in last name. We can also add attachment(its optional) in email. As contact last name is required field on contact object, so it is necessary to enter text body in email.

For more details about email service please this link from salesforce.

Happy coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-email-service/

System.NullPointerException: Attempt to de-reference a null object

System.NullPointerException: Attempt to de-reference a null object

How to solve System.NullPointerException: Attempt to de-reference a null object error

System.NullPointerException: Attempt to de-reference a null object is very common error in apex class.  It occurs when your variable (sobject, list, set or any other data type) is not initialized (allocated memory). In order to use the non primitive data type in the code we need to initialize the memory first. If we don’t do that it may result in Attempt to de-reference a null object error. This error may occur in Apex classes, Visualforce pages with Apex controller, Test classes, Apex Triggers.

For Example if I use like this:

Account acc;
acc.Name = 'sfdcpoint';

It will result in attempt to de-reference a null object error.

We should use it like this:

Account acc = new Account();
acc.Name = 'sfdcpoint';

When we use list or set then also we need to allocate memory to list or set like this

List<Account> accList = new List<Account>();
Set<String> strSet= new Set<String>();

Same way this error can occur when we get null result from map and we try to use it in our code. For example we have accountMap with Id as key and Account as value:

Account accRecord = accountIdAccountMap.get(accId);
System.debug('*****accRecord.Name'+accRecord.Name);

Above code will also result in error. Here in above code accountIdAccountMap or  accRecord can be null. So we should do null check before using it like this.

if(accountIdAccountMap != null){
    Account accRecord = accountIdAccountMap.get(accId);
    if(accRecord != null){
        System.debug('*****accRecord.Name'+accRecord.Name);
    }
}

It is also very good practice to use isEmpty() method like this:

if(!accList.isEmpty()){
     //Do your dml or other operations here
}

As a best practice we should always do exception handling in our code like this

try{
    //Code here
}catch(Exception e){
    //Handle exception here
}

If you get System.NullPointerException. Its advisable to use System.debug to debug line of code which is resulting in this error and then fix it.

Here are salesforce official link for same error

Error in Apex code trigger

Error in Salesforce CPQ

For salesforc lightning interview questions refer to below link salesforce lightning

Happy coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/system-nullpointerexception-attempt-to-de-reference-a-null-object/

Assignment rules in Salesforce

Assignment rules in Salesforce

What are assignment rules in salesforce?

Assignment rules are used to automatically assign lead or Case to owner(User Or Queue). Its used to automate owner assignment on Case and Lead based on conditions on Case or Lead.

Types of assignment rules:

  • Lead Assignment Rules  : Specify how leads are assigned to users or queues as they are created manually, captured from the web, or imported via the Data Import Wizard.
  • Case Assignment Rules : Determine how cases are assigned to users or put into queues as they are created manually, using Web-to-Case, Email-to-Case, On-Demand Email-to-Case, the Self-Service portal, the Customer Portal, Outlook, or Lotus Notes.

Create or Setup assignment rules

  1. From Setup, enter Assignment Rules in the Quick Find box, then select either Lead Assignment Rules or Case Assignment Rules.
  2. Choose New, and then give the rule a name. Specify whether you want this to be the active rule for leads or cases created manually and via the web and email. Then click Save.
  3. To create the rule entries, click New. For each entry, you can specify:
  • Order : Sets the order in which the entry will be processed in the rule, for example, 1, 2, 3. Salesforce evaluates each entry in order and tries to match the criteria of the entry. As soon as a match is found, Salesforce processes the item and stops evaluating the rule entries for that item. If no match is found, the item is reassigned to either the default Web-to-Lead owner, the administrator doing a lead import, or the default case owner.
  • Criteria :Specifies conditions that the lead or case must match for it to be assigned.Enter your rule criteria.
      • Choose criteria are met and select the filter criteria that a record must meet to trigger the rule.For example, set a case filter to Priority equals High if you want case records with the Priority field marked High to trigger the rule. If your organization uses multiple languages, enter filter values in your organization’s default language. You can add up to 25 filter criteria, of up to 255 characters each. When you use picklists to specify filter criteria, the selected values are stored in the organization’s default language. If you edit or clone existing filter criteria, first set the Default Language on the Company Information page to the same language that was used to set the original filter criteria. Otherwise, the filter criteria may not be evaluated as expected.
      • Choose formula evaluates to true and enter a formula that returns a value of “True” or “False.” Salesforce triggers the rule if the formula returns “True.” For example, the formula AND(ISCHANGED( Priority ), ISPICKVAL (Priority, “High”) ) triggers a rule that changes the owner of a case when the Priority field is changed to High. If your condition uses a custom field, the rule entry will be deleted automatically if the custom field is deleted.
  • User : Specifies the user or queue to which the lead or case will be assigned if it matches the condition. Users specified here cannot be marked “inactive” and they must have “Read” permission on leads or cases.
  • Do Not Reassign Owner : Specifies that the current owner on a lead or case will not be reassigned to the lead or case when it is updated.
  • Email Template : Specifies the template to use for the email that is automatically sent to the new owner. If no template is specified, no email will be sent. When assigning a lead or case to a queue, the notification goes to the Queue Email address specified for the queue and all queue members.
  • Predefined Case Teams : Specifies the predefined case team(s) to add to a case when it matches the condition. A case team is a group of people that work together to solve cases.
  • Replace any existing predefined case teams on the case : Specifies that any existing predefined case teams on the case are replaced with the predefined case teams on the condition, when a case matches the condition.

After creating the entry, click Save, or Save & New to save the entry and create more entries.

Assignment Rule Example

Following is sample Case assignment rule which assigns case to different queues based on Billing Country, Account SLA and customer type:

Assignment rules in Salesforce

Assignment rules in Salesforce

For more details about assignment rules please refer to assignment rules official link.

Assignment rules in Salesforce trailhead

Good luck for creating Assignment rules in Salesforce 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/assignment-rules-in-salesforce/

Using apex:repeat in Visualforce Page

Using apex:repeat in Visualforce Page

Using apex:repeat in Visualforce Page

apex:repeat is an iteration component that allows you to output the contents of a collection according to a structure that you specify. The collection can include up to 1,000 items.

Note that if used within an <apex:pageBlockSection> or <apex:panelGrid> component, all content generated by a child <apex:repeat> component is placed in a single <apex:pageBlockSection> or <apex:panelGrid> cell.

This component can’t be used as a direct child of the following components:

  • <apex:panelBar>
  • <apex:selectCheckboxes>
  • <apex:selectList>
  • <apex:selectRadio>
  • <apex:tabPanel>

 

<apex:repeat> tag has following attributes

Attribute Name Attribute Type Description
firstIntegerThe first element in the collection visibly rendered, where 0 is the index of the first element in the set of data specified by the value attribute. For example, if you did not want to display the first two elements in the set of records specified by the value attribute, set first="2".
IdStringAn identifier that allows the repeat component to be referenced by other components in the page.
renderedBooleanA Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.
rowsIntegerThe maximum number of items in the collection that are rendered. If this value is less than the number of items in the collection, the items at the end of the collection are not repeated.
valueObjectThe collection of data that is iterated over.
varStringThe name of the variable that represents the current item in the iteration.

apex:repeat example

apex:repeat Visualforce page

<apex:page controller="repeatCon" id="thePage">
    <apex:repeat value="{!strings}" var="string" id="theRepeat">
        <apex:outputText value="{!string}" id="theValue"/><br/>
    </apex:repeat>
</apex:page>

apex:repeat Apex Code

public class repeatCon {
    public String[] getStrings() {
        return new String[]{'ONE','TWO','THREE'};
    }
}

For more details please refer below official link:

apex:repeat

Difference between apex:pageBlockTable and apex:repeat

When we use pageBlockTable then all salesforce styles are inherited. But when we use apex:repeat we have to manually add table tr td tags and all styles. Advantage of using apex:repeat is that we have more control on display of data.

Other similar post for visualforce

Permanent link to this article: http://www.sfdcpoint.com/salesforce/using-apexrepeat-in-visualforce-page/

Salesforce Governor Limits

Salesforce Governor Limits

What is Salesforce Governor Limits?

What are governor limits in salesforce?

Salesforce Governor Limits

Apex runtime engine strictly enforces limits to ensure that runaway Apex code or processes don’t monopolize shared resources.

Why Salesforce has Governor Limits?

Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits to ensure that runaway Apex code or processes don’t monopolize shared resources. If some Apex code exceeds a limit, the associated governor issues a runtime exception that cannot be handled.

Governor Limits in Salesforce

Type of Governor Limits

  • Per-Transaction Apex Limits
  • Per-Transaction Certified Managed Package Limits
  • Lightning Platform Apex Limits
  • Static Apex Limits
  • Size-Specific Apex Limits
  • Miscellaneous Apex Limit

In this post we will mainly cover Per-Transaction Apex Limits.

These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.

This table lists limits for synchronous Apex and asynchronous Apex (Batch Apex and future methods) when they are different. Otherwise, this table lists only one limit that applies to both synchronous and asynchronous Apex. This table can be used as cheat sheet.

Here is list of important governor limits in salesforce

  • Total number of SOQL queries issued : 200
  • Total number of SOSL queries issued : 20
  • Total number of DML statements issued : 150
  • Total number of records retrieved by SOQL queries : 50,000
  • Total number of records processed as a result of DML statements : 10,000

Here is full list of governor limits in salesforce

DescriptionSynchronous LimitAsynchronous Limit
Total number of SOQL queries issued100200
Total number of records retrieved by SOQL queries50,000
Total number of records retrieved by Database.getQueryLocator10,000
Total number of SOSL queries issued20
Total number of records retrieved by a single SOSL query2,000
Total number of DML statements issued150
Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin10,000
Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, or delete statements16
Total number of callouts (HTTP requests or Web services calls) in a transaction100
Maximum cumulative timeout for all callouts (HTTP requests or Web services calls) in a transaction120 seconds
Maximum number of methods with the future annotation allowed per Apex invocation50
Maximum number of Apex jobs added to the queue with System.enqueueJob50
Total number of sendEmail methods allowed10
Total heap size6 MB12 MB
Maximum CPU time on the Salesforce servers10,000 milliseconds60,000 milliseconds
Maximum execution time for each Apex transaction10 minutes
Maximum number of push notification method calls allowed per Apex transaction10
Maximum number of push notifications that can be sent in each push notification method call2,000

For more details about governor limit, please refer to below link Execution Governors and Limits

Avoiding Governor limits

From a Developer’s perspective, it is important to ensure that our code should be scalable and should not hit the governor limits. Its very important to follow some of best practices so that our code does not hit governor limit. These are some of best practices that we should follow:

  • Bulkify your Code
  • Avoid SOQL Queries or DML statements inside FOR Loops
  • Bulkify your Helper Methods
  • Using Collections, Streamlining Queries, and Efficient For Loops
  • Streamlining Multiple Triggers on the Same Object
  • Querying Large Data Sets
  • Use of the Limits Apex Methods to Avoid Hitting Governor Limits
  • Use @future Appropriately
  • Use batch apex if you are working for more than 50000 records.
  • Never make any SOQL, DML operation inside the loop.

For more details, refer this APEX best Practices

For other Salesforce post, please refer this link

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-governor-limits/

aura:if tag Lightning component example

aura:if tag Lightning component example

aura:if tag Lightning component example

aura if renders the content within the tag if the isTrue attribute evaluates to true. The framework evaluates the isTrue expression and instantiates components either in its body or else attribute.

Difference between aura if and aura renderIf

aura:if instantiates the components in either its body or the else attribute, but not both. aura:renderIf instantiates both the components in its body and the else attribute, but only renders one. If the state of isTrue changes, aura:if has to first instantiate the components for the other state and then render them. We recommend using aura:if instead of aura:renderIf to improve performance.

Example of using aura if

    <aura:attribute name="variable1" type="boolean" default="true"/>
    <aura:attribute name="variable2" type="boolean" default="false"/>
    <aura:attribute name="variable3" type="boolean" default="true"/>
    <aura:attribute name="variable4" type="boolean" default="false"/>
    
    <!--Example of aura:if-->
    <aura:if isTrue="{!v.variable1}">
        <div style="background-color:LightBlue">
    		This should be displayed as variable1 is true
        </div>
    </aura:if>

Example of aura if with aura set else attribute

Assuming that we have same 4 attributes available.

    <!--Example of aura:if with aura:set else attribute-->
    <aura:if isTrue="{!v.variable2}">
        <div style="background-color:LightBlue">
    		This should not be displayed as variable2 is false so else part will execute.
        </div>
        <aura:set attribute="else">
            <div style="background-color:LightBlue">
        		This should be displayed as if condition is not satisfied.
            </div>
    	</aura:set>
    </aura:if>

Example of using and condition with aura:if

    <!--Example of using AND condition with aura:if-->
    <aura:if isTrue="{!and(v.variable1, v.variable2)}" >
        <div style="background-color:LightBlue">
        	and Example. As variable1 is true and variable2 is false so nothing will be displayed.
        </div>
    </aura:if>

    <aura:if isTrue="{!and(v.variable1, v.variable3)}" >
        <div style="background-color:LightBlue">
        	and Example. As variable1 is true and variable3 is true so it will be displayed.
        </div>
    </aura:if>

Example of using or condition with aura if

    <!--Example of using OR condition with aura:if-->
    <aura:if isTrue="{!or(v.variable1, v.variable2)}" >
        <div style="background-color:LightBlue">
        	or Example. As variable1 is true and variable2 is false so it will be displayed.
        </div>
    </aura:if>
    <aura:if isTrue="{!or(v.variable2, v.variable4)}" >
        <div style="background-color:LightBlue">
        	or Example. As variable2 is false and variable4 is false so it will not be displayed.
        </div>
    </aura:if>

aura if multiple conditions

   <!--aura:if with complex or and condition-->
    <aura:if  isTrue="{!or(and(v.variable1, v.variable3) , v.variable2 ) }" >
        <div style="background-color:LightBlue">
            complex or and example. It will showup as variable1 is true, variable3 is true and variable2 is false
        </div>
    </aura:if>

aura if complete component example code

<aura:component >
    <aura:attribute name="variable1" type="boolean" default="true"/>
    <aura:attribute name="variable2" type="boolean" default="false"/>
    <aura:attribute name="variable3" type="boolean" default="true"/>
    <aura:attribute name="variable4" type="boolean" default="false"/>
    
    <!--Example of aura:if-->
    <aura:if isTrue="{!v.variable1}">
        <div style="background-color:LightBlue">
    		This should be displayed as variable1 is true
        </div>
    </aura:if>
    
    <!--Example of aura:if with aura:set else attribute-->
    <aura:if isTrue="{!v.variable2}">
        <div style="background-color:LightBlue">
    		This should not be displayed as variable2 is false so else part will execute.
        </div>
        <aura:set attribute="else">
            <div style="background-color:LightBlue">
        		This should be displayed as if condition is not satisfied.
            </div>
    	</aura:set>
    </aura:if>
    
    <!--Example of using AND condition with aura:if-->
    <aura:if isTrue="{!and(v.variable1, v.variable2)}" >
        <div style="background-color:LightBlue">
        	and Example. As variable1 is true and variable2 is false so nothing will be displayed.
        </div>
    </aura:if>
    
    <aura:if isTrue="{!and(v.variable1, v.variable3)}" >
        <div style="background-color:LightBlue">
        	and Example. As variable1 is true and variable3 is true so it will be displayed.
        </div>
    </aura:if>
    
    <!--Example of using OR condition with aura:if-->
    <aura:if isTrue="{!or(v.variable1, v.variable2)}" >
        <div style="background-color:LightBlue">
        	or Example. As variable1 is true and variable2 is false so it will be displayed.
        </div>
    </aura:if>
    <aura:if isTrue="{!or(v.variable2, v.variable4)}" >
        <div style="background-color:LightBlue">
        	or Example. As variable2 is false and variable4 is false so it will not be displayed.
        </div>
    </aura:if>
    
    <!--aura:if with complex or and condition-->
    <aura:if  isTrue="{!or(and(v.variable1, v.variable3) , v.variable2 ) }" >
        <div style="background-color:LightBlue">
            complex or and example. It will showup as variable1 is true, variable3 is true and variable2 is false
        </div>
    </aura:if>
    
</aura:component>

Sample App for LightningComponentAuraIfExample

<aura:application >
    <c:LightningComponentAuraIfExample/>
</aura:application>

aura if output will be

aura if tag Lightning component example output

aura if tag Lightning component example output

For more detail please refer below official link

Salesforce Lightning Interview Questions

Happy Coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/auraif-tag-lightning-component-example/

apex random number Salesforce

apex random number Salesforce

apex random number Salesforce

Many time we have requirement to generate random number in Apex. It can be achieved using Math.random() function. This method return a positive Double that is greater than or equal to 0.0 and less than 1.0.

This method only returns number between 0.0 and 1.0. Now its important how we can use this method to generate different variation of random number that we need based on our requirements. Lets see some examples of getting random number.

Get random number between 0 and 10 Apex

Integer randomNumber = Integer.valueof((Math.random() * 10));
System.debug('randomNumber  is'+randomNumber);

Get random number between 0 and 100 Apex

Integer randomNumber = Integer.valueof((Math.random() * 100));
System.debug('randomNumber is'+randomNumber);

Get random Boolean value Apex

Integer randomNumber = Integer.valueof((math.random() * 10));
Boolean randomBoolean = Math.mod(randomNumber,2) == 0 ? true : false;
System.debug('randomBoolean is'+randomBoolean);

Get random String from list of strings Apex

List<String> availableValues = new List<String>{'Red','Green','Blue','White','Black'};
Integer listSize = availableValues.size() - 1;
Integer randomNumber = Integer.valueof((Math.random() * listSize));
String randomString= availableValues[randomNumber];
System.debug('randomString is'+randomString);

 

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/apex-random-number-salesforce/

Delete Lightning Component in Salesforce

Delete Lightning Component in Salesforce

Delete Lightning Component in Salesforce is very easy. If we don’t want to use IDE like sublime or Eclipse then we can use developer console.

  1. Open Developer Console
  2. Open Your lightning component from File -> Open Lightning Resource
  3. Click on File Delete or use shortcut Ctrl+Delete
Delete Lightning Component in Salesforce

Delete Lightning Component in Salesforce

 

Salesforce Lightning Interview Questions

Lightning Component Library

Permanent link to this article: http://www.sfdcpoint.com/salesforce/delete-lightning-component-in-salesforce/

salesforce order of execution

salesforce order of execution

What is salesforce order of execution?

What is order of execution in salesforce?

salesforce order of execution

When you save a record with an insertupdate, or upsert statement, Salesforce performs the following events in order.

Before Salesforce executes these events on the server, the browser runs JavaScript validation if the record contains any dependent picklist fields. The validation limits each dependent picklist field to its available values. No other validation occurs on the client side.

Salesforce order of execution

Salesforce order of execution

 

Here is order of execution in salesforce

  • The original record is loaded from the database.
  • System Validation Rules.
  • Executes all before triggers.
  • Custom Validation rules.
  • Executes duplicate rules.
  • Saves the record to the database, but doesn’t commit yet.
  • Executes all after triggers.
  • Executes assignment rules.
  • Executes auto-response rules.
  • Executes workflow rules.
  • If there are workflow field updates, updates the record again.
  • If the record was updated with workflow field updates, fires before and after triggers one more time. Custom validation rules, duplicate rules, and escalation rules are not run again.
  • Executes processes and flows launched via processes and flow trigger workflow actions.
  • Executes escalation rules.
  • Executes entitlement rules.
  • If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  • If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure.
  • Executes Criteria Based Sharing evaluation.
  • Commits all DML operations to the database.
  • Executes post-commit logic, such as sending email.

 

Here is order of execution in salesforce in more detail:

On the salesforce server,

  1. Loads the original record from the database or initializes the record for an upsert statement.
  2. Loads the new record field values from the request and overwrites the old values.

    If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:

    • Compliance with layout-specific rules
    • Required values at the layout level and field-definition level
    • Valid field formats
    • Maximum field length

    When the request comes from other sources, such as an Apex application or a SOAP API call, Salesforce validates only the foreign keys. Before executing a trigger, Salesforce verifies that any custom foreign keys do not refer to the object itself.

    Salesforce runs user-defined validation rules if multiline items were created, such as quote line items and opportunity line items.

  3. Executes all before triggers.
  4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
  5. Executes duplicate rules. If the duplicate rule identifies the record as a duplicate and uses the block action, the record is not saved and no further steps, such as after triggers and workflow rules, are taken.
  6. Saves the record to the database, but doesn’t commit yet.
  7. Executes all after triggers.
  8. Executes assignment rules.
  9. Executes auto-response rules.
  10. Executes workflow rules.
  11. If there are workflow field updates, updates the record again.
  12. If the record was updated with workflow field updates, fires before update triggers and after update trigger one more time (and only one more time), in addition to standard validations. Custom validation rules, duplicate rules, and escalation rules are not run again.
  13. Executes processes and flows launched via processes and flow trigger workflow actions.( process builder)

    When a process or flow executes a DML operation, the affected record goes through the save procedure.

  14. Executes escalation rules.
  15. Executes entitlement rules.
  16. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  17. If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure.
  18. Executes Criteria Based Sharing evaluation.
  19. Commits all DML operations to the database.
  20. Executes post-commit logic, such as sending email.

Additional Considerations

Note the following when working with triggers.

The order of execution isn’t guaranteed when having multiple triggers for the same object due to the same event. For example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the order in which these triggers fire isn’t guaranteed.

Please refer to below official link for salesforce order of execution:

Trigger and Order of Execution

For interview questions related to trigger, refer to below link:

Salesforce Interview Questions on Triggers

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-order-of-execution/

Trigger context variables in salesforce

Trigger context variables in salesforce

What are Trigger context variables in salesforce?

Trigger context variables in salesforce

All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.

Following are the context variable available in triggers. Please note variable availability in trigger varies according to the type of trigger events.

Here is List of Trigger Context Variables

  • isExecuting: Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
  • isInsert: Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
  • isUpdate: Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
  • isDelete: Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
  • isBefore: Returns true if this trigger was fired before any record was saved.
  • isAfter: Returns true if this trigger was fired after all records were saved.
  • isUndelete: Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
  • new: Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
  • newMap: A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
  • old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
  • oldMap: A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
  • size: The total number of records in a trigger invocation, both old and new.

 

Trigger Context Variables Considerations

  • trigger.new and trigger.old cannot be used in Apex DML operations.
  • You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown.
  • trigger.old is always read-only.
  • You cannot delete trigger.new.

 

For interview questions related to trigger, refer to below link:

Salesforce Interview Questions on Triggers

For more details about context variable, please refer to below official link:

Trigger Context Variables in Salesforce

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/trigger-context-variables-in-salesforce/