Triggers code to create a Contract for an Account. Whenever an Opportunity is successfully closed Won, auto-create a new Contract and activate it. Also, set the Contract Start Date = Close date of current Opportunity and Contract Term (months) = 12.
Hi Maheswara, Note : On Contract Object Status it should be first set to "DRAFT" then we can change to Activate. In your usecase it should be done in one transaction only means..
public void createContract(List<Opportunity> opplst, Map<id,Opportunity> oppOldMap) { for(Opportunity op : opplst) { if(op.StageName == 'Closed Won' && op.AccountId != Null && op.StageName != oppOldMap.get(op.Id).StageName) { Contract crt = new Contract(); crt.AccountId = op.AccountId; crt.Status = 'Draft'; // here first we are creating new contract with Status as "DRAFT" crt.StartDate = op.CloseDate; crt.ContractTerm = 12; lstcrt.add(crt); } } Insert lstcrt; for(Contract cn : lstcrt) { cn.Status = 'Activated'; // In single transaction only we are updating that particular Contract Status to "ACTIVATED" } update lstcrt;
Try Below Trigger Please Mark It As Best Answer If It Helps
Thank You!
Note : On Contract Object Status it should be first set to "DRAFT" then we can change to Activate. In your usecase it should be done in one transaction only means..
Please find the below code :
Trigger :
trigger OpportunityTrigger_SF on Opportunity (After Update)
{
OpportunityTrigger_SF_helper ophlpr = new OpportunityTrigger_SF_helper();
if(trigger.isafter && trigger.isUpdate)
{
ophlpr.createContract(trigger.new,trigger.oldMap);
}
}
Trigger Helper APEX class :
public class OpportunityTrigger_SF_helper {
List<Contract> lstcrt = new List<Contract>();
public void createContract(List<Opportunity> opplst, Map<id,Opportunity> oppOldMap)
{
for(Opportunity op : opplst)
{
if(op.StageName == 'Closed Won' && op.AccountId != Null && op.StageName != oppOldMap.get(op.Id).StageName)
{
Contract crt = new Contract();
crt.AccountId = op.AccountId;
crt.Status = 'Draft'; // here first we are creating new contract with Status as "DRAFT"
crt.StartDate = op.CloseDate;
crt.ContractTerm = 12;
lstcrt.add(crt);
}
}
Insert lstcrt;
for(Contract cn : lstcrt)
{
cn.Status = 'Activated'; // In single transaction only we are updating that particular Contract Status to "ACTIVATED"
}
update lstcrt;
}
}
Found helpful please mark it as best answer.
Thank You,
Prasanthi