+ Start a Discussion

trigger to insert more records based on date difference

Hi Friends,

I have a requirement, where I need to insert child records based on date difference.

Below details:
After insert trigger on Order to insert a child custom object based on start date and end date difference.
For Eg: Start Date = 28/02/2020 and End Date = 28/03/2020.
Difference is 29 days and I want to create 29 child records.

How can I start writing the trigger. Kindly give your suggestions.

Thanks in Advance.
Best Answer chosen by HTANIRS
Ashish Singh SFDCAshish Singh SFDC

You can use daysbetween function for this requirement.

Below is the sample code which will help you in understanding about this function and you can test in your dev Org. Just create two date fields start date and end date in your accout object as a required field.
01trigger DaysDiff on Account (after insert) {
02    List<contact> conlist = new List<Contact>();
03    for(Account acc:Trigger.new){
04        Integer dayCount = acc.Start_Date__c.daysBetween(acc.End_Date__c);
05        for(integer i=0; i<dayCount; i++){
06            Contact con = new Contact();
07            con.lastName = acc.name;
08            con.accountId = acc.ID;
09            conlist.add(con);
10        }
11    }
12    insert conlist;
Ashish Singh.