function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dmchengdmcheng 

Errors when inserting TaskRelation records

I have a client who wants the ability to clone a task that has multiple contacts. They would make slight changes to the cloned task (Assigned To, etc) but the multiple contacts would remain the same.

I'm getting a DUPLICATE_VALUE error when I tried to insert the cloned TaskRelation records and I can't figure out why. Do I need to create the task relation records in a different way?

Here's what I'm doing:

I retrieve the TaskRelation records for the original task, use the clone() list method, then insert the cloned Task, then replace the TaskId with the cloned task Id, and attempt to insert the cloned taskRelation records.

The error detail is:

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []

Here are the code snippets:
 
originalRelations = [SELECT RelationId, TaskId, IsWhat FROM TaskRelation 
        WHERE TaskId = :originalTask.Id AND IsWhat = false];
// Don't preserve Id, deep clone.
cloneTask = originalTask.clone(false, true);
cloneRelations = originalRelations.deepClone(false);
...
...
insert cloneTask;
for (TaskRelation relation : cloneRelations) {
    relation.TaskId = cloneTask.Id;
}
insert cloneRelations;

 
Best Answer chosen by dmcheng
dmchengdmcheng
I figured it out - when I insert the clone task, Salesforce automatically creates a TaskRelation for the WhoId, so the duplicate error is because my clone TaskRelation list also contains that combination of WhoId / TaskId.

When I construct the clone TaskRelation list in a loop and skip the existing Task.WhoId, then it works.