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
AshwAshw 

how to put this trigger in class and call it from trigger

As a new comer to salesforce i know how to write a trigger and class but how to conver the below code to class and call it in trigger, so please help me how to do this. Thanks guys in Advance 

Set<Id> accids = new Set<Id>();
	if(trigger.isInsert || trigger.isUpdate ||trigger.isUndelete){
		for(Contact con : trigger.new){
			accids.add(con.accountId);
		}
	}
	if(trigger.isUpdate || trigger.isdelete){
		for(Contact con : trigger.old){
			accids.add(con.accountId);
		}	
	}	
	
	List<account> lst = [Select id, No_Of_contacts__c,(Select id from Contacts) from account where Id in: accids];
	for(Account acc : lst){
		acc.no_of_contacts__c = acc.contacts.size();
	}
	update lst;


Ramu_SFDCRamu_SFDC
Do as below. Note : this is just an example to give you an idea, you would need to change the code further.

Trigger:

Trigger UpdateTest on Contact(Before Insert,Before Update, Before Delete, After Insert, After Update, After Delete, After Undelete){
if(trigger.isInsert || trigger.isUpdate ||trigger.isUndelete){
 utilityclass util=new utilityclass();
util.updatecontact(trigger.new); 
}
}

Class:

Public Class Utilityclass{
Public static Void updatecontact(List<Contact> contacts){
Set<Id> accids = new Set<Id>();
for(Contact con : contacts){
   accids.add(con.accountId);
  }

}
}
AshwAshw
Thanks Ramu 

Thanks for your response, so there is no need of quering account as i did in trigger 

Ramu_SFDCRamu_SFDC
Hi, the code you wrote is perfect. I just wanted to show how you can send the trigger.new collection to the contact list in class so that it is executed when there is a dml action on the record(s). Please implement your code in the same lines as mine and you should be able to achieve what you are looking for.