9 answers
I've reproduced the code with (hopefully) all the issues fixed. I also changed the placement of the test for productIds being empty. You don't want to do the query with an empty set - it will throw an error.<pre>public trigger UpdateProductStockCounts on Asset ( after update ){ // map which stock counts go into which product fields Map<String,String> stockFields = new Map<String,String> { 'Available' => 'Available_Stock__c', 'Not Available' => 'Consumed_Stock__c' }; // figure out which products need to be updated Set<Id> productIds = new Set<Id>(); for ( Asset asset : Trigger.new ) { Asset oldAsset = Trigger.oldMap.get( asset.Id ); if ( asset.Status__c != oldAsset.Status__c ) { productIds.add( asset.Product2Id ); } } if ( !productIds.isEmpty() ) { // use aggregate query to subtotal asset counts by product and status Map<Id,Product2> productsToUpdate = new Map<Id,Product2>(); for ( AggregateResult result : [ SELECT COUNT(Status__c) stock, Status__c, Product2Id FROM Asset WHERE Product2Id IN :productIds GROUP BY ROLLUP(Product2Id, Status__c) ] ) { Id productId = (Id) result.get( "Product2Id" ); if ( !productsToUpdate.containsKey( productId ) ) { productsToUpdate.put( productId, new Product2( Id = productId ) ); } Product2 product = productsToUpdate.get( productId ); String status = (String) result.get( "Status__c" ); Decimal stock = (Decimal) result.get( "stock" ); String field = stockFields.get( status ); if ( field != null ) { product.put( field, stock ); } } update productsToUpdate; }}</pre>