+ Start a Discussion
Rahul Singh 1384Rahul Singh 1384 

Trigger on Opportunity to check old value change

I want to write a trigger on Opportunity, in which i have a field 'Individual Type'
I want to insert an event under this opportunity, if 'Individual Type' has some value.
and Send the mail to opportunity owner about event details.
i want to send mail only in case of 'Individual Type' field on opportunity is updated, i do not want to send mail incase of stage or another field updation for e.g:
--> 'Individual Type' is Null after insert or updation of opportunity, then do not send mail.
--> 'Individual Type' is not Null after insert or updation of opportunity, then  send the mail. 
--> 'Individual Type' value has changed from 'ABC' to 'XYZ' after updation of opportunity, then send the mail. 
--> 'Individual Type' value has not changed, after updation of opportunity, it was ABC, and it is still ABC, then do not send mail again. 

Please someone help with solution or any code assistance.
Any help would be greatly appreciated.
Best Answer chosen by Rahul Singh 1384
Maharajan CMaharajan C
Hi Rahul,

Sorry for the late reply:

There is some pain we will face for this scenario.

but i have the some workaround.

1. If we use the Email Templates then we must have to pass the Contact Id(in SetTargetObject) to merge the fields from Opportunity(in SetWhatId).

2. Otherwise we have to design the HTMl form inside the Trigger to Populate the Opportunity fields.

trigger Individualtypeevent on Opportunity (after Insert,after Update)
{
Map<id,Opportunity> Oppdetails = new Map<Id,Opportunity>();
if(trigger.IsAfter)
{
if(trigger.Isinsert)
{
    for(Opportunity opp:Trigger.new)
    {
    if(opp.Individual_Type__c != null || opp.Individual_Type__c != '')
    {
        if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
          String oppinsertId = Oppdetails.get(opp.id).Id;
          system.debug('==='+oppinsertId);
        }
    }
    }
}
if(trigger.isupdate)
{
    for(Opportunity opp:Trigger.new)
    {
        Opportunity oldopp = trigger.oldmap.get(opp.Id);
        if((opp.Individual_Type__c != null || opp.Individual_Type__c != '') && (opp.Individual_Type__c != oldopp.Individual_Type__c))
        {
            if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
            string OppUpdaId = Oppdetails.get(opp.id).Id;
            system.debug(' --> '+OppUpdaId);
        }
        }
    }
}
}
Map<Id,String> opEmail = new Map<Id,String>();
List<Opportunity> i = [select ownerid, id, Owner.manager.email, Owner.Email from opportunity where id =: Oppdetails.keySet()];
for(Opportunity o:i)
{
if(!opEmail.containskey(o.Id))
{
opEmail.put(o.Id,o.Owner.Email);
}
}
system.debug ('I==='+opEmail);
List<event> eventtoInsert = new List<event>();
system.debug('Opporetunity Details = '+Oppdetails);
if(Oppdetails.size() > 0)
{
    for(opportunity oppevent:Oppdetails.values())
    {
        Event eve = new Event();
        eve.WhatID = Oppevent.Id; 
        eve.Subject='The Individual Type for your opportunity is added or updated';
        eve.StartDateTime=system.now();
        eve.DurationInMinutes=60;
        String Email1=Oppevent.Owner.Email;
        system.debug('Email1='+Email1);
        eventtoInsert.add(eve);
        
    }
}
if(eventtoInsert.size()>0)
    {
    insert eventtoInsert;
    
List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
for(Event u : eventtoInsert){
                 Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                 String Owneremail = opEmail.get(u.WhatId);
                 system.debug('Email Id = '+Owneremail);
                 message.toAddresses = new String[]{OwnerEmail};
                 String ContactId= Oppdetails.get(u.whatId).Primary_Contact__c;       /// Here i used the Primary_Contact__c ( Lookup of                 Contact in Opportunity )      or   hard code any Contact Id here this is trick  because it is mandatory.
                 message.setTargetObjectId(ContactId); 

                 message.setTreatTargetObjectAsRecipient(false);
                 String oppId= Oppdetails.get(u.whatId).Id;     
                 message.setwhatId(oppId);                                                     ///  This will merge the Opportunity fields

                 message.setTemplateId('00X0K000001TJs4');                           /// Use your Email Template Id
                 message.setSaveAsActivity(false);
                 //message.subject = 'Reminder Notification regarding Individual type is Updated or Created for your Opportunity'; 
                 String Name = Oppdetails.get(u.whatId).Name; 
                 //message.plainTextBody = 'Please check your salesforce Opportunity ; Opportunity Name' +'  ' +Name+' ';
                   allMails.add(message);
                             }
             
             Messaging.sendEmail(allMails);
        
    
    }
}





OR


2. 
Otherwise we have to design the HTMl form inside the Trigger to Populate the Opportunity fields.

