1

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});

    }

}

3 Answers 3

4

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});
    }
}

}

1

compare the value in the trigger.new vs the trigger.old to see if the hiring manager field has been updated. If it has been updated then send the email..

0

Create a workflow with second criteria and use ISCHANGED() , PRIORVALUE() != newValue

Create an email alert and send it using workflow

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .