+ Start a Discussion
Nitesh hadaNitesh hada 

On Account, How to fetch no. of open Opportunity?

On Account, How to fetch no. of open Opportunity
Best Answer chosen by Nitesh hada
PriyaPriya (Salesforce Developers) 
Hi Nitesh,

You need to create a custom field on The Account Object and then you need to write a trigger on the Opportunity object.

I have sample code to count the no of contact for each account. Refer this and modify it accordingly
 
trigger FindContactsCount on Contact (after insert, after update, after delete) {
    
   List<Contact> modContacts = Trigger.isDelete ? Trigger.old:Trigger.new;
    Set<Id> accIds  = new Set<Id>();
    for (Contact c: modContacts)  {
        accIds.add(c.AccountId);
    }
   List<Account> modAccounts = [Select Name, (Select Id from Contacts)  from Account WHERE Id in: accIds ];

    for (Account a: modAccounts) {
       List<Contact> s = a.Contacts;
       System.debug('Account:' + a.Name + ' No. of Contacts: '+ s.size()); 
       a.No_of_Contacts__c = s.size();
    }
}
 

Kindly mark it as the best answer if it works for you.

 

Thanks & Regards,

Priya Ranjan



 

All Answers

PriyaPriya (Salesforce Developers) 
Hi Nitesh,

You need to create a custom field on The Account Object and then you need to write a trigger on the Opportunity object.

I have sample code to count the no of contact for each account. Refer this and modify it accordingly
 
trigger FindContactsCount on Contact (after insert, after update, after delete) {
    
   List<Contact> modContacts = Trigger.isDelete ? Trigger.old:Trigger.new;
    Set<Id> accIds  = new Set<Id>();
    for (Contact c: modContacts)  {
        accIds.add(c.AccountId);
    }
   List<Account> modAccounts = [Select Name, (Select Id from Contacts)  from Account WHERE Id in: accIds ];

    for (Account a: modAccounts) {
       List<Contact> s = a.Contacts;
       System.debug('Account:' + a.Name + ' No. of Contacts: '+ s.size()); 
       a.No_of_Contacts__c = s.size();
    }
}
 

Kindly mark it as the best answer if it works for you.

 

Thanks & Regards,

Priya Ranjan



 
This was selected as the best answer
Andrew GAndrew G
With Account & Opportunity - whilst its a lookup field reference, you can actually create a Roll Up Summary field on the Account record and use the Opportunity records.
Set it to Count and set a filter for Closed <> True

Regards
Andrew