The below i dont tested but i tested the above it works fine.So if you face any issue in the below thing try to slve or let me know.

         message.subject = 'Reminder Notification regarding Individual type is Updated or Created for your Opportunity'; 
         String Name = Oppdetails.get(u.whatId).Name; 
         String Amount= Oppdetails.get(u.whatId).Amount; 
         String CloseDate= Oppdetails.get(u.whatId).Closedate; 
         String body = '<html lang="ja"><body>'+ 
                          '<br><br>'+'This email alert is to bring to your notice that this Opportunity is updated Opportunity name:' :'+'  '+'<b>'+Name+'</b>'+'  '+'is going to Closed within'+'<b>'+' '+CloseDate+' '+'</b>'+
                          '<br><br>'+'Opportunity Amount:'+' '+'<b>'+Amount+'</b>'+' </body></html>';
         mail.setHtmlBody(body);

Can you please Let me know if it works or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
​Raj

 

All Answers

Ashish DevAshish Dev
Hi Rahul,
I would recommend to use process builder to achieve above requirement. It can easily be done.
Maharajan CMaharajan C
Hi Rahul,

1. Please find the below code for your scenarion using trrigger:

trigger Individualtypeevent on Opportunity (after Insert,after Update)
{
Map<id,Opportunity> Oppdetails = new Map<Id,Opportunity>();
if(trigger.IsAfter)
{
if(trigger.Isinsert)
{
    for(Opportunity opp:Trigger.new)
    {
    if(opp.Individual_Type__c != null || opp.Individual_Type__c != '')
    {
        if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
          String oppinsertId = Oppdetails.get(opp.id).Id;
          system.debug('==='+oppinsertId);
        }
    }
    }
}
if(trigger.isupdate)
{
    for(Opportunity opp:Trigger.new)
    {
        Opportunity oldopp = trigger.oldmap.get(opp.Id);
        if((opp.Individual_Type__c != null || opp.Individual_Type__c != '') && (opp.Individual_Type__c != oldopp.Individual_Type__c))
        {
            if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
            string OppUpdaId = Oppdetails.get(opp.id).Id;
            system.debug(' --> '+OppUpdaId);
        }
        }
    }
}
}
Map<Id,String> opEmail = new Map<Id,String>();
List<Opportunity> i = [select ownerid, id, Owner.manager.email, Owner.Email from opportunity where id =: Oppdetails.keySet()];
for(Opportunity o:i)
{
if(!opEmail.containskey(o.Id))
{
opEmail.put(o.Id,o.Owner.Email);
}
}
system.debug ('I==='+opEmail);
List<event> eventtoInsert = new List<event>();
system.debug('Opporetunity Details = '+Oppdetails);
if(Oppdetails.size() > 0)
{
    for(opportunity oppevent:Oppdetails.values())
    {
        Event eve = new Event();
        eve.WhatID = Oppevent.Id; 
        eve.Subject='The Individual Type for your opportunity is added or updated';
        eve.StartDateTime=system.now();
        eve.DurationInMinutes=60;
        String Email1=Oppevent.Owner.Email;
        system.debug('Email1='+Email1);
        eventtoInsert.add(eve);
        
    }
}
if(eventtoInsert.size()>0)
    {
    insert eventtoInsert;
    
List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
for(Event u : eventtoInsert){
                 Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                 String Owneremail = opEmail.get(u.WhatId);
                 system.debug('Email Id = '+Owneremail);
                 message.toAddresses = new String[]{OwnerEmail};
                 //message.setOrgWideEmailAddressId('0D20K000000XZnL');
                 //message.setTemplateId('00X0K000001i02Y');
                 message.setSaveAsActivity(false);
                 message.subject = 'Reminder Notification regarding Individual type is Updated or Created for your Opportunity'; 
                 String Name = Oppdetails.get(u.whatId).Name; 
                 message.plainTextBody = 'Please check your salesforce Opportunity ; Opportunity Name' +'  ' +Name+' ';
                   allMails.add(message);
                             }
             
             Messaging.sendEmail(allMails);
    }
}

2. You can also use the Process builder.

3.And also use the trigger only for create the event and send the Email alert using the WF rule in the Event when the record is created. 

Can you please Let me know if it works or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
​Raj
 
 
Rahul Singh 1384Rahul Singh 1384
Thanks a lot for the help Maharajan,
One last help can we send Email Template in mail with the help of Trigger? I have to send 3 to 4 fields of that opportunity which is recently updated, i have mentioned those fields in my Email Template, but i want help in sending it to opportunity owner through trigger.
Any help?
Maharajan CMaharajan C
Hi Rahul,

Sorry for the late reply:

There is some pain we will face for this scenario.

but i have the some workaround.

1. If we use the Email Templates then we must have to pass the Contact Id(in SetTargetObject) to merge the fields from Opportunity(in SetWhatId).

2. Otherwise we have to design the HTMl form inside the Trigger to Populate the Opportunity fields.

