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
sfdc98sfdc98 

trigger add error scenario

Hi everyone ,i have tried below trigger ,Account should have only one active oppotunity ,but it is not working as expected ,not hitting error.help me..
trigger:
trigger onlyonechildactive on Opportunity (before insert,before update) {
set<Id>accountId=new set<Id>();
    for(opportunity o:trigger.new){
        if(o.AccountId!=null){
            accountId.add(o.id);
        }
    }
    List<Account>acclist=[select id,name,(select id,stageName,closeDate,name,Active__c from opportunities where Active__c=true)from Account where Id=:accountId];
    map<id,boolean> bb=new map<id,boolean>();
    //for each account
    for(Account a:acclist){
        bb.put(a.id,a.opportunities.size()>0  );
            
        }
    for(opportunity op:trigger.new){
        if(bb.get(op.AccountId)==true && op.Active__c==true){
           op.addError('there is already a Active opp'); 
        }
    }
    }
Thanks in Advance
Best Answer chosen by sfdc98
Naveen KNNaveen KN
    for(opportunity o:trigger.new){
        if(o.AccountId!=null){
            accountId.add(o.id);
        }
    }

You are adding opportunity id to the account id set, hence when we query the account object with opportunity id it is not fetching the records. Rest looks good. 

change it to accountId.add(o.Accountid);

-
Naveen KN

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
trigger onlyonechildactive on Opportunity (before insert,before update) {
set<Id>accountId=new set<Id>();
    map<id,opportunity> Accountoppmap = new map<id,opportunity>();
    for(opportunity o:trigger.new){
        if(o.AccountId!=null){
            accountId.add(o.AccountId);
        }
    }
   List<opportunity> opplist = [select id,accountId,name,Active__c from opportunity where (Accountid=:accountId AND Active__c=true)];
    for(opportunity oppps: opplist){
        Accountoppmap.put(oppps.accountId,oppps);
        
    }
   
 for(opportunity opp: trigger.new){

 if(Accountoppmap.containsKey(opp.AccountId)){
      ppmap.containsKey(opp.AccountId));
 
 opp.adderror('Please choose another account');
 
 }
 }
 

    }
Naveen KNNaveen KN
    for(opportunity o:trigger.new){
        if(o.AccountId!=null){
            accountId.add(o.id);
        }
    }

You are adding opportunity id to the account id set, hence when we query the account object with opportunity id it is not fetching the records. Rest looks good. 

change it to accountId.add(o.Accountid);

-
Naveen KN
This was selected as the best answer