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
Mani RenusMani Renus 

How to count the existing no. of accounts using trigger??

I have to write trigger on custom object...
I have to count the no. of accounts where territory (lookup)=t1 , then the count value display in my custom object...How can we do this using trigger??
Cloud_BKCloud_BK
Hi Mani,

First thing is you need to determine if you want this trigger to only fire on creation and/or update.

You could do this be writing a SOQL query in your trigger that pulls all account records into a list.  Use the WHERE operator at the end of the SOQL query to limit the results to only those with a territory of t1.

From here you can write a for loop to iterate through each new/updated custom object (called trigger.new in apex) and store the size of the newly created list in a custom field.

Here is more guidance on all the methods (functions) you can call on an apex list. http://www.salesforce.com/us/developer/docs/dbcom_apex250/Content/apex_methods_system_list.htm

Good luck,

BK
Abhi_TripathiAbhi_Tripathi
Hey,

Salesforce provides a SOQL Query named as Aggregate queries, where you can count the total number of records in the query by a particular value

you can use a query like this

//Query returns the number of records fetched
SELECT COUNT() FROM Account

Here is the URL for your help
http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_agg_functions.htm

Regards,
Abhi Tripathi
Salesforce Developer