+ Start a Discussion
Phuc Nguyen 18Phuc Nguyen 18 

Create multiple child records from parent with different value

Hello All,
Was wondering if someone will help me with the best approach for adding  multiple child records:
Parent is Project  and finance is child.  The Child records will mostly be the same exexpt for a text field that I will populate:
List<Finance__c> finline = new List<Finance__c>();   

if(trigger.isInsert){        
            for (SObject so : Trigger.New) {
                Project__c newP = (Project__c) so;
                
                if (newP.ProjectChild__c != null ) { 
                   Finance__c newF = new Finance__c();
                        newF.Subject = newP.ProjectSubject__c;
                        newF.description__c = 'Custom text for finance record';
                        finline .add(newF);

                        newF.Subject = newP.ProjectSubject__c;
                        newF.description__c = 'Another Custom text for finance record';
                        finline .add(newF);

                }
            }
        }
Was wondering if there is a better way to perform this action.  There will be 5-6 child records.  Also, I will a different child record that will be created off the same parent record and there may be 3-4 records for this custom object.  
Any suggestions would be greatly appreciated.
Cheers,
P
 
Aparna JAparna J
Is there a field on Parent record that defines the number of child records that you need to create from trigger?
Suraj Tripathi 47Suraj Tripathi 47

Hi,

You can take references from the below code.

trigger CreateAccountContact on Account(after insert,after update, after delete) {
    if(trigger.isAfter && trigger.Insert){
	Integer i=0;
        Integer j=100;
	List<Contact> contactList=new List<Contact>();
	for(Account ac:trigger.new){
	contact con=new Contact();
        con.accountId=ac.id;
	con.LastName='Data'+i;
	i++;
	contactList.add(con);
        contact conn=new Contact();
        conn.accountId=ac.id;
	conn.LastName='Data'+j;
	j++;
	contactList.add(conn);

	}
	if(contactList.size()>0){
	insert contactList;
	}
	}
  
}
Thank You
Phuc Nguyen 18Phuc Nguyen 18
Thank you both for the replies. Aparna J, unfortunately there is no indicator that define the number of records that need to becreated.  Suraj Tripathi 47, do I need to increment the variables if I will create records where like in your example I know the LastName and I will be setting it?
Thank you,
P