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
dpardpar 

When parent is created automatically child record also created for each date from start date to end date

I have two objects projects and timesheet where project have start date and end date. Requirement is when parent record is create the child record for each date from start to end date using trigger
v varaprasadv varaprasad
Hi Digna,

Try like below : 
 
trigger OppTrigger on project__c (After insert) {
    
    list<timesheet__C> lstTimes = new list<timesheet__C>();
    for(project__c opp : trigger.new){      
        if(opp.StartDate__c != null && opp.EndDate_c != null && opp.StartDate__c <= opp.EndDate_c){
           date startDate  = opp.StartDate__c;
            for(integer i=0; startDate<opp.EndDate_c; i++){
                System.debug('Created child records '+i);
				timesheet__C ts = new timesheet__C();
				//Add all fields
			
				lstTimes.add(ts);
				
                startDate = startDate.addDays(1);
                system.debug('==startDate=='+startDate);
            }
            
        }
    }
	
	if(lstTimes != null){
	   insert lstTimes;
	}

}

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Salesforce Project Support: varaprasad4sfdc@gmail.com

Salesforce latest interview questions  :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1