+ Start a Discussion
DeveloperDeveloper 

Please write trigger on account object


There can only be one active record of the Opportunity associated to the Account, 
please write on trigger.
Best Answer chosen by Developer
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger OneOppPerAcc on Opportunity (before insert) {
    
    List<id> accId = new List<id>();
    for(Opportunity cc : trigger.new){
        if(cc.AccountId != null){
            accId.add(cc.AccountId);    
        }
    }
    
    List<Opportunity> ccList = new List<Opportunity> ();
    
    List<Account> accLst = [select id,(select id from Opportunities) from account where id IN : accId] ;
    for(account accObj : accLst ){
        for(Opportunity c : accObj.Opportunities){     
            ccList.add(c);
        }
    }
    
    for(Opportunity oCon:trigger.new){ 
        if(ccList.size() > 0 ){
            oCon.addError('you can not add more then one Opportunity for this account'); 
            
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas