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
jillianjillian 

Trigger that Creates Opportunity when a Case is Closed

I am trying to write a trigger that creates an Opportunity when a case is closed, the opportunity would be attached to the Account that was associated to the case. Here is what I have, anyone have any help here?


trigger Opportunitycreate on case (after insert) {
    List<opportunity>Listopp = New List<opportunity>();
    for(case acc:trigger.new){
       if(acc.Create_opp__c=True){
        Opportunity opp = New opportunity();
        opp.name=acc.name;
        opp.CloseDate=date.Today();
        opp.StageName='Prospecting';
        Listopp.add(opp);
       }
       }
    if(Listopp.size()>0)
    insert Listopp;
}
 
Best Answer chosen by jillian
MithunPMithunP
Hi Jillian,

Here is the working sample code.
 
trigger oppCase on Case (after insert, after update) {
    list<opportunity> opplist = new list<opportunity>();
    for(case cs : trigger.new){
          if(cs.status == 'Closed'){
               opportunity opp = new opportunity();
               opp.accountid = cs.accountid;
               opp.name = 'New Opportunity -' + cs.casenumber;
               opp.stageName = 'Prospecting';
               opp.closedate = system.today();
               opplist.add(opp);
          }
    }
    if(opplist.size() > 0){
       insert opplist;
    }

}



Best Regards,
Mithun.

All Answers

MithunPMithunP
Hi jillian,

Create_opp__c field is created in Case object or Account object?

Best Regards,
Mithun.
Bhanu MaheshBhanu Mahesh
Hi Jillian,

try adding pp.AccountId = acc.AccountId; while creating opportunity

trigger Opportunitycreate on case (after insert) {
    List<opportunity>Listopp = New List<opportunity>();
    for(case acc:trigger.new){
       if(acc.Create_opp__c=True){
        Opportunity opp = New opportunity();
        opp.AccountId = acc.AccountId;
    opp.name=acc.name;
        opp.CloseDate=date.Today();
        opp.StageName='Prospecting';
        Listopp.add(opp);
       }
       }
    if(Listopp.size()>0)
    insert Listopp;
}

Regards,
Bhanu Mahesh
MithunPMithunP
Hi Jillian,

Here is the working sample code.
 
trigger oppCase on Case (after insert, after update) {
    list<opportunity> opplist = new list<opportunity>();
    for(case cs : trigger.new){
          if(cs.status == 'Closed'){
               opportunity opp = new opportunity();
               opp.accountid = cs.accountid;
               opp.name = 'New Opportunity -' + cs.casenumber;
               opp.stageName = 'Prospecting';
               opp.closedate = system.today();
               opplist.add(opp);
          }
    }
    if(opplist.size() > 0){
       insert opplist;
    }

}



Best Regards,
Mithun.
This was selected as the best answer