2

I have a wrapper class which has one attribute for Parent record and another list of child records.

I'm getting this list of wrappers from my lightning component. Now I need to insert these records.

How can I map the parent with the correct child record while inserting?

Wrapper:

public class Wrapper {
    
    @AuraEnabled
    public Account acc {get;set;}
    @AuraEnabled
    public List<Contact> conList{get;set;}
    
    public TaskAnalysisDataWrapper(){
        acc = new Account();
        conList = new List<Contact>();
    }
    
}

Now I have a list of Wrapper in my apex method:

List<Wrapper> wrapperList

How can I match contact with correct account while inserting records?

1 Answer 1

1

Simple. First, insert the accounts, then the contacts. Here's an example using your wrapper as a starter:

@AuraEnabled public static void createAccountsAndContacts(Wrapper[] wrapperList) {
  Account[] accounts = new Account[0];
  for(Wrapper item: wrapperList) {
    accounts.add(item.acc);
  }
  insert accounts;
  Contact[] contacts = new Contact[0];
  for(Wrapper item: wrapperList) {
    // Associate each contact to its account
    for(Contact contactRecord: item.conList) {
      contactRecord.AccountId = item.acc.Id;
    }
    contacts.addAll(item.conList);
  }
  insert contacts;
}

This all works because of how objects are stored: by "reference". When you create the accounts, the variable in the wrapper is also updated. This allows us to keep track of which contact belongs to which account without any extra setup.

A reference simply means that the variable stores an object's memory address, so when you pass them between each other, the memory points to the same address, so it's the same object. Here's a simple example of that behavior:

Account record1 = new Account();
Account record2 = record1;
record2.Name = 'Demo';
System.debug(record1.Name); // Demo

As you can see, we update one variable, and the other sees the change. Similarly, doing a DML on a list of records from variables extracted from the wrapper will also update the wrapper records.

1
  • Thanks for quick answer and also explaining
    – sfdc
    Nov 29, 2020 at 17:47

You must log in to answer this question.

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