0

Hi I need to calculate fields in a trigger depending on the parent Account record. For this, I created on the custom object Object__c, where the calculation needs to be done, the text field Parent_Account__c which copies the ParentId from Account to Object__c. Then I implement the trigger - it is just an excerpt as the trigger is more complicated. Please mind I do know to move the logic to a class, but for now I just want the trigger to be working.

trigger triggerUpdateObject on Object__c (before insert, before update) {

    public list <String> listParentIds = new list <String>();
    public list <Object__c> listObject = new list <Object__c>();

    //loop through new/updated records (I need this twice in the trigger due to other logic)
    for (Object__c cv: trigger.new){

        listParentIds.add(cv.Parent_Account__c);

    }

    public Map<Id,AggregateResult> mapAggAR = new Map<id,AggregateResult>([Select ParentId, Min(Field)minfield, Max(Field)maxfield from Account where Field <> null AND ParentId <> null AND ParentId IN :listParentIds group by ParentId]);   

    //loop through records again
    for (Object__c cv: trigger.new){

        //loop through ParentIds from Aggregate Result Map and calculate field depending on ParentId
        for (Id mapId : mapAggAR.keyset()){

            AggregateResult ARObject = mapAggAR.get(mapId);
            Double ValueMax = Double.valueof(ARObject.get('maxfield'));
            Double ValueMin = Double.valueof(ARObject.get('minfield'));

            //calculate fields on the record where ParentId is the Account Parent Id
            if (cv.Parent_Account__c == mapId){
                cv.Max = ValueMax;
                cv.Min = ValueMin;
            }
        }

}

I get the error

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger triggerUpdateObject caused an unexpected exception, contact your administrator: triggerUpdateObject: execution of BeforeUpdate caused by: System.ListException: Row with null Id at index: 0: Trigger.triggerUpdateObject: line 25, column 1

That is the line where I generate the map mapAggAR. I have created accurate test records, so there should be Ids available. So what is wrong? Thanks for your help!

Vamsi Krishna Gosu
  • 10,464
  • 5
  • 32
  • 49

0 Answers0