function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Biju NarayananBiju Narayanan 

Capture Account OwnerId updates in a Trigger

Hi 

I have a requirement to update some fields of an account based ont he Account Owner Ids. The process should be

1. Write Trigger in the Account Update
2. Check if the Owner is updated 
3. Check if a specific Id is common for both Old/New Owners (Select PGroupId, Id from user where id in (OldOwnerId,NewOwnerId)
4. If group id is same for both owners update specific fields in the account.

I have started coding in the Trigger. Since these changes are happening from the ETL process, I  am not sure how to bulkify my code. Should I get all the Account Ids before starting the Trigger & Compare in the below trigger ? Any suggestions
for (Account acc: Trigger.new) {
}

Thanks
Biju
Veenesh VikramVeenesh Vikram
Hi Biju,

Something like this is what you will need:
 
trigger xyx on account(before update){
	List<Account> processRecordsList = new List<Account>();	
	Set<Id> newOwners = new Set<Id>();
	Set<Id> oldOwners = new Set<Id>();
	for (Account acc: Trigger.new) {
		//Check if owner Updated
		if(acc.ownerId != trigger.oldmap.get(acc.Id).ownerId){
			newOwners.add(acc.ownerId);
			oldOwners.add(trigger.oldmap.get(acc.Id).ownerId);
			processRecordsList.add(acc);
		}
	}
	Map<Id,User> newOwnersMap = new Map<Id,Owner>();
	Map<Id,User> oldOwnersMap = new Map<Id,Owner>();
	
	//Query User fields
	if(newOwners.size() > 0 && oldOwners.size() > 0){
		newOwnersMap.putAll([Select PGroupId, Id from user where id in :newOwners]);
		oldOwnersMap.putAll([Select PGroupId, Id from user where id in :oldOwners]);
	}
	
	//Now Iterate, check and put records for update
	for (Account acc: processRecordsList) {
		if(newOwnersMap.get(acc.ownerId).PGroupId == oldOwnersMap.get(trigger.oldmap.get(acc.Id).ownerId).PGroupId){
			//DO UPDATE
		}
	}	
	
}

Hope this helps.

Veenesh