Saturday 1 December 2012

Create a Task using Apex

Apex provides the facility to create a Task activity and assign it to the respective users. We can create task via controller for a user or group of users. But Salesforce Task can't be share among the users so each user will have their own copy of Task created.

Below is the syntax to create a task in Salesforce

Controller syntax:
    public class example{
        public void createTask(){
            Task taskCreation = new Task(); // object initialized
                taskCreation.Priority = 'Normal'; // setting the priority of the task
                taskCreation.Status = 'Not Started'; // current status of the task
                taskCreation.Subject = 'New task created'; // subject for the task
                taskCreation.ActivityDate = System.today().addDays(10); // setting the due date
                taskCreation.Description = 'This task is created for testing.';
                // e is the instance of any record.
                // ownerId should be the id of a user for which task needs to be created.
                taskCreation.OwnerId = e.CreatedById;
                taskCreation.WhatId = e.id; // this will set the id for which task is created.          
                insert taskCreation;
        }
    }

Note:
1. If you want to assign a contact to a task, then you can use WhoId field to set the values.

No comments:

Post a Comment