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
Pankaj Yadav 29Pankaj Yadav 29 

Trigger opportunity if it has two open opportunity related stop the user not created that opportunities

Set<String> setname = new Set<String>();
     for(Opportunity opp : Trigger.New)
     {
         setname.add(opp.Name);
     }
    List<Opportunity> opplist = [SELECT ID, Name, StageName From Opportunity Where Name In:setname And (stageName='closed won' OR stageName='closed lost')];
    Map<String, Opportunity> mapopp = new Map<String, Opportunity>();
    Map<String, Opportunity> mapopen = new Map<String, Opportunity>();
    for(Opportunity opploop : opplist)
    {
       mapopp.put(opploop.Name, opploop);
       mapopen.put(opploop.StageName, opploop);
    }
    for(Opportunity oppnew : Trigger.New)
    {
        if(mapopp.containsKey(oppnew.Name) && mapopen.containsKey(oppnew.StageName))
        {
            oppnew.addError('same name with two opportunity');
        }
    }
This trigger is working but my doubt another way doing that type of question 
Peter.BaezaPeter.Baeza
Not exatly sure what you are trying to do but the StageName check seems strange. The query can  have many Opps as result and the map will have 1 key entry for any stage that is among any of these opps.  So in many cases with 200 Opps as input you might end up with a mapOpen map that has both closed won and closed lost as keys.  If you only want to check for duplicate names I think you can skip the mapopen map. Also if you only want to check against closed opps it might be better to use the isClosed boolean field in the query instead of the stagenames. Then you wil get all closed opps regarless of the stage name. 
Peter.BaezaPeter.Baeza
Another thing that might be worth checking is that if you are also running similar code as part of a update trigger then you might detect the same opp as initiatted the transaction as a duplicate name. I guess that what you are doing now is trying to prevent creation of an opp with the same name as an existing closed or won opp so just a new insert trigger. But then nothing prevents a name change to a duplicate name. Also since you only are comparing with closed opps you might run into a situation where multiple opps with same name are open and if one of them gets closed then how would you handle the remaining ones. Not sure if this is valid for your use case and you might already have handled it but pointing it out just in case.