Reparent notes and attachments using apex

The parent ID is not writeable after insert. You will have to copy the attachment / note to a new attachment/note, then set the parent id there. Insert the new one, and delete the old one.

For example:

Attachment a = [SELECT Name, Body FROM Attachment WHERE ParentID = :oldParentId];
Attachment b = New Attachment(Name = a.Name, Body = a.Body);
b.parentID = newParentId;
insert b;
delete a;

Nope, you cannot directly update the ParentId field on the note and attachments. You can find more information on the below link what all you can update or insert.

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_attachment.htm

There is a workaround to change the parentId, it involves the below step:

  • Create new records of the notes and attachment with the new parentId and copy over all the fields from the old records.
  • Delete the old records

Tags:

Apex