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?

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.

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 salesforce governor limits cheat sheet.

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/

Salesforce security interview questions

Salesforce security interview questions

Salesforce security interview questions or data and security salesforce interview questions

There are different levels of security that is implemented in Salesforce. This post is related to data and security.

What are different Levels of data access in Salesforce?

Organization level security

For your whole org, you can maintain a list of authorized users, set password policies, and limit logins to certain hours and locations.

Object level security

Access to object-level data is the simplest thing to control. By setting permissions on a particular type of object, you can prevent a group of users from creating, viewing, editing, or deleting any records of that object. For example, you can use object permissions to ensure that interviewers can view positions and job applications but not edit or delete them.

Field level security

You can restrict access to certain fields, even if a user has access to the object. For example, you can make the salary field in a position object invisible to interviewers but visible to hiring managers and recruiters.

Record level security

You can allow particular users to view an object, but then restrict the individual object records they’re allowed to see. For example, an interviewer can see and edit her own reviews, but not the reviews of other interviewers. You can manage record-level access in these four ways.

  • Organization-wide defaults
  • Role hierarchies
  • Sharing rules
  • Manual sharing

 

What is Organization-wide defaults?

Organization Wide Defaults(OWD) in salesforce is the baseline level of access that the most restricted user should have. Organizational Wide Defaults are used to restrict access. You grant access through other means like(sharing rules, Role Hierarchy, Sales Teams and Account teams, manual sharing, Apex Sharing ). In simple words Organization Wide Defaults(OWD) specify the default level of access users have to each other’s records.

For more details please level to below post Organization Wide Defaults(OWD) in salesforce

What is role hierarchy?

It give access for users higher in the hierarchy to all records owned by users below them in the hierarchy. Role hierarchies don’t have to match your organization chart exactly. Instead, each role in the hierarchy should represent a level of data access that a user or group of users needs.

What are Sharing Rules?

Sharing Rules are automatic exceptions to organization-wide defaults for particular groups of users, so they can get to records they don’t own or can’t normally see. Sharing rules, like role hierarchies, are only used to give additional users access to records. They can’t be stricter than your organization-wide default settings.

What is Manual sharing?

It allows owners of particular records to share them with other users. Although manual sharing isn’t automated like org-wide sharing settings, role hierarchies, or sharing rules, it can be useful in some situations, such as when a recruiter going on vacation needs to temporarily assign ownership of a job application to someone else.

For more details related to salesforce security please refer to this trailhead module Data Security

I will keep adding more questions to Salesforce security interview questions.

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-security-interview-questions/

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

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.

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 triggers 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.

    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 more details:

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 is 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.

  • 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.

 

Context Variable 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 Variable

 

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

Salesforce Interview Questions on Triggers

Salesforce Interview Questions on Triggers

In this post I am going to share Salesforce Interview Questions on Triggers

What is a Trigger?

Apex triggers enable you to perform custom actions before or after events to records in Salesforce, such as insertions, updates, or deletions. Just like database systems support triggers, Apex provides trigger support for managing records.

Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.

What is Trigger Syntax?

trigger TriggerName on ObjectName (trigger_events) {
   code_block
}

What are the various event on which a trigger can fire?

A trigger is a set of statement which can be executed on the following events. In above trigger events one or more of below events can be used with comma separated.

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

What are different type of Triggers?

There are two types of triggers:

  • Before triggers are used to perform a task before a record is inserted or updated or deleted. These are used to update or validate record values before they are saved to the database.
  • After triggers are used if we want to use the information set by Salesforce system and to make changes in the other records. are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.

What are the considerations while implementing the Triggers?

Consider the following before implementing the triggers.

  • Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)
  • Merge trigger are fired on both events on delete
  • Field history is updated after the trigger has successfully finished processing data.
  • Any callout should be asynchronous so that trigger does not have to wait for the response.
  • A trigger cannot have a static keyword in its code.
  • If a trigger completes successfully the changes are committed to the database and if it fails the transaction is rolled back.

