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
Rahul.SharmaRahul.Sharma 

Can we insert related record on child object using before insert trigger on parent object. How can I populate parent record id on child record alternatively in before insert trigger itself even it is not generated yet ?

Can we insert related record on child object using before insert trigger on parent object. How can I populate parent record id on child record alternatively in before insert trigger itself even it is not generated yet?
I want to generate child record related with parent record when new parent record is created. But I need to do this thing in before insert trigger only because some validations also need to be performed before inserting parent record. How can I achieve this?
Best Answer chosen by Rahul.Sharma
Rahul-SharmaRahul-Sharma
Hi Rahul,

You cannot create child records by using before insert trigger on parent object. You must use after triggers for this puropose. 
However, you have mentioned you need to perform some validations on parent record too. For that purpose, use either validation rules or before trigger then write your insert logic in after trigger.

Hope this would help.

Regards,
Rahul Sharma

All Answers

Manohar kumarManohar kumar

Hi Rahul, 
You can't get id in before trigger. I think you have to go with after trigger here. If validation occurs it will be rolled back. 
Are you sure you can't do this with after trigger. 

Thanks,
Manohar 

Rahul.SharmaRahul.Sharma
Hi Manohar,
It can be done by after trigger very easily but I need to do this using before trigger because the validation must be done in before trigger only. After data validated successfully then I need to insert and create related child record. Is there any alternate way to achieve this requirement?
Thanks,
Rahul
Manohar kumarManohar kumar
Hi Rahul,
i can't think of any other way. Your validations are on parent or child object ? Give after trigger a try your vaildation will be catched in that, i think. 

Thanks,
Manohar 
Arpit Jain7Arpit Jain7
Hi Rahul,

You can not get record Id in before insert it is not possible. Though what you can do is do all your validation in before insert and once everything goes well then you can create some checkbox and mark it true.Once this checkbox field value is true then insert your related child records with process builder or trigger.

Hope this helps !

Thanks
Arpit
Rahul-SharmaRahul-Sharma
Hi Rahul,

You cannot create child records by using before insert trigger on parent object. You must use after triggers for this puropose. 
However, you have mentioned you need to perform some validations on parent record too. For that purpose, use either validation rules or before trigger then write your insert logic in after trigger.

Hope this would help.

Regards,
Rahul Sharma
This was selected as the best answer