You need to sign in to do that
Don't have an account?

trigger to insert child record based on parent record update
Hi Friends,
I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records.
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
Let me know your suggestions to complete this requirement.
Thanks in advance.
I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records.
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
trigger insertDailyPractices on Study_Plan__c (after insert) { System.debug('--- Inside Trigger ---'); List<Daily_Practice__c> dplist = new List<Daily_Practice__c>(); for(Study_Plan__c sp : Trigger.New) { if(String.isNotBlank(sp.Phase_Start_Date__c) && String.isNotBlank(sp.Phase_End_Date__c) { Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c); System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c); System.debug('--- Day Count ---' + daycount); for(integer i=0; i<=daycount; i++) { Daily_Practice__c dps = new Daily_Practice__c(); dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1; dps.StudyPlan__c = sp.Id; dps.Status__c = 'Assigned'; dplist.add(dps); } } } if(dplist.size() > 0) { insert dplist; } system.debug('--- Inserted Daily Practice ---'+ dplist.size()); }
Let me know your suggestions to complete this requirement.
Thanks in advance.
For the sencond requirement you can use the trigger.old to get the old values and check the difference to get the number of records you will have to create or delete.
I hope this helpful for your use case in case if it did help please close the thread by amrking a best answer so that it can be useful to others in the future and also helps in keeping the community clean.
Regards,
Anutej
I think you missed after update in the trigger function. As you are editing the date in the current record. Use after Update Function and try once again. Use after Update and Trigger.old. The issue will be resolved.