Everything you need to know about creating Tasks in Salesforce Apex

Everything You need to Know About Creating Tasks in Salesforce Apex
Sharing is Caring

Salesforce tasks records are basically action items or items on a to-do list. Tasks are commonly logged against relevant records like a Lead, Opportunity, Contact or Account. Sometimes, depending, on your organizations data model it may also make sense to log tasks against custom objects.

Tasks can be incredibly useful for the business. Users can assign tasks to others, see how many times they’ve followed up with a particular lead, or allow managers to see what their staff are up to.

Tasks can be created through apex, visual flows, process builder, and of course through the api. When creating a new Task, you will need to include all required fields from the Task object. Currently, the required fields are Subject, OwnerId, Status, and WhatId. The Subject field is the name of the Task, the WhatId is the object the task is associated to, and finally OwnerId is the person that will do the Task.

Creating Salesforce Tasks in Apex isn’t overly difficult. The below example code shows how we could create a call task that needs to be done immediately.

Task tsk = new Task();
tsk.Subject = 'Follow up with Lead';
tsk.WhatId = [select Id from Opportunity Limit 1].Id;
//This is the default...
tsk.OwnerId = UserInfo.getUserId();
tsk.Status = 'New';
tsk.Type = 'Call';
insert tsk;

Tasks also split up into two interesting standard objects called Calls, and Events depending on the type that has been selected when the object is saved.

I commonly create Tasks from an apex trigger on an Opportunity when the Sales Stage reaches a certain point. This allows the Sales Staff or Onboarding Staff to know when it’s necessary to do additional steps. For example, at some Sales Stage we may want to create a quote and email it to the Opportunity’s Primary Contact.

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring