WAT if the owner of an account is changed then the owner of the related contacts should also be updated.

 Account Trigger

============================================

trigger AccountTrigger on Account (after update) {

  Set<ID> accountId = new Set<ID>();

  if(Trigger.IsAfter && Trigger.IsUpdate){

    for(Account objAcc : trigger.new){

      if(trigger.oldMap.containsKey(objAcc.id)){

        if(trigger.oldMap.get(objAcc.id).OwnerId != objAcc.OwnerId){

          accountId.add(objAcc.Id);

        }

      }

    }

    if(accountId != null && accountId.size() > 0 ){

      AccountTriggerHandler.UpdateOwnerofContact(Trigger.newMap, accountId);

    }

  }

}


============================================

AccountTriggerHandler Class


public with sharing class AccountTriggerHandler {

  public static void UpdateOwnerofContact(Map<Id,Account>accountMap,Set<id>accountId){

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

    Map<id,Contact> mapofIdToContact = new Map<id,Contact>([SELECT Id,Name,AccountId From contact WHERE AccountId =:accountId]);

    if(mapofIdToContact != null && mapofIdToContact.size()>0){

      for(Contact objCon : mapofIdToContact.values()){

        if(accountMap.containsKey(objCon.AccountId)){

          objCon.OwnerId = accountMap.get(objCon.AccountId).OwnerId;

          lstUpdateOwnerofContact.add(objCon);

        }

      }  

    }

// Check null and size 

    if(lstUpdateOwnerofContact != null && lstUpdateOwnerofContact.size()>0){

      Database.SaveResult [] sr = Database.update(lstUpdateOwnerofContact,false);

    }

  }

}

Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page