+ Start a Discussion
Rogerio Lara 2028Rogerio Lara 2028 

Apex Trigger to create a child record when a new parent record is created.

I need to create a child record when a new parent record is created.

I am trying to create an Apex trigger that creates or forces a child record to be created when a new parent record is created, but unfortunately isn't working :-(

 
trigger CreateBuyingInfluence on Opportunity_Positioning__c (after insert)

 {
    List<Buying_Influence__c> Childs = new List<Buying_Influence__c>();

    for(Opportunity_Positioning__c a : trigger.new)
    {
       Buying_Influence__c Child = new Buying_Influence__c ();
       Child.SCOP__c = a.id;
       Buying_Influence__c.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs;
}

I'm getting this error message: Error: Compile Error: Expression cannot be assigned at line -1 column -1

Please, I would really appreciate any help. ;-)

Thank you,
Rog
UC InnovationUC Innovation
Hi Rog,

Line 10 looks incorrect. It should look like this:

Child.Name = 'testName';
 
trigger CreateBuyingInfluence on Opportunity_Positioning__c (after insert)

 {
    List<Buying_Influence__c> Childs = new List<Buying_Influence__c>();

    for(Opportunity_Positioning__c a : trigger.new)
    {
       Buying_Influence__c Child = new Buying_Influence__c ();
       Child.SCOP__c = a.id;
       Child.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs;
}

That should work!
Rogerio Lara 2028Rogerio Lara 2028
Thank you very much Ken. It’s setting off the trigger but because I have required field on the child object Buying Influence I am getting an error. Is there a workaround it, or will I have to remove “required” from the fields? Error: Invalid Data. Review all error messages below to correct your data. Apex trigger CreateBuyingInfluence caused an unexpected exception, contact your administrator: CreateBuyingInfluence: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Degree of Influence, Rating for base covered]: [Degree of Influence, Rating for base covered]: Trigger.CreateBuyingInfluence: line 15, column 1
Rogerio Lara 2028Rogerio Lara 2028
What if I just want to redirect the page? Let’s say, when the Opportunity Positioning is created then upon saving the record a trigger will prompt me to create Buying Influences or direct me to the buying influence pages.? I removed required from those fields and the trigger is creating a new record but with 5 fields not being populated. Any suggestions as to what would be best in this case? Thank you so much. Rog
UC InnovationUC Innovation
You could use a combination of process builder and flows. Use process builder to fire the flow upon record creation, and you can design the flow to bring up a page to create the child Buying Influence by passing in the parentID from the process builder.