+ Start a Discussion

trigger for counting total cases in an asset

Hi there,

I am new to writing triggers (in fact, havent written anything yet) but I am fairly familiar with custom controllers and visualforce pages.


recently we have a requirement to count the number of cases related to an asset. There's already a built-in relationship and the detail page of the asset displays the number of cases in one of the links at the top "Cases [1]".


I'm wondering how I can put this number in a custom number field so we can run our own asset validations through this field?


Any help in getting started is greatly appreciated.






Write a trigger on Case after insert, update, delete, undelete.


Use the aggregate query to get the count for each Asset and update the field on Asset record.


Fetch all the asset Ids from the case records in a set: assetIdSet


AggregateResult[] groupedResults = [SELECT AssetId, COUNT(Id) FROM Case WHERE AssetId IN :assetIdSet GROUP BY AssetId ];


Update the Asset records.