+ Start a Discussion
grandak koygrandak koy 

How to create apex class to insert child record when parent record changes

I have an apex class that creates a child record when a field on the parent record changes: 
public with sharing class newTable {


  public static void newTable(
  Map < Id, Team__c > oldTeam,  List<Team__c> Team) {
  list<table__c>  P = new list<table__c> ();
   for(team__c team :teams)  {
  if ((team.filled__c = TRUE ||
  team.Sent__c == 'Confirmed') && .
 (oldTeam.get(team.id).filled__c = False ||
  oldTeam.get(team.id).Sent__c != 'Confirmed')) {
  T.add(new table__c(team__c = team.id, com__c = TRUE));
 insert T;
    }
   }
 }
 }
It inserts a record but shouldn't I be using newMap instead of New? Since I just want to review that the parent record changes (compare the old to the new) instead of comparing a list of records? What would be the correct way to write an apex class to insert a child record when a field on the parent changes that doesn't match the previous and fits filled__c ="True"?

I have created this class to be called from my triggerhandler, so I would prefer not to write a trigger for it.


 
Raj VakatiRaj Vakati
Just modify the code 
 
public with sharing class newTable {


  public static void newTable(Map < Id, Team__c > oldTeam,  List<Team__c> Team) {
  list<table__c>  P = new list<table__c> ();
   for(team__c team :teams)  {
  if ((team.filled__c = TRUE ||
  team.Sent__c == 'Confirmed') && .
 (oldTeam.get(team.id).filled__c = False ||
  oldTeam.get(team.id).Sent__c != 'Confirmed')) {
  p.add(new table__c(team__c = team.id, com__c = TRUE));

    }
   }
   
   if(p.size()){
	   insert p ;
	   
   }
 }
 }

 
grandak koygrandak koy
Thank you, but why use the new list and not new map? If I wanted to compare old and new values shouldn't I do newmap?
Raj VakatiRaj Vakati
You can use both the list or map. but the only thing is if you use the map you can compare the old values with out iterations.because you can get the old value from the map directly
grandak koygrandak koy
When I change the If Statement to include a change that a lookup field on the parent changes (Team__r.Tenant_shift__c ='occupied' it does not insert a record.