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

**Topic:** Development · **Difficulty:** Easy · **Asked at:** Accenture, Wipro, Infosys · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/whenever-an-opportunity-stagename-is-changed-to-closed-won-automatically-create-a-contract-or-follow-up-task

## Answer

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.

---
Source: ForceChallenges · last updated 2026-10-19
