Development questions

Whenever an Opportunity StageName is changed to Closed Won, automatically create a Contract or Follow-Up Task for the Opportunity Owner.

DevelopmentEasyAccentureWiproInfosys

Use after update (and compare old vs new StageName so it fires only on the transition). Create a Task for the Opportunity Owner.

apex
trigger OppTrigger on Opportunity (after update) {
    List<Task> tasks = new List<Task>();
    for (Opportunity o : Trigger.new) {
        if (o.StageName == 'Closed Won' && Trigger.oldMap.get(o.Id).StageName != 'Closed Won') {
            tasks.add(new Task(Subject = 'Follow-up on ' + o.Name, WhatId = o.Id,
                OwnerId = o.OwnerId, ActivityDate = Date.today().addDays(7)));
        }
    }
    if (!tasks.isEmpty()) insert tasks;
}

For a Contract, insert Contract records with AccountId and Status = 'Draft' instead.

apex-triggertriggercodingscenario