Skip to content. | Skip to navigation

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

Apex Snippet: Opp Task Copier

A class and method to handle copying tasks from one opoortunity record to another. Takes a opportunity ID as a string (or ID, they're implicitly converted in SF), uses an opportunity named "Task Template" as a template for the tasks (this can be changed by reassigning the value for the global 'OppTasksName') and returns the number of tasks copied from the template record to the calling record. It will also assign the tasks to the currently logged in user, set any closed tasks on the source opp to open on the destination opp, and move the dates forward. It will not copy tasks from one to the other if the subject is already in the list of the calling contact's tasks. Stolen from Kevin's Task Copier class.
//Written by Kevin Bromer, copyright (c) 2008 NPower Seattle
//Modified by Mike Jones
//OppTaskCopy Class

public class OppTaskCopy {    

    /***********Instance Variables***********/
    integer taskscopied = 0;
    id ThisOpportunity;
    id OppTasksID;
    boolean FirstTask = true;
    date FirstTaskDate;
    date Today = Date.Today();
    integer DaysToAdd = 0;

    //This string defines the name of the Opportunity FROM which tasks are to be copied
    string OppTasksName = 'Task Template';

    //Constructor for TaskCopy
    public OppTaskCopy(id OpportunityID)
        {
            ThisOpportunity = OpportunityID;
        }

	public integer copyIt()    
    {
        //Get the ID for Opportunity 'Fin Aid Tasks'
        Set st = new Set();
        OppTasksID = [select id from Opportunity WHERE name = :OppTasksName].id;

        for (Task s : [select subject from Task WHERE WhatID = :ThisOpportunity])
            {
                st.Add(s.Subject);
            }        

        for (Task t : [SELECT ID, WhoID, Subject, Description, OwnerID, Status, Priority, ActivityDate, 
                        WhatID FROM Task WHERE WhatID = :OppTasksID order by activitydate])
            {
            Task nt = New Task();
               if (st.Contains(t.subject) != true)
               {
                   if (FirstTask == true) 
                {
                DaysToAdd = t.ActivityDate.daysBetween(Today);
                }
            nt.WhatID = ThisOpportunity;
            nt.Subject =  t.Subject;
            nt.Description = t.Description;
            nt.OwnerID = UserInfo.getUserId();
            nt.Status = 'Not Started';
            nt.Priority = t.Priority;
            nt.ActivityDate = t.ActivityDate.addDays(DaysToAdd);     
            Database.SaveResult SR = database.insert(nt);
            taskscopied++;              
            }
        FirstTask = false;
        }
        return taskscopied;
    }
Document Actions

Comments (0)

« February 2012 »
February
MoTuWeThFrSaSu
12345
6789101112
13141516171819
20212223242526
272829