Master-Detail fields not writable? | How to fix 'Error: Field is not writeable--for Master-Detail relationship'

by - 9:23 PM

What if you try modifying the field that are  master-detail relationship using code (API). If you do so, you might encounter this error highlighted below. Realistically, from user interface perspective , these fields are locked and are non-editable.

System.SObjectException: Field is not writeable: Child_Object__c.Master_Detail_Field__c

Can I still be able to achieve that ? Yes you can

The workaround I am suggesting here is situational and you got to figure out your case. Ideally a simple approach would be, to change the relationship type from (Master-Detail) to Lookup relationship if we want to make it work, but if you cannot than you have to 'deep clone records'.

Read more about deep clone in salesforce docs here at -  Clone Method()

Here is my scenario - I am using Salesforce Chatter Communities and in communities, we have Zones (read about it here), the Question and the Reply. They are in master-detail relationship to each other, meaning reply could not exist without question, similarly question cannot exist without zones. Lets make it more clear looking at relationship visually

This is how it looks like

Zones (Master-Detail)   ----> Question (Master-Details) -------> Reply

My objective was to move question/answers with their votes, datacategories from one zone to another. I thought of cloning questions and just pointing replies to newly cloned questions. But this is not as simple as it look like reason being

1. Question and Replies are in (Master-Detail) relationship
2. QuestionId field on Reply object signifies, which question this reply belongs to  and this field is  read-only so i cannot modify/update the reply to point to new cloned question, just like shown here

Reply.QuestionId= newQuestion.Id;  
//Pointing old reply to new question, this field is not writeable as well

So I decided to clone both the objects with their hierarchies (meaning both question/replies) and then deleted copied objects to clean the data.

First I cloned questions, then I cloned the Replies, then I relate them maintaining relationship and commit records, later afterward I delete the old question that I copied, which in turn deleted related replies as well, because they are in master-detail relationship.

This is how I did it : Notice, I am getting all replies with all question in one single query itself, if you carefully notice

Once we have map, we will do deep clone of standard object (Question/Replies), here code comments are self explanatory on how I am cloning keeping hierarchies as it is

Should be it !

You May Also Like