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
mbforcembforce 

Need Help in trigger

Need help in writing Trigger
 
want to write trigger on Contact Object
 
created checkbox field on contact object with name Technical_employee
 
created number field on Account object with name Total_Technical_Employee
 
Total_Technical_Employee field should contain count of records from contact object whose Technical_employee checkbox is checked, how to write (insert, update, delete) trigger for this.

 

Thanks,

Manish

Satish_SFDCSatish_SFDC

You can also do it using Roll-up summary fields.

 

Or is there any special reason you would like to use triggers?

Regards,
Satish Kumar

mbforcembforce

Hi Satish,

 

I want to do it using Apex triggers (insert ,update,Delete).

I am new to salesforce and facing difficulty to code these triggers.if possible help me in writing and understanding these triggers.

 

Thanks,

Manish.

digamber.prasaddigamber.prasad

Hi,

 

I think below code snippet can help you in start writing your trigger. I have added comments as well to make sure you understand the code.

 

trigger ContactTrigger on Contact (after insert, after update, after delete) {
    Set<Id> setAccountId = new Set<Id>();
	for(Contact cont : trigger.new){
		if(trigger.isInsert){
			//checks if contact is Technical Employee on insert operation then only update count on account record
			if(cont.Technical_employee__c == true)
				setAccountId.add(cont.AccountId);
		}else if(trigger.isUpdate){
			//on update check if Technical Employee field of contact change, then only we need to update count on account record
			if(cont.Technical_employee__c != trigger.oldMap.get(cont.Id).cont.Technical_employee__c)
				setAccountId.add(cont.AccountId);
		}
	}
	
	//in delete we don't have trigger.new, so we need to cater delete operation in follwoing loop
	for(Contact cont : trigger.old){
		if(trigger.isDelete){
			//if contact was Technical Employee, then only update count on accout record
			if(cont.Technical_employee__c == true)
				setAccountId.add(cont.AccountId);
		}
	}
	
	if(setAccountId.size() > 0){
		//update count on account records
	}
    
}

 Please let me know if you need further help. Hope this will help you.

 

Happy to help you!

 

Regards,

Digamber Prasad