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
CKRCKR 

How to write a trigger while a cusotm field (Picklist) staus__C on account is changing from Open to Processing,its related contacts have to be fetched and the checkbox "Yes" on related contacts have to be checked i.e "True"

Hi All,
How to write a trigger while a cusotm field (Picklist)  status__C on account is changing from Open to Processing,its related contacts have to be fetched and the checkbox field "Yes" on related contacts have to be ''checked'' i.e as "True". i tried using trigger.new/Old , which did not worked at all and my code looks terrible, so i am not posting here. actually my reason behind this question is to know the perfect use case that makes me sense of the importance of trigger.Newmap, trigger.oldmap and trigger,Isexecuting.
Help will be appreciated.
Thanks
CKR
santanu boralsantanu boral
Hi,

You can follow this code below.

Trigger
 
trigger AccountTrigger on Account (after update) 
{
   AccountTriggerHelper.executeAction(Trigger.oldMap,Trigger.newMap);
}

Apex class
public class AccountTriggerHelper
{
	
	public static void executeAction(Map<Id,Account> oldMap, Map<Id,Account> newMap)
	{
		Set<Id> accSetIds = new Set<Id>(); //holds the updated Account Ids
		for(Account acc:newMap.values())
		{
			 Account oldAccount = oldMap.get(acc.Id);
			if(acc.status__c.equals('Processing')  && oldAccount.status__c.equals('Open'))
			{
				accSetIds.add(acc.Id);
			}			
		}
		
		//retrieve the list of contacts based on updated accounts
		List<Contact> lstContact = [SELECT Id, Yes__c FROM Contact WHERE AccountId in:accSetIds];
		if(lstContact.size()>0)
		{
			for(Contact contactObj:lstContact)
			{
				contactObj.Yes__c = true;
			}
			update lstContact;
		}
	}
}

If this surves your purpose, please mark this answer.