+ Start a Discussion

Related List population in Apex

In an Apex batch process, I am s creating record of a new RecordType that is a consolidation of 2 existing RecordTypes of  each Account record.


It is functioning properly EXCEPT it's not getting the Related Lists.  I presume that it would require specific code to address it but,  for instance,  to populate the Related Contacts, I used:


Note - The item.Accounts is the source record List which includes Account.Contacts in the query,  myAccount is the new record being created.


myAccount.Contacts = item.Account.Contacts;     I got the error  -  field is not writable.


I tried     myAccount.Contacts.Id = 'xx';   -  ( xx is just to test the reference) which resulted in  the error  -   Invalid foreign key relationship.


Any ideas on how this would be populated?



Best Answer chosen by Admin (Salesforce Developers) 
Jake GmerekJake Gmerek

So you are approaching it the wrong way, the contacts are related to the account not the other way around.  You need something like this:


for (contact c: item.Account.Contacts){


c.accountID = item.Account.ID;




update item.Account.Contacts



I am not sure what the structure of the item object is, so you may have to tweak that a little bit and i am not sure if you can do this "update item.Account.Contacts" you may have to push your contacts onto a separate list and update them that way, but this should get you started.