function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
King KooKing Koo 

Trigger - how to insert into two dependent objects?

Hi there

 

I want to create a trigger so that, when a record is inserted into object A,

 

that will create one or more records into object B (that has a lookup to object A)

 

and will create one or more records into object C (that has a lookup to object B)

 

My construct to insert the records into object B is straightforward:

 

for loop (for each records to be inserted to object B)

{

        ListVariable.add(a new instance of object B)

}

insert(ListVariable)

 

i.e. I first put all the records that I need to insert into object B into a list, and then call the insert.

 

To insert records into object C, I will need to get the Id of object B.

 

Now that I have created into object B, how do I retrieve the IDs of each record that I inserted into object B so I can finish the second part of the trigger?

 

Thanks

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
ForceMantis (Amit Jain)ForceMantis (Amit Jain)

When you use insert Ids are automatically populated in object/collection of object that you just inserted. for example

 

Account a = new Account(Name = 'ABC');
insert a;

System.Debug(a.Id); //Will give id of newly inserted account

 You can apply same thing to list. Hope this helps.

All Answers

ForceMantis (Amit Jain)ForceMantis (Amit Jain)

When you use insert Ids are automatically populated in object/collection of object that you just inserted. for example

 

Account a = new Account(Name = 'ABC');
insert a;

System.Debug(a.Id); //Will give id of newly inserted account

 You can apply same thing to list. Hope this helps.

This was selected as the best answer
King KooKing Koo

Thanks, looking at my original posting, it actually wasn't quite complete, I think I"ll need to rephrase my question slightly.

 

But you are right, it does pass the Id back in a list, just like if you're inserting one record.  THanks for that!

 

Let me re-think my question and I'll post again.

 

Thanks!