1

I'm trying to create a very basic trigger - when I create a Parent Object record, create a Child Object record under it. Here's what I have so far, it saved without errors, but no child record gets created when I create a parent record. But when I edit a Parent record I get error:

trigger CreateChild on Parent__c (before update) 
{
    List<Child__c> Childs = new List<Child__c>();

    for(Parent__c a : trigger.new)
    {
       Child__c Child = new Child__c ();
       Child.id=a.id;
       Child.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs; 

}

And I'm newer than new to Apex Triggers...not to Salesforce, but this is my first Trigger. Thanks everyone

2

@David: Few points to note:

  1. Code should be applicable for trigger "after insert" mode, so that child record is created only after creation of parent record.

  2. Additionally, in order to establish the relationship, you need to associate child with parent, by populating parent's id in relationship field. Parent's id would only be available in after insert

Sample code:- (psuedocode)

trigger CreateChild on Parent__c (after insert) {
    List<Child__c> Childs = new List<Child__c>();

    for(Parent__c a : trigger.new)
    {
       Child__c Child = new Child__c ();
       Child.Parent__c = a.id;
       Child.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs;
}
  • Wow. Anshul, that was perfect man. I literally did a Find/Replace with your pseudocode with my object names and it worked LIKE. A. CHARM. Thank you so very much! I was able to repeat a chunk of code 10 times and now when I create a new Parent, 10 new Children are added under it. (I'm sure there's a much cleaner way to do that, but here it is now) Not sure how to get the code block readable below – TNSalesforceGuru May 10 '15 at 23:32
  • trigger CreateChild on Parent__c (after insert) { List<Child__c> Childs = new List<Child__c>(); for(Parent__c a : trigger.new) { Child__c Child = new Child__c (); Child.Parent__c = a.id; Child.Name = 'Child 1'; Childs.add(Child); } for(Parent__c a : trigger.new) { Child__c Child = new Child__c (); Child.Parent__c = a.id; Child.Name = 'Child 2'; Childs.add(Child); } insert Childs; } – TNSalesforceGuru May 10 '15 at 23:34
  • happy to help :) – Anshul May 10 '15 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.