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
Preeti ShettyPreeti Shetty 

Email template to include any field change value


Is there anyway to include anyfield cahnge in an email template. In Cases when a user updates any field (not a specific field) an email alert should be sent wherein the email template should specify which field has changed. There are many fields in cases, so the email template should specify only the one which has been changed or edited.

Please let me know how can we do this.
Jason BealJason Beal
You need an event which will cause the email to be sent such as the update event of a trigger. Merge fields in an email template are based on a target object passed into the template. You can pass the object being updated to the email template but you would not have the ability to compare the values of the object before and after the update. Instead of using an email template you could construct the email body manually. Have a look at the Contact trigger below. This trigger will send an email every time a Contact is updated and list the differences between the Contact before and after the update is performed. 

Alternatively you can report on field history by enabling History Tracking on each object you are auditing but you are limited to tracking 20 fields per object. 
trigger MonitorContactTrigger on Contact (after update) {
	Schema.DescribeSObjectResult objSchema = Contact.sObjectType.getDescribe();
	Set<String> fields = objSchema.fields.getMap().keySet();
    String[] changedFields  = new String[]{};
    for(Contact c:{
        for(string s: fields){
            if(c.get(s) != trigger.oldMap.get(c.Id).get(s)){
                changedFields.add('Contact: ' + c.Id + ' - ' + s + ' - old:' + trigger.oldMap.get(c.Id).get(s) + ' new:' + c.get(s));
    	messaging.singleEmailMessage mail = new messaging.singleEmailMessage();
        mail.setToAddresses(new string[]{UserInfo.getUserEmail()});
        mail.setSubject('Cantact updated');
        string htmlBody = '';
        for (String s : changedFields){
            htmlBody += '<div>' + s + '</div>';
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});