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
JuanTalJuanTal 

I need to create a roll-up summary only with apex code

I have a trigger-before-update in a parent custom object and i wanna create a roll-up summary with other custom object-child

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
trigger calculosPresupuesto on Presupuesto__c ( before update) {
  
  if(Trigger.isUpdate){ 
    Presupuesto__c [] pre = Trigger.new;
    Movimiento_Presupuestal__c [] mov;
    String cuenta;
    for(Presupuesto__c p:pre){ 
      cuenta = p.Partida__c;
    } 
    mov = [SELECT cuenta__c FROM movimiento_presupuestal__c WHERE  cuenta__c =: cuenta];
     
    cAfectaciondePresupuesto.calcularPresupuesto(pre,mov); 
     
  }
     
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

public static void calcularPresupuesto(Presupuesto__c [] pre, Movimiento_Presupuestal__c [] mov){
    Double cargo, reserva, abono; 
    Date fecha;
    String cuenta;
    Integer mes;   
     
         Double prueba;  
         
    for(Presupuesto__c p:pre){     
      cuenta = p.Name;   
      p.auxcuenta__c = cuenta;
      Movimiento_Presupuestal__c [] movim = [SELECT cargo__c, abono__c, reserva__c, fecha_de_movimiento__c FROM movimiento_presupuestal__c WHERE  cuenta__c =: cuenta limit 1];
      for(Movimiento_Presupuestal__c movi:movim){
        cargo = movi.Cargo__c;
        fecha = movi.Fecha_de_Movimiento__c;
        mes = fecha.month();
      }  
      p.Balance_Anual__c = p.Presupuesto_Anual_Aprobado__c - p.Gasto_Anual__c - p.Reserva_Anual__c;
      if(mes == 1 ){ 
        p.Balance_Enero__c = p.Presupuesto_de_Enero__c - cargo - reserva;
        
      }  
     
    }
  }  
  
  

}

the line from 15 to 18 all assigned values are null, cuenta is the lookup field,  any idea...

dmchengdmcheng

For rollup summaries, the trigger has to be on the child object, not the parent object.  If a change occurs in a child record, that's when you want to recalculate the summary in the parent record.