0

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?

  • Please do not use duplicate punctuation, it is often considered impolite. – Adrian Larson Jun 14 '17 at 11:13
0

In your trigger make a set of all parent Id field and then query the child based on that and use 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 accountmap you will get count of all child till 5 level. To fill AccountIdSet you can use same query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.