Trigger to create a task when an Opportunity is updated – Salesforce Apex Triggers for Beginners.
Requirement: Write a Salesforce Apex Trigger to create a Task when an Opportunity is updated. The task should be assigned to the Opportunity owner and the status of the task should be “In Progress”.
The Salesforce Apex Trigger Sytax is as follows:
trigger *triggerName* on *Object* (*before/after event*) { for (*Object* *Variable* : Trigger.New) **Trigger Actions & Code Block** }
Now lets write our trigger with the following steps.
- Define the trigger
- Iterate through each opportunity
- Create a Task
- Assign values to the Task
The complete Salesforce Apex Trigger to create a Task when an Opportunity is updated would be:
////define the trigger name, object and events trigger createTaskOnOpp on Opportunity (before update) { //Iterate through each opportunity and assign it the variable Opp for (Opportunity Opp :Trigger.New) { //Create a new task and assign it the variable t Task t = new Task(); // Assign Values to the task t t.WhatID = Opp.Id; t.Ownerid = opp.Ownerid; t.subject = 'This is the Subject'; t.Status = 'In Progress'; t.Description = 'This is the Description'; insert t; } }
This is how the trigger looks in the developer console (image)
Leave a Reply