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
Maheswara Reddy 25Maheswara Reddy 25 

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.

CharuDuttCharuDutt
Hii Maheswara
Try Below Trigger
trigger opptyTrigger on Opportunity (after update) {
    for(opportunity opp : trigger.new){
       if(opp.StageName == 'Closed Won' && Opp.StageName != trigger.oldMap.get(Opp.Id).StageName && Opp.AccountId != Null){
           contract cont = new contract();
           cont.AccountId = opp.AccountId;
           cont.StartDate = opp.CloseDate;
           cont.ContractTerm = 12;
           cont.Status = 'Activated';
           insert Cont;
       }
    }
}
Please Mark It As Best Answer If It Helps
Thank You! 
Prasanthi_s1505Prasanthi_s1505
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..

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