0

Getting Invalid loop variable type expected Id was Transaction__c error in the last for loop. P.s. I am also using a trigger handler:

Set<Id> transactionIds = new Set<Id>();
        for(TransactionItem__c rec: (List<TransactionItem__c >) Trigger.new) {
            transactionIds.add(rec.Transaction__c);
        }

        Map<Id, AggregateResult> results = new Map<Id, AggregateResult>([
        SELECT Transaction__c Id, count(Id) sum
            FROM TransactionItem__c
            WHERE Transaction__c = :transactionIds
            GROUP BY Transaction__c
        ]);

        for(Transaction__c record: transactionIds) {
            Integer itemCount = (Integer)results.get(record.Id)?.get('sum');
                if(itemCount == null) {
                    itemCount = 0;
                }
            System.debug('Total transaction items = ' + itemCount);
        }
2
  • When you do transactionIds.add(rec.Transaction__c) you actually put an id into the list. So your for loop must be for ( Id recordId : transactionIds) – nchursin Dec 19 '20 at 10:17
  • These are compilations error. Please go through how to write code in apex. Trailheads are good place to start. – Nagendra Singh Dec 19 '20 at 10:23
3

Your trigger is working on TransactionItem__c, so that's what you need to use in your loop:

for(TransactionItem__c record: (TransactionItem__c[])Trigger.new) {
    Integer itemCount = (Integer)results.get(record.Transaction__c)?.get('sum');
        if(itemCount == null) {
            itemCount = 0;
        }
    System.debug('Total transaction items = ' + itemCount);
}
1
  • Finally it ran successfully! I know I need to do a lot of learning. I am doing so and I will get there with the help of Awesome people like you. Thanks @sfdcfox - appreciate all the help. – STSF Dec 19 '20 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.