0

We have a scenario, where 3rd party system send us the data to salesforce and using that data we are creating new parent object record along with its child record and we are able to create it.

Problem: I have written a trigger on parent object, where I want to fetch that newly created child record id from the newly created parent record, I am able to get the parent record Id, but not able to get the child record id. Below is the code

Trigger on parent object:

Trigger parentTrigger on ParentObject(after update, after insert,before update, before insert){
if(Trigger.isAfter &&  Trigger.isInsert){
   parentTriggerHandler.getChildId(Trigger.New);//call trigger handler class
   }
}

Trigger Handler class:

public class parentTriggerHandler{
public static void getChildId(List<ParentObject> newParentObject){
    Set<Id> idParentObject = new Set<Id>();
    List<ChildObject> lstChild = new List<ChildObject>();
    for(ParentObject objParent : newParentObject){
        idParentObject.add(objParent.Id);  //able to get the parent record id.
     }

   if(!idParentObject.isEmpty()){
      lstChild = [SELECT Id,ParentObject__c,Name FROM ChildObject WHERE ParentObject__c IN:idParentObject];//not able to get the child record(getting empty list)
      }
    }
}

1 Answer 1

1

It is impossible for a newly-created parent record to have any child records until its own save process completes. This means you cannot access any child records that will be created in the parent object’s after-insert event.

You may be able to observe these records in the parent after-update event if inserting a child record results in mutation to the parent. It’s much more likely, however, that you want to be building whatever functionality this is in a trigger on the child object.

You must log in to answer this question.