Skip to content. | Skip to navigation

Personal tools
Log in
Sections
You are here: Home Database Salesforce Apex & Visualforce Apex Snippet: Task Copier

Apex Snippet: Task Copier

A class and method to handle copying tasks from one contact record to another. Takes a contact ID as a string (or ID, they're implicitly converted in SF), uses a contact named "Random Task" as a template for the tasks (this can be changed by reassigning the value for the global 'RandomTaskName') and returns the number of tasks copied from the template record to the calling record. It will not copy tasks from one to the other if the subject is already in the list of the calling contact's tasks.
//Written by Kevin Bromer, copyright (c) 2008 NPower Seattle


public class TaskCopy {
    
    
    /***********Instance Variables***********/
    integer taskscopied = 0;
    id ThisContact;
    id RandomTaskID;
    
    //This string defines the name of the contact FROM which tasks are to be copied
    string RandomTaskName = 'Random Task';
    
    
    
    //Constructor for TaskCopy
    public TaskCopy(id ContactID)
        {
            ThisContact = ContactID;
        }
    
    
    
    public integer copyIt()
    {
        //Get the ID for student 'Random Task'
        
        Set<String> st = new Set<String>();
        RandomTaskID = [select id from Contact WHERE name = :RandomTaskName].id;
        for (Task s : [select subject from Task WHERE WhoID = :ThisContact])
            {
                st.Add(s.Subject);
            }        


               
        
        for (Task t : [SELECT ID, WhoID, Subject, Description, OwnerID, Status, Priority, ActivityDate, 
                        WhatID FROM Task WHERE WhoID = :RandomTaskID])
            {
            Task nt = New Task();
                
            if (st.Contains(t.subject) != true)
            {        
            nt.WhoID = ThisContact;
            nt.Subject = t.Subject;
            nt.Description = t.Description;
            nt.OwnerID = UserInfo.getUserId();
            nt.Status = t.Status;
            nt.Priority = t.Priority;
            nt.ActivityDate = t.ActivityDate;
            nt.WhatID = t.WhatID;
                    
            Database.SaveResult SR = database.insert(nt);
            taskscopied++;                
            }
        }         
        return taskscopied;

    }

Document Actions

Comments (1)

Kevin Bromer Oct 23, 2008 03:19 PM
I've modified the above code from the original task copier. The copier will now 'assign' the task to whomever the logged in user who runs the code is.
« February 2012 »
February
MoTuWeThFrSaSu
12345
6789101112
13141516171819
20212223242526
272829