3

I want to set fields on all child records with values from parent record, but I don't want to use for loop inside a for loop.How can I have only one for loop from this class?

 public class SetChild
 {
public void S_value(List<ParentObjects> Plst)
{
child object clist = select id from child object where relationship In : Plst)

for(parent object : Plst)
 {
 for(child object : clist)
 {
 childobject.field1 = parentobjfield.value1;
 childobject.field2 = parentobjfield.value2;
 childobject.field3 = parentobjfield.value4;
 }
 }

1 Answer 1

3

Could you do something like this?

for ( Child c : [ SELECT id, field1, field2, field3, p.field1, p.field from child where relationship in : plst ])
{
c.field1 = c.p.field1;
..
}

Here is a real-world example using Accounts and Contacts

 list<Contact> updateContacts = new list<Contact>();

    for ( Contact c : [ SELECT Id, Account.Name, Name FROM Contact ])
    {
        c.FirstName = c.Account.Name;
        updateContacts.add( c );
    }

    if ( !updateContacts.isEmpty() )
    {
        update updateContacts;
    }
4
  • hey @Benjamin Pirih, can you please eloborate this, i didn't get your solution properly
    – Sharma_raj
    Commented Apr 12, 2016 at 6:23
  • Updated answer with a simple code example that uses Accounts and Contacts. Same logic will work in your problem.. Commented Apr 12, 2016 at 7:17
  • but here both object should have some relationship then only it works but if no relationship is there then how to achieve this. @Benjamin Pirih
    – Sharma_raj
    Commented Apr 12, 2016 at 7:39
  • I don't understand.. "child records with values from parent record" child / parent implies relationship.. need some type of relationship.. Commented Apr 12, 2016 at 17:25

You must log in to answer this question.

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