+ Start a Discussion
John ClevelandJohn Cleveland 

Trigger to copy parent child to custom parent child objects

I have Custom Object A and Custom Object B which is a child of A.
I also have Custom Object C and Custom Object D which is a child of C.
When records are created in Custom Object A and B, I need to copy values from A and B to C and D. I have a trigger to copy A to C but need help with adding code to copy B to D. Can anyone help? It would be greatly appreciated.
 
trigger createCFromA on Custom_Object_A (after insert, after update) {

	Id RecTypeId =  [Select Id from RecordType where name = 'recordtype' and sObjectType = 'Custom_Object_C' limit 1].Id;

    
    List <Custom_Object_C> cToInsert = new List <Custom_Object_C>();

    
    for (Custom_Object_A a : Trigger.new){        

        if (a.Status__c == 'New' ) {
                
        Custom_Object_C c = new Custom_Object_C (); 
        
                c.Field_1__c = a.Field_1__c;
				c.Field_2__c = a.Field_2__c;
				c.Field_3__c = a.Field_3__c;
				c.RecordTypeId = RecTypeId;

        cToInsert.add(c);
        
        }
        
    }
    

    try {
        insert bToInsert; 
    } 
        catch (system.Dmlexception e) {
        system.debug (e);
    }
    
   
}

 
pratap singh 10pratap singh 10
is this trigger working?
bToInsert is not populated anywhere.
you can write similar trigger on Object B to copy it to Object D,

 
John ClevelandJohn Cleveland
Yes it's working. bToInsert is really cToInsert. 

So there's no way to do it in one trigger? If I do another trigger on object b how would it know to make the parent id the one the records should link to in object C. I'll also need to copy attachments from object A to object C. 
John ClevelandJohn Cleveland
Anyone have ideas
pratap singh 10pratap singh 10
try to do divide the logic in smaller chunks.
Trigger event will fire when your dml event(after insert) occurs, So Ideally parentId will alreay be populating.
For copying attachment you need to write a another trigger on Attachment object.
Hope it will give you some Ideas to go ahead :)