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
Admin 123Admin 123 

Account and Contact Object have Lookup relationship.

Account and Contact Object have Lookup relationship.
There are two requirements:

To display the count of Contacts into the Account Object.So I have created the trigger for it and now it is displaying the Contacts Count onto the custom field of Account Object.

Now the Second Requirement is: ParentAcc: ABC ,,,Account1: Contact1, Contact2 (count will display 2 in Account custom field) ParentAcc: ABC,,,Account2: Contact1, Contact2, Contact3(count will display 3 in Account custom field)
But now In Parent Account: ABC Count Should Display as 5.

How can we achieve this??
NagendraNagendra (Salesforce Developers) 
Hi,

In your trigger make a set of all parent Id field and then query the child based on that and use the parentId field to make a group of them. Now in a map increase the count.
Map<Id,integer> accountMap = new Map<Id,integer>();
for(Id accountId : AccountIdSet)
    accountMap.put(accountId, 0);
for(contact c: [Select Id,AccountId,Account.ParentId,Account.Parent.parentId, Account.Parent.Parent.parentId, Account.Parent.Parent.Parent.parentId from contact where AccountId IN : AccountIdSet Or Account.ParentId IN : AccountIdSet Or Account.Parent.parentId IN : AccountIdSet Or Account.Parent.Parent.parentId IN : AccountIdSet Or Account.Parent.Parent.Parent.parentId IN : AccountIdSet]){
    if(accountMap.containsKey(c.AccountId))
        accountMap.put(accountId,accountMap.get(c.AccountId)+1);
    if(accountMap.containsKey(c.Account.ParentId))
        accountMap.put(accountId,accountMap.get(c.Account.ParentId)+1);
    if(accountMap.containsKey(c.Account.Parent.parentId))
        accountMap.put(accountId,accountMap.get(Account.Parent.parentId)+1);
    if(accountMap.containsKey(c.Account.Parent.Parent.parentId))
        accountMap.put(accountId,accountMap.get(c.Account.Parent.Parent.parentId)+1);
    if(accountMap.containsKey(c.Account.Parent.Parent.Parent.parentId))
        accountMap.put(accountId,accountMap.get(c.Account.Parent.Parent.Parent.parentId)+1);
}
Here AccountIdSet is the Id of all parent Account of current child account. Now using this code in the account map you will get a count of all child till 5 level. To fill AccountIdSet you can use the same query.

Hope this helps.

Thanks,
Nagendra