[SalesForce] Send Email only if the field value changes

I have a below trigger created where I use a field called Hiring Manger to identify the user's email id and send an email to the person that a project is assigned to them. But my trigger runs every time a do some edit to the record with out changing the hiring manger field. I would like to send an email only if the previous value does not match the current value in hiring manager field. How can i implement this condition here:

trigger SendEmailToHiringManger on SFDC_Job_Opening__c (after insert, after update) {

    list<SFDC_Job_Opening__c> i = [select id,SO__c,SFDC_Job_Opening__c.Hiring_Manager__r.email,Account_Name__c from SFDC_Job_Opening__c where id IN:trigger.newMap.keySet()];

    for( SFDC_Job_Opening__c s : i)
    {

        system.debug('Name is'+ s.Hiring_Manager__c);
        String userEmail = s.Hiring_Manager__r.email; 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
        String[] toAddresses = new String[] {userEmail}; 
        mail.setToAddresses(toAddresses); 
        mail.setSubject('You have a project assigned' + ' So#- '+ s.SO__c); 
        String body = 'Project Assigned' + '-' + s.SO__c + ' ' + s.Account_Name__c ; 
        mail.setPlainTextBody(body); 
        Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail});

    }

}

Best Answer

You can access the 'old' and the 'new values in an after trigger. You already access the new values in trigger.newMap. The old values are in trigger.oldMap :-)

So compare the old and new value of the field in your code.

trigger SendEmailToHiringManger on SFDC_Job_Opening__c (after insert, after update) {

list<SFDC_Job_Opening__c> i = [select id,SO__c,Hiring_Manager__r.email,Account_Name__c from SFDC_Job_Opening__c where id IN:trigger.newMap.keySet()];

for( SFDC_Job_Opening__c s : i)
{
    if(s.Hiring_Manager__c != trigger.oldMap.get(s.Id).Hiring_Manager__c)
    {
        system.debug('Name is'+ s.Hiring_Manager__c);
        String userEmail = s.Hiring_Manager__r.email; 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
        String[] toAddresses = new String[] {userEmail}; 
        mail.setToAddresses(toAddresses); 
        mail.setSubject('You have a project assigned' + ' So#- '+ s.SO__c); 
        String body = 'Project Assigned' + '-' + s.SO__c + ' ' + s.Account_Name__c ; 
        mail.setPlainTextBody(body); 
        Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail});
    }
}

}

Related Topic