I’m doing something with some custom objects analogous to this, just because it’s structurally very handy to have the parent record and the child record grouped together:
Account a = new Account(); Contact c = new Contact(); a.Contacts.add(c); system.debug(a.Contacts.size());
No matter how many contacts I add, the size is always zero and there are never any there. There’s no error. Just a.Contacts
remains empty.
Is this expected?
I know there are a zillion other ways to do this and I’ve used enough of them that I don’t need workarounds, I’m just surprised this doesn’t work so I’d like to know if I can make this work.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The “child relationship” entities on a record (e.g. Account.Contacts) are immutable lists, and can only be populated by a query (or as the result of deserialization from JSON using JSON.deserialize()
). They are never null, and they actively resist any attempt to change them, such as using sort()
, add()
, addAll()
, remove()
, and clear()
. You cannot use any assignment operator, such as =
, to override the reference that they contain.
Why?
As for why: They’re not intended for general storage of data, but instead meant to be used for enumerating the results of a query. Since this is specialized data, it has special rules. This is outlined in the documentation in the developer’s guide. If you need to associate these records together, use a map or a multi-dimensional array.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0