Sunday 23 November 2014

Simple Script for Calculating bumber of childs in Salesforce!

Hi Guys!!

Its been long time.  This time I am with very simple scenario. Must say salesforce is expanding day by day. Its really awesome, but its becoming very difficult to keep running salesforce, so many new features are being released with every release.

Any ways lets get back to buisness.

Scenario:- Say, I have many accounts and Contacts in my Org. And I simply wants to calculate the number of Contacts that are related to one account.

Solution:-

It is very easy . Just take a copy and a pen, and lay down the idea and think before writting the code.
prerequisite :- Get familiar with Workbench. 

In workbench go to the apex execute.  section , which is under the Utilities.



Map<id,List<Contact>> mapit = new Map<id,List<Contact>>();
for(Contact con : [Select id, AccountID from Contact]){
 If(Con.AccountId != null){
    mapit.put(con.AccountId, new List<Contact>([Select id from Contact where AccountId = : Con.AccountID]));
}
}
System.debug('=='+Mapit.keySet().size());
For(Account acc : [Select id from Account where id in :Mapit.keySet()]){
     system.debug('size='+mapit.get(acc.id).size());
    acc.NumberofLocations__c = mapit.get(acc.id).size();
}


NumberofLocations__c is a number field in account. 

Happy Coding
Ankush 

ankushsalesforce@gmail.com










No comments:

Post a Comment

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...