1

I am trying to insert a parent and related child records in same apex execution phase.

// code to cretae parent record list
 List<Parent_Record__c> parentList = new List<Parent_Record__c>();
 List<Child_Record__c> childList = new List<Child_Record__c>();

    Parent_Record__c pr1=new Parent_Record__c();
    pr1.field1__c='f1';
    pr1.field2__c='f2';
    parentList.add(pr1);

    Child_Record__c  ch1=new Child_Record__c();
    ch1.field1='f1';
    ch1.Parent_Record__c=pr1.Id;
    childList.add(ch1);

    Child_Record__c  ch2=new Child_Record__c();
    ch2.field1='f1';
    ch2.Parent_Record__c=pr1.Id;
    childList.add(ch2);

    insert parentList;


    insert childList;

With the above code, the insertion of child record is failing saying parent id is null.

Here there is a Master-detail relation between parent and child. The parent object is already reaching all limits so we don't want to create an external id.

Is there any other way to achieve this?

1
  • 1
    You need to insert parent record before accessing pr1.Id while collecting child object.
    – Raul
    May 5, 2017 at 7:38

2 Answers 2

1

Hi The list which got inserted for parent records (parentlist) will contain the record id afterthe insert operation.

Get the value of parent id from the parentlist and assign to the child list.

Then insert childlist.

1

Yes the error is given are absolutely correct , the reason is :

  1. you are assigning the parent id in child object before inserting the value of parent object.

your code should be like below :

// code to cretae parent record list
 List<Parent_Record__c> parentList = new List<Parent_Record__c>();
 List<Child_Record__c> childList = new List<Child_Record__c>();

    Parent_Record__c pr1=new Parent_Record__c();
    pr1.field1__c='f1';
    pr1.field2__c='f2';
    parentList.add(pr1);

    insert parentList;// inserting the parent record

    Child_Record__c  ch1=new Child_Record__c();
    ch1.field1='f1';
    ch1.Parent_Record__c=parentList[0].Id;//updating the parent record after insertion 
    childList.add(ch1);

    Child_Record__c  ch2=new Child_Record__c();
    ch2.field1='f1';
    ch2.Parent_Record__c=parentList[0].Id;//updating the parent record after insertion 
    childList.add(ch2);

    //insert parentList;


    insert childList;

it should work.

You must log in to answer this question.

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