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
Priyakaran1320Priyakaran1320 

apex trigger logic

Hey guys if can help me   i have a situation in which i need a apex logic to fit in a apex class which is already written

the situation is i need to write a trigger in which i have two custom fields which are in two different tabs so wen ever a custmer updated that particular field it has been updated automatically from the team site so now my job is to create a trigger tht wen ever it is update it should fire a trigger that shoots a email to that particular account user.

i need that logic it u guys can help me writing it 

 thanks

lovetolearnlovetolearn

Just to confirm, you need a trigger that send the email to the account user everytime a custom is updated?

Priyakaran1320Priyakaran1320

yes trigger fires a email whenever it is updated

lovetolearnlovetolearn

Hi, 

 

Please try the following:

 

/******************
I make the following assumption about your Salesforce instance:
1. The objects that you are working with are custom objects.
2. The fields that you are working with are custom fields as well. 
3. The account user field is a lookup field to the native SF user class. 
This means that the user account contain valid email addresses
******************/

trigger on Object__c (after update){

	List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();   

	for(Object__c o:trigger.new){

		object__c oldValues = trigger.oldMap.get(o.Id);
		if(o.yourfield__c != oldvalues.yourfield__c){
			Messaging.SingleEmailMessage alertEmail = new Messaging.SingleEmailMessage();
			String[] toAddress = new String[]{o.account_user__c.Email};
			alertEmail.setToAddresses(toAddress);
			alertEmail.setSubject('Please note that the field has been updated'); //Feel free to change the subject of the email
			alertEmail.setHTMLbody('Please note that the field has been updated');
			alertEmail.setPlainTextBody('Please note that the field has been updated'); 
			//I don't know what type of email service you use, but ideally you want to set a HTML and a plain text version
			emailList.add(alertEmail);//Adding to a list will ensure that you won't hit the 10 email governor limit. 
		}
	}System.debug(emailList.size());
	try{
		Messaging.sendEmail(emailList);
	}catch(Exception e){
		System.debug('This is your error:' + ' ' + e);
	}
}