Skip to main content

Salesforce Interview Trigger Questions

1. Write a trigger on Account, for update related contacts if Contact's Company Name field is blank, populate it with Account's Company Name field.

Limitations: Only 1 loop allowed.

Solution:

trigger on Account (After Update) {

    Map<Id, Account> accountMap = Trigger.newMap;

    List<Contact> contactList = [Select Id, Company_Name__c From Contact Where AccountId             in:accountMap.keys()];

    List<Contact> contactListForUpdate = List<Contact>();

    for(Contact contact : contactList) {

if(String.isBlank(contact.Company_Name__c)) {

    contact.Company_Name__c = accountMap.get(contact.AccountId).Company_Name__c;

    contactListForUpdate.add(contact);

}

}

update contactListForUpdate;

}

Comments

Popular posts from this blog

Static and Instance Methods, Variables, and Initialization Code

Static methods, variables, and initialization code have these characteristics They’re associated with a class. They’re allowed only in outer classes. They’re initialized only when a class is loaded. They aren’t transmitted as part of the view state for a Visualforce page. Using Static Methods and Variables public class Parent {     public static boolean isRun = true;  } A trigger that uses this class could then selectively fail the first run of the trigger trigger T1 on Account (before delete, after delete, after undelete) {         if(Trigger.isBefore){           if(Trigger.isDelete){              if( Parent .isRun){                  Trigger.old[0].addError('Before Account Delete Error');                    Parent .isRun =false;              }  ...

Order of Execution of a record in Salesforce Database

Loads the original record from the database or initializes the record for an upsert statement. 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. Executes record-triggered flows that are configured to run before the record is saved. Executes all before triggers. Runs most system validation steps again, such as verifying that all required...