0

Question:

Salesforce allows me to write specific field values to specific related list records on an object in a Map by referencing the __r[Index] relationship of that particular record.

However, it does not allow me to overwrite the entire Related List in memory with a new (or modified) list of the same SObject Type. Why?


Example (Not Writeable):

Map<Id,SObject1> objectMap = new Map<Id,SObject1>([SELECT Id,
                             (SELECT Id,Field_Name__c FROM SObjects2__r) 
                             FROM SObject1]);

if(objectMap.containsKey(objectId)){
    SObject1 object1 = objectMap.get(objectId);
    List<SObject2> new2List = new List<SObject2>();
    object1.SObjects2__r = new2List; // Not writeable
}

Example (Writeable):

Map<Id,SObject1> objectMap = new Map<Id,SObject1>([SELECT Id,
                             (SELECT Id,Field_Name__c FROM SObjects2__r) 
                             FROM SObject1]);

if(objectMap.containsKey(objectId)){
    SObject1 object1 = objectMap.get(objectId);
    object1.SObjects2__r[0].Field_Name__c = 'Field Value'; // Writeable
}
2

It's not overwriteable because of the hidden background logic regarding related lists. Namely, they can either be a normal List<Sobject> (for some specific type), or they can be a QueryResultIterator (or a similar type), which is when the list isn't populated directly, but instead is given a database cursor to iterate over. In order to preserve this functionality, it was decided that this object would be a special reference that can't be replaced, and the list itself cannot have clear(), add(), addAll(), or remove() called on it. You can actually fake these relationships with JSON.deserialize, if you wanted to, but otherwise they can't be populated except via database queries.

  • Exactly the kind of answer I was looking for, seems reasonable to me! Thanks fox – Morgan Marchese May 3 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.