Trigger to create Task when Opportunity is updated

Trigger to create task when Opportunity is updated – Salesforce Apex Triggers

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.

  1.  Define the trigger
  2.  Iterate through each opportunity
  3.  Create a Task
  4.  Assign values to the Task

////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;
	}
}

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)

Trigger to create Task when Opportunity is updated
Trigger to create Task when Opportunity is updated

 

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.