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
stefandlstefandl 

Trigger fires case depending on Opportunity Custom Field

Hello,

 

I'm writing a trigger that should fire a new case when the custom field Approval_Status__c changes to a specific value (Value changed to "Approved by AD" when opportunity is approved based on an approval process).

The problem is that my trigger is working but generates a case each time that the opportunity is updated.

 

The trigger I wrote is the following:

 

trigger NewCaseFromOpp on Opportunity (after update) { for (Opportunity opp : Trigger.new) { if (opp.approval_status__c == 'Approved by AD' ) { Case c = new Case ( Opportunity__c = opp.Id, Status = 'New', Origin = 'Web', Type = 'Request', Case_reason__c = 'Campaign Setup', Subject = 'New Direct Track Implementation', OwnerId= '00G20000001Pz10' ); insert c; } else {} } } 

 

Is there someone that can help me with this trigger?

 

Thanks,

 

Stefano

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

The problem is that you are generating a new case if the approval status matches the value, whereas you want to generate a new case when the approval  status changes to the value.

 

Something like the following should do the trick:

 

 

trigger NewCaseFromOpp on Opportunity (after update) 
{ 
 for (Opportunity opp : Trigger.new) 
 { 
    if ( (opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) )
    { 
       Case c = new Case ( Opportunity__c = opp.Id, Status = 'New', Origin = 'Web', Type = 'Request', Case_reason__c = 'Campaign  Setup', Subject = 'New Direct Track Implementation', OwnerId= '00G20000001Pz10' ); 
       insert c; 
    } 
    else 
    {
    } 
 } 
} 

 

 

All Answers

bob_buzzardbob_buzzard

The problem is that you are generating a new case if the approval status matches the value, whereas you want to generate a new case when the approval  status changes to the value.

 

Something like the following should do the trick:

 

 

trigger NewCaseFromOpp on Opportunity (after update) 
{ 
 for (Opportunity opp : Trigger.new) 
 { 
    if ( (opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) )
    { 
       Case c = new Case ( Opportunity__c = opp.Id, Status = 'New', Origin = 'Web', Type = 'Request', Case_reason__c = 'Campaign  Setup', Subject = 'New Direct Track Implementation', OwnerId= '00G20000001Pz10' ); 
       insert c; 
    } 
    else 
    {
    } 
 } 
} 

 

 

This was selected as the best answer
stefandlstefandl

Great!

It seems working properly.

 

Thanks a lot.

 

Stefano