2

I have written a small code snippet:

public void setAttachment()
{
    renderForm = false;
    System.debug('renderForm is'+renderForm);
    String fileContent = ApexPages.currentPage().getParameters().get('fileContent');
    upsert dFlow;

    if (fileContent.length() > 23)
    {
        attachment.Body = EncodingUtil.base64Decode(fileContent.substring(5+11+7));
        if(attachment.ParentId == null)
            attachment.ParentId = dFlow.Id;
        upsert attachment;
    }
}

When I call this function via actioncall, it's giving me an error:

Field is not writeable: Attachment.ParentId

How do I associate an attachment with a custom object?

2 Answers 2

2

You cannot update The parentID.

At some point in your code, the attachment record was inserted and the parent ID in the database was updated. When you try to set it in your code you then get the error because it is already set int he database.

We will need to see more code to help you find the point where the attachment gets

1

The plain fact is: you can't reparent Attachments because of the parentId isn't writable. But you can work around that limitation in two ways:

  • either you create a new Attachment using the destination parentId and copy some other relevant field values including the body and then insert the new and delete the old attachment
  • or you prevent the first insert until you know it's final destination and then insert it once at the right place. But this works only if your logic is running in a single transaction and is not split splitup into more. E.g. if the attachment was inserted earlier and now you select it from DB to reparent it can't work and you have to choose the method above: copy&delete

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .