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
nsoosnsoos 

Apex trigger to create child object code

Hi,

 

I have a master object KC_Sales_c and a child object Pro_Forma_c

 

I have created an Apex trigger so that every time a KC Sales record is added a Pro Forma is automatically created.


Is it correct?

 

Thanks

 

trigger CreateProForma on KC_Sales__c (before insert) {

//1. Create collection of new Pro Formas
List<Pro_Forma_c> newProForma = new List<Pro_Forma_c>();

//2. Iterate through the new sales

for (KC_Sales_c sale : trigger.new) {

//2a. For each sales, create a new pro forma
Pro_Forma_c freshProForma = new Pro_Forma_c();
freshProForma.KC_Sales_c = sale.id;
freshProForma.Name = sale.Name_c;

// NO NO!
// insert freshProForma;

//2b. Add the new ProForma to the collection
newProForma.add(freshProForma);

}

//4. Save the new ProFormas

insert newProFormas;

}

Sfd developerSfd developer

Hi,

 

For creating child records, you need to use after trigger,

 

trigger CreateProForma on KC_Sales__c (after insert) {

List<Pro_Forma_c> newProForma = new List<Pro_Forma_c>();


for (KC_Sales_c sale : trigger.new) {

Pro_Forma_c freshProForma = new Pro_Forma_c();
freshProForma.KC_Sales_c = sale.id;
freshProForma.Name = sale.Name_c;


newProForma.add(freshProForma);

}

insert newProFormas;
}

 

C_GibsonC_Gibson

What if you want the record that these child objects have been created in the parent object. I am attempting to write a trigger where child objects must be created and a checkbox on the parent is checked to signify that these records have been created. I have attemped to make the call asynchronously from an after insert trigger and also tried doing this in a before insert. Any thoughts?