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
Padmini S 26Padmini S 26 

Inserting the child records double time

I have 3 objects Booking, Products and Collections. Booking object has two related lists that is Products and Collections. After creating the booking record then automatically collection records are created depend on field payment duration on Booking. For this i have implemented the Apex Trigger. It is inserting the child collection records fine only but problem is when i will update the booking payment duration field as 2 again 2 more recods are inserting under collection object. It is inserting collection records again. If i will remove the after update event then child collections records are inserting the payment amount as 0.Below is the trigger.
trigger createCollections on Order ( after insert, after update) {

List<Collection__c> coll = new List<Collection__c>();
for(Order o : trigger.new)
{
 if(createcollectionclass.runonce()){
if(o.Payment_Duration__c != null  && o.Type == 'Periodic' )
{
for(integer i = 0; i< integer.valueOf(o.Payment_Duration__c); i++){

                Collection__c c= new Collection__c();
                c.Order__c = o.id;
                c.Payment_Amount__c = ( o.Total_Due__c/o.Payment_Duration__c);
                coll.add(c);
            }
}
}
}
if(!coll.isEmpty()){
    insert coll;
    }       
}
Kindly help on this issue.

 
SandhyaSandhya (Salesforce Developers) 
Hi Padmini,

You can check condition for isinsert and isupdate.
 
if(isInsert)
{
insert coll;
}

if(isUpade)
{
update coll;
}

or simply use

(upsert coll); instead of( insert coll;)

Hope this helps you!


Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 
Padmini S 26Padmini S 26
Hi Sandhya,
Thank you for your help. I have tried with both scenarios. Still it is inserting child records again. Kindly let me know how to resolve this issue.

Regards,
Padmini