Tasks in Salesforce.com are a powerful tool that can help users and managers in the environment complete assignments associated to business processes. You can create tasks manually, through workflows, or custom Apex code. In this blog, we are going to show you how to create a task via Apex Code.
When creating a new Task, you will need to include all required fields from the Task object. By default the Subject, OwnerId, Status, and WhatId fields are required, and will need to be included in the Task creation, along with any other fields your organization have marked as required. The Subject field states the name of the Task, the OwnerId is the person that the Task is assigned to, and the WhatId is the object on which the Task is associated.
For our example, we are assigning the Task on the Opportunity (o) object, and to the current user (userId). The following will create a task for an Opportunity, assign it to the current user, then insert the task onto the Task object.
String userId = UserInfo.getUserId();
Task t = new Task();
t.OwnerId = userId;
t.Subject = ‘Hello World’;
t.Status = ‘Open’;
t.Priority = ‘Normal’;
t.WhatId = o.Id;