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
Rory McDonnellRory McDonnell 

Trigger on Lead record that updates lead fields and also creates a task

Hi I am learning how to build triggers and am trying to do the following.

When a new lead is created with a specific company name, update two fields on the lead record and also create a new task. 

My understanding is that since it is a new record I would need to use an AFTER INSERT trigger as the task will need the newly created lead ID as a reference in the WhatID. But seeing as I also need to update fields on the lead record it doesn't seem that the After Insert will allow that.

Am I stuck with choosing between a Before Insert so I can update my lead record, and an After Insert if I want to create a task.

I'm pretty sure there is a simple solution but still very new to Apex.
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
hi Rory,
Please refer below code:
trigger LeadTrigger on Lead (after insert,before insert) {
	
	if(Trigger.isInsert){
		List<Task> tasks = new List<Task>();
		for(Lead leadObj : Trigger.New){
			if(trigger.isBefore){
				//set the field values you want
			}
			if(trigger.isAfter){
				//create Task as below
				Task taskObj = new Task(WhoId = leadObj.Id, ..set other task fields..);
				tasks.add(taskObj);
			}
		}
	}
	if(!tasks.isEmpty())	insert tasks;
}

 

All Answers

Danish HodaDanish Hoda
Hi Rory,
Your understading is absolutely correct, for this you need both Before (to upate Lead fields) and After (to create task) triggers.
Please note that you need to set WhoId when linking task on Lead. :)
Rory McDonnellRory McDonnell
Thanks Danish, so does this mean I would create two seperate triggers to solve the requirement?
Danish HodaDanish Hoda
hi Rory,
Please refer below code:
trigger LeadTrigger on Lead (after insert,before insert) {
	
	if(Trigger.isInsert){
		List<Task> tasks = new List<Task>();
		for(Lead leadObj : Trigger.New){
			if(trigger.isBefore){
				//set the field values you want
			}
			if(trigger.isAfter){
				//create Task as below
				Task taskObj = new Task(WhoId = leadObj.Id, ..set other task fields..);
				tasks.add(taskObj);
			}
		}
	}
	if(!tasks.isEmpty())	insert tasks;
}

 
This was selected as the best answer
Rory McDonnellRory McDonnell
Thanks Danish, that's great!