-3

My Requirement is I want to get Total Count of Opportunities and Contact on Account Object.If I delete Contact or Opportunities Count should be updated Automatically.

Can someone please suggest possible solution?

2

You can easily get Opportunity Count on Account Object with the help of Configuration.

Follow Below Steps:

  • Navigate To Account Object.
  • Under 'Account Custom Fields & Relationships' Click on New button to create Custom Field.
  • Select Field Type as Rollup Summary Field.Click Next then mentioned field Name as 'Opportunity Count'.Click Next,Under Summarize Object Select 'Opportunities' as Summarize Object.Select Roll-Up Type as 'Count'.Click Next and Establish field-level security to User Profile and make it visible to Page Layout.

Thats it you will see Opportunity Count on Account Object.

However in Order to get Contact Count.You need to go with Apex Solution because Contact has Lookup Relationship with Account and You can create Rollup Summery Field only when Child has Master Detail Relationship with Parent.Here is the Sample Code that gives you Contact Count.

Apex Class:

public class ContactTriggerClass{
  public static void contactCount(List<SObject> newItems, List<SObject> oldItems)
    {
    Map<Id,Account> AccountMap=new Map<Id,Account>();
            set<String> updateContactCount= new Set<String>();
            set<String> accId=new Set<String>();
            for(SObject newObj :newItems) {
                Contact newCntObj = (Contact)newObj;
                Contact oldCntObj = null;
                if(newCntObj.Id!=null && oldItems!=null) {
                    oldCntObj = (Contact)newObj;
                }
                if(newCntObj.AccountId!=null){
                accId.add(newCntObj.AccountId);
                }
            }

                for(Account ac:[Select Id,Contact_Count__c,(select Id from Contacts) from Account where Id IN:accId]){
                    ac.Contact_Count__c=ac.Contacts.size(); // Contact_Count__c is a Custom field that needs to be created on Account
                    AccountMap.put(ac.Id,ac);
                }

            update AccountMap.values();
    }

}

Apex Trigger:

trigger ContactTrigger on Contact (After Insert,After update,After Delete,After Undelete) {
 List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;
    ContactTriggerClass.contactCount(contacts,contacts);
}

Add the above code and let me know if it helps.

0

You can easily achieve that result by creating a set of rollup summary fields in the Account record that COUNT the child records.

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.