Read the Apex Developer Guide for more detailed considerations.

What are context variables in triggers?

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.

  • 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.

Refer to Trigger context variables in salesforce link for more details.

How is Trigger.New Different from Trigger.newMap?

Trigger.New variable returns the list of sObject which has invoked the trigger and Trigger.NewMap returns the map of ID’s with the newly entered records. NewMap is only available in after insert, before and after the update and after undelete.

How is Trigger.new different from Trigger.old?

Trigger.New variable returns the list of sObject which has invoked the trigger and Trigger.old returns a list of the older versions of the records which have invoked the trigger. Trigger.Old is only available in update and delete events

Can a trigger call a batch class?

Yes, we can call a batch class in the trigger as we do in the normal apex code.

Can a trigger make a call to Apex callout method?

we can call a callout method in Apex Trigger but the only condition is that it has to be an asynchronous callout because the trigger flow cannot wait on the response received by the callout method.

Define Recursive Trigger and how to avoid it?

There is a possibility that the result of the trigger can end up calling the same trigger again and can run in a loop, this is known as a recursive trigger. To avoid this scenario we should create a static variable and check the value of this variable before we execute anything in the trigger. For more details refer to below link:

Avoid recursive trigger in salesforce

What do you mean by the bulkifying trigger?

A trigger should be able to handle single record and thousands of record. There are two important point for it:

  • Write triggers that operate on collections of sObjects.
  • Write triggers that perform efficient SOQL and DML operations.

If we will not follow above point we may hit governor limit when records are created/updated/deleted in mass using data loader or other tool.

Bulk Apex Trigger trailhead

Is there any limit on number of triggers define on an object?

We can define as many triggers on an object as we want but it is recommended to have one trigger per object because the order of execution of different trigger is not guaranteed and any trigger can fire first.

Can you explain the order of execution in Triggers?

Following is the order of execution of events which Salesforce perform before a DML Event.

  1. The record is loaded from the database or is initialized in case of upset statement.
  2. New record’s field values are overwriting the old values, now depending on the origin of the request this flow varies: if the request is from a UI page then the following validations are performed by Salesforce:
    1. Any layout specific rules are checked
    2. All the required values are checked at layout and field level
    3. All the field formats are validated along with the maximum length of field values

If the request originates other than UI then Salesforce only checks for Validation of foreign keys.

  1. Now all the before triggers are executed at the database.
  2. Most of the validations are performed again to verify that all the required fields are holding some values and are not null, at this step user defined validations are also executed and the only validation which is not repeated in this step are the rules specific to the layout.
  3. After the success of the previous step, the record is reviewed for duplicate records, by running the duplicate rule. If a duplicate is found the flow is stopped and no further actions performed.
  4. In this step, record is saved to the database but it not committed yet.
  5. Now all the after Triggers are executed.
  6. In this step, assignment rules are executed.
  7. Now if there is any auto-response rule is present then they are executed.
  8. Next in the queues are the workflow, they are executed after the auto response.
  9. If the workflow was updating a field, then the fields updated in this step and the flow after this step varies if this was the case.
  10. If a field was updated then the before and after update triggers are fired once more and standard validation are also executed again. Custom validation escalation rule and duplicate rules are not required to run again.
  11. Once the execution has reached this stage, then process is fired if there are any declared on the object.
  12. Now the escalation rules are executed.
  13. Entitlement rules are executed if any.
  14. If there are any roll-up summary field, then they are calculated at this step and the parent object go through the save process.
  15. Now the sharing rules are executed.
  16. If we reach this stage, then that means no error has occurred and the data is ready to be committed to the database and is committed now.
  17. Now if there is any post-commit logic like email, then that is executed.

 

For more details about trigger please refer below links

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

Trailhead get started with Triggers

Other posts related to interview questions

Salesforce lightning interview questions

I will keep adding more questions to Salesforce Interview Questions on Triggers.

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-interview-questions-on-triggers/