You need to sign in to do that
Don't have an account?
hamza akouayri
Trigger Start date End date
Hello All,
I have two custom objects. project_c and week_c
In Project_c.object i have fileds start date and end date
I want to create a trigger that will create records of weeks in week_c object based on start date and end date
For example:
---------Project---------
start date : 10/02/2020
end date : 27/02/2020
----------week----------
week 9Feb
week 16Feb
week 23Feb
*PS (first day of the week will be sunday )
Thanks in Advance
I have two custom objects. project_c and week_c
In Project_c.object i have fileds start date and end date
I want to create a trigger that will create records of weeks in week_c object based on start date and end date
For example:
---------Project---------
start date : 10/02/2020
end date : 27/02/2020
----------week----------
week 9Feb
week 16Feb
week 23Feb
*PS (first day of the week will be sunday )
Thanks in Advance
Trigger:
-------------------
trigger ProjectTrigger on Project__c (before Insert) {
if(Trigger.isBefore) {
if(Trigger.isInsert) {
ProjectHandler.onBeforeSave(Trigger.New);
}
}
}
Apex class:
--------------------------
public with sharing class ProjectHandler {
public static void onBeforeSave(List<Project__c> projects) {
List<Week__c> newWeeks = new List<Week__c>();
// Loop to iterate over the list of Project records
for(Project__c project : projects) {
//Date that accepts the Start Date
Date startDate = project.Start_Date__c ;
System.debug('Date of Start : ' + startDate);
// It will get the start date of the week based on Date so here it is 2020 02 09
StartDate = StartDate.toStartofWeek();
System.debug('Start of week for Start Date : ' + startDate);
Date endDate = project.End_Date__c;
System.debug('Date of EndDate : ' + EndDate);
// It will get the start date of the week based on Date so here it is 2020 02 09
endDate = endDate.toStartofWeek() + 7;
System.debug('Start of week for end Date : ' + endDate);
while(startDate < endDate) {
Week__c week = new Week__c();
DateTime dt = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day()) ;
week.Name = String.valueOf(startDate.day()) + dt.format('MMM');
System.debug(week.Name);
startDate = startDate+7;
newWeeks.add(week);
}
}
try {
if(!newWeeks.isEmpty()) {
insert newWeeks;
}
}catch(DMLException e) {
System.debug('Unable to insert the weeks : ' + e.getMessage());
}
}
}
Input:
-----------------------
Start Date:
Feb 10, 2020
End Date:
Feb 27, 2020
Output:
---------------------
9Feb
16Feb
23Feb
I hope this helps.
Thanks,
but i still face issue when i try to update the recorde it create a dupliaction of weeks
Example
Project level
startDate: 02/09/2020 endDate: 02/25/2020
weeks level
9 Feb
16 Feb
23 Feb
updated Example startDate: 02/09/2020 endDate: 03/03/2020
weeks level
9 Feb
16 Feb
23 Feb
9 Feb
16 Feb
23 Feb
1 Mar
instead
9 Feb
16 Feb
23 Feb
1 Mar
now i think i have to create a logic for update than add update event to the trigger