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
SF7SF7 

Trigger to create multiple child records when a parent is created

Hi ,
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model

Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices 

Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .

I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .

Here is the start with able to create single child record 
 
trigger CreatePaymentLineItems on Payment__c (after insert) {   
   
  
   
    
        List<Payment_Item__c> PItem = new List<Payment_Item__c>();
        for (Payment__c Pay : trigger.new) 
        {
           Payment_Item__c PBI = new Payment_Item__c();
            PBI.Payment__c = Pay.Id;
           // PBI.Financial__c = Pay.;
           
            
            PItem.add(PBI);
        }
        insert PItem;
    }

Thanks,
Akhil
Best Answer chosen by SF7
Vigneshwaran GurunathanVigneshwaran Gurunathan
trigger CreatePaymentLineItems on Payment__c (after insert) {
		List<Payment_Item__c> PItem = new List<Payment_Item__c>();
		Set<Id> setAccountId = new Set<Id>(); // Set of Id to hold Account id's in Payment
		Map<Id,Integer> mapAccountIdInvoiceCount = new Map<Id,Integer>(); // Map of Id to Integer to hold Account Id and corresponding number of Invoices
        for (Payment__c Pay : trigger.new) 
        {
			setAccountId.add(pay.Account__c); //Here Account__c is the relationship field in Payment__c which relates to Account
		}
		for(Account a : [Select Id,(Select Id from Invoices) where id =: setAccountId])
		{
			mapAccountIdInvoiceCount.put(a.Id,a.Invoices.size()); // Populate map with Account Id and corresponding list of invoice size
		}
		for (Payment__c Pay : trigger.new) 
        {
			for(Integer i=0; i<mapAccountIdInvoiceCount.get(pay.Account__c);i++)
			{
				Payment_Item__c PBI = new Payment_Item__c();
				PBI.Payment__c = Pay.Id;
				// PBI.Financial__c = Pay.;
				PItem.add(PBI);
			}
        }
        insert PItem;
    }

 

All Answers

Vigneshwaran GurunathanVigneshwaran Gurunathan
trigger CreatePaymentLineItems on Payment__c (after insert) {
		List<Payment_Item__c> PItem = new List<Payment_Item__c>();
		Set<Id> setAccountId = new Set<Id>(); // Set of Id to hold Account id's in Payment
		Map<Id,Integer> mapAccountIdInvoiceCount = new Map<Id,Integer>(); // Map of Id to Integer to hold Account Id and corresponding number of Invoices
        for (Payment__c Pay : trigger.new) 
        {
			setAccountId.add(pay.Account__c); //Here Account__c is the relationship field in Payment__c which relates to Account
		}
		for(Account a : [Select Id,(Select Id from Invoices) where id =: setAccountId])
		{
			mapAccountIdInvoiceCount.put(a.Id,a.Invoices.size()); // Populate map with Account Id and corresponding list of invoice size
		}
		for (Payment__c Pay : trigger.new) 
        {
			for(Integer i=0; i<mapAccountIdInvoiceCount.get(pay.Account__c);i++)
			{
				Payment_Item__c PBI = new Payment_Item__c();
				PBI.Payment__c = Pay.Id;
				// PBI.Financial__c = Pay.;
				PItem.add(PBI);
			}
        }
        insert PItem;
    }

 
This was selected as the best answer
SF7SF7
Hi Vignesh,

Thanks for the reply 

I am getting an error at 
 for(Account a : [Select Id,(Select Id from Invoices) where id =: setAccountId])   ---  
and 
 mapAccountIdInvoiceCount.put(a.Id,a.Invoices.size()); // Populate map with Account Id and corresponding list of invoice size   -- No field invoices . Here i beleive we are refernceing Custom child object Invoices__C Right?
sandeep sankhlasandeep sankhla
Hi Akhil, 

Let me know if this is solved or you need any help. You can check the cofrrect syntax and field names before using them in query.

Thanks
SF7SF7
Hi Sandeep,

I still could not get this to working, I checked the names and i am using the correct object names .

Thanks
sandeep sankhlasandeep sankhla
Can you share the entire code and error so I can look into ?

 
SF7SF7
 Compile Error: unexpected token: 'Select' at line 11 column 23  (On Select Statment )
Invalid field FInancials__C on account
trigger CreatePaymentLineItems on Financial_Batch__c (after insert) {
     
     
        List<Financial_Batch_Item__c> PItem = new List<Financial_Batch_Item__c>();
        Set<Id> setAccountId = new Set<Id>(); // Set of Id to hold Account id's in Payment
        Map<Id,Integer> mapAccountIdInvoiceCount = new Map<Id,Integer>(); // Map of Id to Integer to hold Account Id and corresponding number of Invoices
        for (Financial_Batch__c Pay : trigger.new) 
        {
            setAccountId.add(pay.Account__c); //Here Account__c is the relationship field in Financial_Batch__c which relates to Account
        }
        for(Account a :Select Id,(Select Id from Financials__c) where id =: setAccountId])
        {
            mapAccountIdInvoiceCount.put(a.Id,a.Financials__c.size()); // Populate map with Account Id and corresponding list of invoice size
        }
        for (Financial_Batch__c Pay : trigger.new) 
        {
            for(Integer i=0; i<mapAccountIdInvoiceCount.get(pay.Account__c);i++)
            {
                Financial_Batch_Item__c PBI = new Financial_Batch_Item__c();
                PBI.Financial_Batch__c = Pay.Id;
                // PBI.Financial__c = Pay.;
                PItem.add(PBI);
            }
        }
        insert PItem;
        }



 
