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
Paulien van der Krift 9Paulien van der Krift 9 

How to create a detail object with one record per project month?

Hi everyone, I have a complicated question.

We have an object called Project. This object contains te following fields:
- Project Name
- Start date
- End date
- Total project months
- Average revenue per month

We want to create a detail object that holds a record for each month within a project. So this Project Months object should have:
- Project Name (master-detail relationship)
- Month number (month number - year, a text field)
- Average revenue per month (formula field, automatically the avg revenue belonging to the related project)

So in short, when a project is created, there should be records created for each Project Month containing the project name, month number and revenue. So when a project has 12 months, 12 records should be automatically added to the object Project Month, each containing the project name, month number and revenue.

I'm looking for a smart and maintenance fiendly way to do this. Please advise!
Meghna Vijay 7Meghna Vijay 7
Hi,
The only way i can think of is by creating a trigger on Project with After Insert event and creating records for Project Month. Do you want a code snippet?

Thanks.
Lokesh KumarLokesh Kumar
Do you want all 12 child records to get created at one time or Month wise?
Paulien van der Krift 9Paulien van der Krift 9
@lokesh they need to be created at one time

@megna yes please, thanks!
Meghna Vijay 7Meghna Vijay 7
trigger on  ProjectTriggger (After Insert) {
  if(Trigger.isAfter && Trigger.isInsert) {
    ProjectTriggerHandler.handleAfterInsert(Trigger.New);
}
}

public class ProjectTriggerHandler {
      List<ProjectMonth > proMonthList = new List<ProjectMonth >();
      public static void handleAfterInsert(List<Project> newProjectList) {
        
   for(Project newPro : newProjectList) {
     // Add a check if that Project Months is not null
    // Loop over those project Months using currentMonth variable and Inside the Loop create ProjectMonth records  
    // Since Average Revenue is a formula field so it can be done via config      
        ProjectMonth proMonth = new ProjectMonth(Project Name = newPro.Id, Month Number = currentMonth );
        proMonthList.add(proMonth);
        
}
if(proMonthList.size()>0) {
    insert proMonthList;
}

}
}
Hope it helps. 
Thanks
Meghna Vijay 7Meghna Vijay 7
Hi Paulien,
If the issue is solved please mark it as solved.
Thanks