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
VICKY_SFDCVICKY_SFDC 

trigger on new opportunity and Old account

Assume In an account opportunity is there then 2nd opportunity its pop up an An error else if no opportunity is there then automatic an opportunity will be created?
ANUTEJANUTEJ (Salesforce Developers) 
Hi Vikas,

Can you try the below code once 

trigger opptri on Opportunity (before insert) {
List<Id> accID = new List<Id>();
    for(Opportunity c : trigger.new){
        if(c.accountId != null){
            accID.add(c.accountId);
        }
    }
    AggregateResult[] groupedResults
      = [SELECT Accountid,count(id) FROM Opportunity where AccountId in :accID  Group BY AccountId]; 
      map<id,integer> accoountmap= new map<id,integer>();
      for (AggregateResult ar : groupedResults)  {
          
    accoountmap.put((id)ar.get('Accountid'),(integer)ar.get('expr0'));
}
for(Opportunity o: trigger.new)
{
    system.debug(accoountmap.get(o.AccountId));
    if(accoountmap.get(o.AccountId)>=1)
    {
        system.debug('inside check');
        o.adderror('cannot have more opportunities under this account');
    }
 
}}

and in case if this helps please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej
VICKY_SFDCVICKY_SFDC
2nd half of code is working where inserting more than one opportunity,BUT OTHER HALF WHERE OLD ACCOUNT DON'T HAVE AN OPPORTUNITY WILL SHOW AN ERROR MSG ON THAT ACCOUNT IS NOT WORKING