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
Kunal Purohit 4Kunal Purohit 4 

Issue in triggers

I am writing this trigger to prevent duplicate entry. But this trigger runs even at time of creating new record..How to resolve?
trigger TriggerOpp on Opportunity (before insert,before update) {
   set<id> setid=new set<id>();
    for(Opportunity opp:trigger.new)
    {
       setid.add(opp.AccountId);
    }
    
    Map<id,Account> acmap=new map<id,Account>();
    
    for(account acc:[select id,Name,(select id,Name,StageName from Opportunities) from Account where id in:setid])
    {
        acmap.put(acc.id,acc);
    }
    
    for(Opportunity opp:trigger.new)
    {
        if(acmap.containsKey(opp.AccountId) && acmap.get(opp.AccountId).Opportunities!=null)
        {
        
           {
               if(opp.StageName=='Prospecting')
               {
                     (opp.AccountId).addError('Duplicate value');
               }
           }
        }
    }
}
Abhishek BansalAbhishek Bansal
Please remove before insert from first line.

trigger TriggerOpp on Opportunity (before update) {
Kunal Purohit 4Kunal Purohit 4
But if i am removing before insert,it is inserting record but not preventing duplication
Abhishek BansalAbhishek Bansal
Hi Kunal,

You can use the below trigger code. You need to add a filter on the existing Opprtunity records that the stage should be equal to Prospecting.
trigger TriggerOpp on Opportunity (before insert,before update) {
   set<id> setid=new set<id>();
    for(Opportunity opp:trigger.new)
    {
       setid.add(opp.AccountId);
    }
    
    Map<id,Account> acmap=new map<id,Account>();
    
    for(account acc:[select id,Name,(select id,Name,StageName from Opportunities where StageName = 'Prospecting') from Account where id in:setid])
    {
        acmap.put(acc.id,acc);
    }
    
    for(Opportunity opp:trigger.new)
    {
        if(acmap.containsKey(opp.AccountId) && acmap.get(opp.AccountId).Opportunities!=null)
        {
        
           {
               if(opp.StageName=='Prospecting')
               {
                     (opp.AccountId).addError('Duplicate value');
               }
           }
        }
    }
}

Thanks,
Abhishek Bansal.
rims polyrims poly
I have junction object Author - research paper. Prevent duplicate Author for same research paper help on this