Back

Apex triggers Q&A

1. What are the trigger events?

Before Mode: Before the record is saving into the database, it will fire. After Mode: After the record is saved into the database (doesn’t commit at this point of time), it will fire.

Before After
before insert after insert
before update after update
before delete after delete
after undelete

Note: before undelete event is not available.

2. What are the trigger context variables?

To capture the runtime information we use trigger context variables.

Below context variables will return either true or false.

  • Trigger.isBefore – returns true if the trigger context is Before Mode
  • Trigger.isAfter – returns true if the trigger context is After Mode
  • Trigger.isInsert – returns true if the trigger context is Insert
  • Trigger.isUpdate – returns true if the trigger context is Update
  • Trigger.isDelete – returns true if the trigger context is Delete
  • Trigger.isUndelete – returns true if the trigger context is Undelete
  • Trigger.isExecuting – returns true if the apex class method is getting call from Apex Trigger Below context variables will store records at runtime.
  • trigger.old – stores history (old versions) of the records
  • trigger.oldMap – stores history (old versions) of the records along with id
  • trigger.new – stores new version of the records
  • trigger.newMap – stores new version of the records along with id
3.Availability of trigger.old and trigger.new for the different trigger events?

Apex Trigger Collections availability for the different events –

Events   trigger.old    trigger.oldMap     trigger.New     trigger.NewMap  
before insert   No No Yes No
after insert   No No Yes Yes
before update   Yes Yes Yes Yes
after update   Yes Yes Yes Yes
before delete   Yes Yes No No
after delete   Yes Yes No No
after undelete   No No Yes Yes
4. Read/Write accessibility of trigger.old and trigger.new?

Read/Write access over the trigger collections on different events –

Events   trigger.old    trigger.oldMap     trigger.New     trigger.NewMap  

before insert NA NA Read/Write NA

after insert NA NA Read Only Read Only

before update Read Only Read Only Read/Write Read Only

after update Read Only Read Only Read Only Read Only

before delete Read Only Read Only Read Only Read Only

after delete Read Only Read Only Read Only Read Only

after undelete Read Only Read Only Read Only Read Only

5.When to use before triggers and when to use after triggers?

Before Triggers – To perform the validations we should use before triggers.

If you are updating any field on the same object on which you are writing the trigger and no need to explicitly include the DML statements (already due to DML operation only trigger fire and it is still in progress at this point of time.)

After Triggers – If you are dealing with relationship records and if you need record id in these situations we should use after trigger (in before insert record doesn’t contain the record id).

6.For the same event if there are multiple triggers on the object, how to control the order of execution?

We cannot control the order of execution in this situation. It is recommended to have only one trigger per one object.

Note: We can keep the logic of the apex trigger in an apex class and can invoke from that class.

7. What are the recursive triggers and how to avoid?

If we perform update operation on the record in after update event logic recursive triggers will arise. Using static Boolean variable in an apex class (we should not keep static Boolean variable inside of the trigger) we can avoid recursive triggers.

8. What is MIXED-DML-OPERATION error and how to avoid?
  • If we perform DML operation on standard/custom object and global objects (User, User Role, Group, Group Member, Permission Set, etc…) in same transaction this error will come.
  • To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.
  • In general all the apex classes and apex triggers execute synchronously (execute immediately).
  • If we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.
  • To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.

See the below example: Note: To analyse the code copy it and paste it in notepad for the convenience.

public class TriggerUtility {

  1. Following future method execute asynchronously (whenever server is free it will execute in future context).
  2. We should not declare @future method in Apex Trigger.
  3. @future method should be always static.
  4. @future method accepts only primitive data types (Integer, String, Boolean, Date, etc…) as parameters and it won’t accept non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.
  5. @future method should not contain return type. Always it should be void.
  6. From an apex trigger we can make only make asynchronous call outs. To make call out we should include “callout = true” beside the future @annotation.
  7. We cannot perform synchronous call outs from Apex Trigger.

//Below is the example for the future method –

@future(callout = true)
public static void processAsync(primitive parameters) {
//Logic to insert/update the standard/custom object.
}
9. Following Custom Objects are available in the organization
  • ChildObject__c
  • ParentObject__c

Relationship between ChildObjectc and ParentObjectc objects is Lookup relationship. In case of lookup relationship if we delete the parent object record in child object only the relationship field value will be removed (child records won’t be deleted).

But client has a requirement to delete the child object records. How to achieve this?

Write an apex trigger to achieve this functionality.

We should take before delete event. If we take after delete relationship will broke up b/w parent and child object records.,

Trigger ParentTrigger on ParentObject__c(before delete) {

Note: – For delete events only trigger.old and triggger.oldMap will be available. – trigger.old holds old versions of the records but if we mention that in SOQL query salesforce will automatically convert those records into ids.

List childLst = [select id, Parent_Object__c from ChildObject__c where Parent_Object__c in: trigger.old];
delete childLst;
}
10.What is the order of execution in salesforce?
  • We are creating validation rules, workflow rules, assignment rules, auto-responsive rules, escalation rules and apex triggers etc..
  • If the condition is same for all the rules which will execute first and which will execute next, for this salesforce provide the order.

Order of execution in sales force

Prepare the record for insert/update operation.

It will replace all the old field values with new field values.

If the request is coming form UI all the system validations will execute –

  • DataType
  • Length
  • Required
  • Unique
  • PageLayout level validations
  • Before triggers

Custom Validations and again system validation rules will fire (Page Layout level validations won’t fire at this point of time)

Record will be saved into the database but doesn’t not commit.

  • After triggers
  • Assignment rules
  • Auto-responsive rules
  • Workflow Rules

In case of Workflow Rule Field updates again before triggers and after triggers fire one more time

  • System validation rules for duplicate check
  • Escalation Rules
  • Rollup-Summary fields will be calculated
  • Grant parent Rollup-Summary fields will be calculated
  • Criteria base sharing evaluation
  • Record will be committed into the database
  • Post commits logic (Sending emails)
11. There is a validation rule which will fire if amount = 100 and will display the error message. There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000. What will the value of the amount field?

Validation rules will fire first then workflow rules will fire. So, the answer is 100 (Even though there is a validation rule because of the workflow rule it will accept 100 in the amount field).

12. There is a before trigger which will fire if amount = 100 and will display the error message.What will the value of the amount field?

There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000.It will throw the validation error because after the workflow field update before triggers fire one more time.



Back
Site developed by Nikhil Karkra © 2021 | Icons made by Freepik