sandeep sankhlasandeep sankhla
Hi

Replace line no 11 with this line

for(Account a : [Select Id,(Select Id from Financials__c) where id IN: setAccountId])
let me knwo if it works.

Thanks
SF7SF7
Still getting error 
Error: Compile Error: unexpected token: where at line 11 column 65

I tried differnt syntaxes for the IN condition and still having issues
SF7SF7
trigger CreatePaymentLineItems on Financial_Batch__c (after insert) {
     
     
        List<Financial_Batch_Item__c> PItem = new List<Financial_Batch_Item__c>();
        Set<Id> setAccountId = new Set<Id>(); // Set of Id to hold Account id's in Payment
        Map<Id,Integer> mapAccountIdInvoiceCount = new Map<Id,Integer>(); // Map of Id to Integer to hold Account Id and corresponding number of Invoices
        for (Financial_Batch__c Pay : trigger.new) 
        {
            setAccountId.add(pay.Account__c); //Here Account__c is the relationship field in Financial_Batch__c which relates to Account
        }
       for(Account a : [Select Id,(Select Id from Financials__r) from account where id IN: setAccountId])
        {
            mapAccountIdInvoiceCount.put(a.Id,a.Financials__r.size()); // Populate map with Account Id and corresponding list of invoice size
        }
        for (Financial_Batch__c Pay : trigger.new) 
        {
            for(Integer i=0; i<mapAccountIdInvoiceCount.get(pay.Account__c);i++)
            {
                Financial_Batch_Item__c PBI = new Financial_Batch_Item__c();
                PBI.Financial_Batch__c = Pay.Id;
                // PBI.Financial__c = Pay.;
                PItem.add(PBI);
            }
        }
        insert PItem;
        }

This worked . Thanks sandeep . I have one more question . So when i am adding all invoices(Financials) to the Financial Line item i want to exclude the Invoices which are alreadt created for other Financial Line item . So bascially before we added all invoices for the customer now we have to limit it. Sorry if i am asking for too much

Thanks
Akhil.
SF7SF7
The reason it worked i chnaged the field name from __c to __r
SF7SF7
I have one pb here , when my new 20 records are created one for each invoice it doesn't have the lookup field for invoice populated .Any suggestions please
SF7SF7
@Vignesh 

Thanks for the solution . I am one step away from completion. Trigger autpmaticaly created 20 records only missing peice is the Lookup Feild getting populated. I want those 20 Invoices filled in the Lookup so that they can access the invoice right from there 
Greer Zimmerman 5Greer Zimmerman 5

Hi I have a question that kind of expands on this question:

I have workshops and individual sessions for that workshop in Salesforce. When a workshop is created I want the sessions to be created based on the information entered on the workshop record. I understand how to do this if the workshop meets just one day a week (see code below) but sometimes these workshops meet two or three times a week and the particular days are stored in a multi picklist. The user can select which days they meet, the start date, and the end date. 

I cannot for the life of me figure out how to create ongoing records for sessions occuring on, say, Mondays AND Thursdays AND Wednesdays or any other combo of days. Can anyone help?

trigger AssociatedSessions on Group__c (after insert) {

	List<Session__c> session = new List<Session__c>();
    
    for (Group__c newGroup: Trigger.New) {
            Date sd1 = newGroup.Start_Date__c;
            Date ed1 = newGroup.End_Date__c;
            
            if (newGroup.Frequency__c == 'weekly') {
                integer numberOfWeeks = sd1.daysBetween(ed1) / 7 ;
            
            	for(integer i = 1; i < numberOfWeeks ; i++){
              	  session.add (new Session__c(
                  Term__c = newGroup.Id,
                  Date__c = sd1 + i * 7)
                  );
                      
            	}   
  			}
        if (newGroup.Frequency__c == 'daily') {
            integer numberOfDays = sd1.daysBetween(ed1);
            
            for(integer i = 1; i < numberOfDays ; i++){
              	  session.add (new Session__c(
                  Term__c = newGroup.Id,
                  Date__c = sd1 + i * 7)
                  );
             }
        }
        if (newGroup.Frequency__c == 'biweekly') {
            integer numberOfDays = sd1.daysBetween(ed1) / 14;
            
            for(integer i = 1; i < numberOfDays ; i++){
              	  session.add (new Session__c(
                  Term__c = newGroup.Id,
                  Date__c = sd1 + i * 14)
                  );
             }
        }
        if (newGroup.Frequency__c == 'monthly') {
            integer numberOfDays = sd1.daysBetween(ed1) / 30;
            
            for(integer i = 1; i < numberOfDays ; i++){
              	  session.add (new Session__c(
                  Term__c = newGroup.Id,
                  Date__c = sd1 + 30)
                  );
             }
        }
        
    insert session;
 	}
}