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

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 :{
        if(c.accountId != null){
    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)  {
for(Opportunity o:
        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.

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