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
kynchiiin2kynchiiin2 

Trigger to create child records

Newbie here - so please be gentle...

 

I have a trigger that I am trying to get to create child record every time a parent is created - works ok, but I need it to create a child record for each product in a lookup (quote_product__c). The code below simply takes one if the IDs from quote_product__c, and it works fine, but I need to loop through every product where active__c = true. ex: [Select id from quote_product__c where active__c = true]

Parent = Quote__c

Child = Quote_Line__c

lookup = Quote_Product__c

trigger AutoCreateQuoteLines on Quote__c (after insert) {
    List<Quote_Line__c> quotelines = new List<Quote_Line__c>();

    for (Quote__c newQuote: Trigger.New) {
        if (newQuote.Account__c != null) {
            quotelines.add(new Quote_Line__c(
                        Quote__c = newQuote.Id,
                        Product__c = 'a27J00000004Fq6'));
        }
    }
    insert quotelines;
}

 Thanks in advance for any help!

Best Answer chosen by Admin (Salesforce Developers) 
Aar3538Aar3538

Hello,

 

Just to make sure I fully understand the requirements, anytime a Quote__c is created, you want  a Quote_Line__c forevery Active Quote_Product__c no matter what.  So if I have 10 Active Quote Products, and I add a new Quote__c, you want to add 10 new Quote_Line__c, correct?

 

Double for loops within salesforce are dangerous due to the ease of hitting limits by using them however sometimes its necessary.  If your Quote Products lists grows too large you can easily begin to run into too many script statements or other errors and might need to come up with other solutions.  However for now,  I would do the following:

 

List<Quote_Line__c> quotelines = new List<Quote_Line__c>();

//Gather the list of quote products

List<Quote_Product__c> quoteProducts =  [Select id from quote_product__c where active__c = true];

 

 for (Quote__c newQuote: Trigger.New) {

        if (newQuote.Account__c != null) {

//Loop through each quote product for each quote.

for (quote_product__c singleQuote: quoteProducts){

 quotelines.add(new Quote_Line__c(

                        Quote__c = newQuote.Id,

                        Product__c = singleQuote.Id));

}

           

        }

    }

    insert quotelines;

 

 

I hope this helps!  Please let me know if I've misinterpreted your requirements or if you need anything else.