+ Start a Discussion
NerdyNerdy 

How can I update a field of a related object when a fields is updated using a trigger ?

Hello, I am new to triggers ...can anybody help me with this 

I have a lookup relationship between two custom objects A and B(the child)
when two checkbox fields in object A are unchecked, i want two other checkbox in obj B to be unchecked...

I know this can be done via process builder but would like to try this with  a trigger so I can start to understand more about Apex
Best Answer chosen by Nerdy
Vivian Charlie 1208Vivian Charlie 1208

Hi Rachidy,

 

Please use this as a reference. The trigger is on Account and if both checkboxes are false it updates the related Contacts

 

trigger Accounttrigger on Account (after update){
	set<Id> setIds = new set<Id>);
	for(Account objP : trigger.new){
		if(objP.chkbox1__c = false
		&& objP.chkbox2__c = false){
			setIds.add(objP.Id);
		}
	}
	
	if(!setIds.isEmpty()){}
		list<Contact> lstCon = [Select Id, AccountId, cbox1__c, cbox2__c from Contact where AccountId IN : setIds];
		for(Contact objC : lstCon){
			objC.cbox1__c = false;
			objC.cbox2__c = false;
		}
		if(!lstCon.isEmpty()){
			update lstCon;
		}
	}
}


Thanks

Vivian