trigger Individualtypeevent on Opportunity (after Insert,after Update)
{
Map<id,Opportunity> Oppdetails = new Map<Id,Opportunity>();
if(trigger.IsAfter)
{
if(trigger.Isinsert)
{
    for(Opportunity opp:Trigger.new)
    {
    if(opp.Individual_Type__c != null || opp.Individual_Type__c != '')
    {
        if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
          String oppinsertId = Oppdetails.get(opp.id).Id;
          system.debug('==='+oppinsertId);
        }
    }
    }
}
if(trigger.isupdate)
{
    for(Opportunity opp:Trigger.new)
    {
        Opportunity oldopp = trigger.oldmap.get(opp.Id);
        if((opp.Individual_Type__c != null || opp.Individual_Type__c != '') && (opp.Individual_Type__c != oldopp.Individual_Type__c))
        {
            if(!Oppdetails.containskey(opp.Id))
        {
            Oppdetails.put(opp.id,opp);
        }
        else if(Oppdetails.containskey(opp.Id))
        {
            string OppUpdaId = Oppdetails.get(opp.id).Id;
            system.debug(' --> '+OppUpdaId);
        }
        }
    }
}
}
Map<Id,String> opEmail = new Map<Id,String>();
List<Opportunity> i = [select ownerid, id, Owner.manager.email, Owner.Email from opportunity where id =: Oppdetails.keySet()];
for(Opportunity o:i)
{
if(!opEmail.containskey(o.Id))
{
opEmail.put(o.Id,o.Owner.Email);
}
}
system.debug ('I==='+opEmail);
List<event> eventtoInsert = new List<event>();
system.debug('Opporetunity Details = '+Oppdetails);
if(Oppdetails.size() > 0)
{
    for(opportunity oppevent:Oppdetails.values())
    {
        Event eve = new Event();
        eve.WhatID = Oppevent.Id; 
        eve.Subject='The Individual Type for your opportunity is added or updated';
        eve.StartDateTime=system.now();
        eve.DurationInMinutes=60;
        String Email1=Oppevent.Owner.Email;
        system.debug('Email1='+Email1);
        eventtoInsert.add(eve);
        
    }
}
if(eventtoInsert.size()>0)
    {
    insert eventtoInsert;
    
List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
for(Event u : eventtoInsert){
                 Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                 String Owneremail = opEmail.get(u.WhatId);
                 system.debug('Email Id = '+Owneremail);
                 message.toAddresses = new String[]{OwnerEmail};
                 String ContactId= Oppdetails.get(u.whatId).Primary_Contact__c;       /// Here i used the Primary_Contact__c ( Lookup of                 Contact in Opportunity )      or   hard code any Contact Id here this is trick  because it is mandatory.
                 message.setTargetObjectId(ContactId); 

                 message.setTreatTargetObjectAsRecipient(false);
                 String oppId= Oppdetails.get(u.whatId).Id;     
                 message.setwhatId(oppId);                                                     ///  This will merge the Opportunity fields

                 message.setTemplateId('00X0K000001TJs4');                           /// Use your Email Template Id
                 message.setSaveAsActivity(false);
                 //message.subject = 'Reminder Notification regarding Individual type is Updated or Created for your Opportunity'; 
                 String Name = Oppdetails.get(u.whatId).Name; 
                 //message.plainTextBody = 'Please check your salesforce Opportunity ; Opportunity Name' +'  ' +Name+' ';
                   allMails.add(message);
                             }
             
             Messaging.sendEmail(allMails);
        
    
    }
}





OR


2. 
Otherwise we have to design the HTMl form inside the Trigger to Populate the Opportunity fields.

The below i dont tested but i tested the above it works fine.So if you face any issue in the below thing try to slve or let me know.

         message.subject = 'Reminder Notification regarding Individual type is Updated or Created for your Opportunity'; 
         String Name = Oppdetails.get(u.whatId).Name; 
         String Amount= Oppdetails.get(u.whatId).Amount; 
         String CloseDate= Oppdetails.get(u.whatId).Closedate; 
         String body = '<html lang="ja"><body>'+ 
                          '<br><br>'+'This email alert is to bring to your notice that this Opportunity is updated Opportunity name:' :'+'  '+'<b>'+Name+'</b>'+'  '+'is going to Closed within'+'<b>'+' '+CloseDate+' '+'</b>'+
                          '<br><br>'+'Opportunity Amount:'+' '+'<b>'+Amount+'</b>'+' </body></html>';
         mail.setHtmlBody(body);

Can you please Let me know if it works or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
​Raj

 
This was selected as the best answer
Maharajan CMaharajan C
 Change the   mail.setHtmlBody(body);    to       message.setHtmlBody(body);

 
Rahul Singh 1384Rahul Singh 1384

Awesome! That is really helpful, 

Thanks a lot Maharajan