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
IntroAmmyIntroAmmy 

on Account if duplicate opportunity record present then throw error

I have one sceanrio, 

In Account we have more than 1 Opportunity tagged and we are trying to update the one of opprtunity status from Removed to Active and if other opprtunity already present with Active status for this account then it should throw an error and not able to save the record 
can someone please help on that via trigger 
HarshHarsh (Salesforce Developers) 
Hi,
Please try the below code.
Put your Status API name in place of (status api name).
You can put an Error message as per your need.
 
// trigger
trigger opportunitytriggerdemo on Opportunity (before update) {
    if(trigger.isBefore && trigger.IsUpdate){
        opportunitytriggerdemohandler.Demo(trigger.new);
    }
}

---------------------------------------------------------------------------------------------------------------
// handler class

public class opportunitytriggerdemohandler {
    public static void Demo(list<Opportunity> updateoppo){
        set<id> accid = new set<id>();
        for(Opportunity obj: updateoppo){
            accid.add(obj.AccountId);     
        }
        List<Opportunity> retivedata = [select Id, name, (status api name) from opportunity where AccountId In:accid AND (status api name) = 'Active'];
        if(!retivedata.isEmpty()){
            for(Opportunity obj: updateoppo){
                obj.addError('You cant update the record, active record is there');
            }
        }
    }
}

Please mark it as Best Answer if the above information was helpful.

Thanks.