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
Bob_zBob_z 

Trigger not working correctly. Error message trigger unwanted behavior

I created a trigger that  display an error message if the owner of a opportunity tries to enter the same number in a field that is already on another record. My trigger below is working mostly. The message shows at the field level when there is another opportunity with the same number, but if i create an  opportunity and do not enter a number ( so the field is null/blank). Then go back into the record
and try to add a number it gives me the error message no matter what number I enter into the field. I'm not sure how to get the trigger to allow a user to enter a number in the field after it's been created without getting the error. Any help would be greatly appreciated.
 
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    
    //Display error message if another opportunity has the same number in Quting_Priority__c field

 Set<decimal> oppSet = new Set<decimal>();

 for(Opportunity o : trigger.new){

     oppSet.add(o.Quting_Priority__c);
       
}

 //query all existing record for quoteprioritynum__c
 List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
 Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
      FROM Opportunity 
      WHERE Quting_Priority__c in :oppSet AND 
 Owner.Id = :userinfo.getuserid()];
   
    //ignore system admins
    Profile pr = [select id from Profile where name='System Administrator'];
  
  if(UserInfo.getProfileId()!=pr.id)
for(Opportunity o:trigger.new) 
    
{
    //Check Update for dupe numbers
    if(Trigger.isUpdate && 
    Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c
     && o.LastModifiedBy.Id == o.Owner.Id)
       
    {
       o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
    }

    //Only check for priority size
    if(Trigger.isInsert && o.Quting_Priority__c==o.Quting_Priority__c
         && oppsList.size()>0 && o.LastModifiedBy.Id == o.Owner.Id)
       
    {
       o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');

    }
} 

}



 
Best Answer chosen by Bob_z
ApuroopApuroop
A system admin can create opps with the same Quting_priority.
Other users can't add an opp with the same Quting_priority if a record already exists AND is created by him/her.

Try this:
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    
    //Display error message if another opportunity has the same number in Quting_Priority__c field
    Set<decimal> oppSet = new Set<decimal>();
    for(Opportunity o : trigger.new){
        if(o.Quting_Priority__c != null){
            oppSet.add(o.Quting_Priority__c);
        }
    }
    //query all existing record for quoteprioritynum__c
    List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
                                  Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
                                  FROM Opportunity 
                                  WHERE Quting_Priority__c in :oppSet AND OwnerId =: UserInfo.getUserId()];
    
    //ignore system admins
    Id sysadminId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
    User currentUser = [Select Id, ProfileId FROM User WHERE Id =: UserInfo.getUserId()];
    
    if(currentUser.ProfileId != sysadminId){
        for(Opportunity o:trigger.new){
            //Only check for priority size
            if(Trigger.isInsert){
                if(oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            } else if(Trigger.isUpdate){
                //Check Update for dupe numbers
                if(Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c && oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            }
        }
    }
}

All Answers

ApuroopApuroop
Hey Bob,

I have made some significant changes but works in my developer org. Below is the code:
 
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    //Display error message if another opportunity has the same number in Quting_Priority__c field
    Set<decimal> oppSet = new Set<decimal>();
    for(Opportunity o : trigger.new){
        oppSet.add(o.Quting_Priority__c);
    }
    //query all existing record for quoteprioritynum__c
    List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
                                  Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
                                  FROM Opportunity 
                                  WHERE Quting_Priority__c in :oppSet AND 
                                  Owner.Id = :userinfo.getuserid()];
    
    //ignore system admins
    Profile pr = [select id from Profile where name='System Administrator'];
    
    for(Opportunity o:trigger.new){
        //Only check for priority size
        if(Trigger.isInsert){
            if(oppsList.size()>0){
                o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
            }
        } else if(Trigger.isUpdate){
            //Check Update for dupe numbers
            if(Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c && oppsList.size()>0){
                o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
            }
        }
    }
}

Try and let me know.
Ajay K DubediAjay K Dubedi
Hi Bob,
Try this code:
Trigger:
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    if((trigger.isInsert && trigger.isBefore) || (trigger.isUpdate && trigger.isBefore)) {
        TR_RejectDupPriority_handler.checkNumberField(trigger.new);
    }
}
Handler:
public class TR_RejectDupPriority_handler {
    public static void checkNumberField(List<Opportunity> oppList) {
        try {
            List<Opportunity> oldOppList = new List<Opportunity>();
            Map<Decimal, Opportunity> QutingPriorityVsOppMap = new Map<Decimal, Opportunity>();
            oldOppList = [SELECT Id, Quting_Priority__c FROM Opportunity WHERE Quting_Priority__c != null LIMIT 10000];
            if(oldOppList.size() > 0) {
                for(Opportunity op : oldOppList) {
                    if(!QutingPriorityVsOppMap.containsKey(op.Quting_Priority__c)) {
                        QutingPriorityVsOppMap.put(op.Quting_Priority__c, op);
                    }
                }
            }
            for(Opportunity o : oppList) {
                if(QutingPriorityVsOppMap.containsKey(o.Quting_Priority__c)) {
                    o.addError('Another quote has the same priority number, please enter a new number!');
                }
            }
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Bob_zBob_z
Thank you both for helping,

Ajay - I am getting errors in your code when i try to save the trigger.
Line 7:
Missing '<EOF>' at 'public'  

Line 3:
Variable does not exist: TR_RejectDupPriority_handler


Apuroop - Your code works but when i log in as another user and create an opportunity without a Quoting Priority Number and save it, then go back into the record and try to add a number it gives me the error message "Another quote has the same priority number, please enter a new number"   I'm working on this in my sandbox and  the user I'm logged in as does not have any other records with a blank priority field, so im not sure how the trigger is finding another record with a blank field? 
ApuroopApuroop
Hey Bob,

In first for loop, we really don't want the records with null values in Quting_Priority__c field. So I added an if statement there.
In the SOQL query on line 10, I removed the where clause for OwnerId, because we would want to deal with all the records in the database, I reckon.

Updated code:
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    //Display error message if another opportunity has the same number in Quting_Priority__c field
    Set<decimal> oppSet = new Set<decimal>();
    for(Opportunity o : trigger.new){
        if(o.Quting_Priority__c != null){
            oppSet.add(o.Quting_Priority__c);
        }
    }
    //query all existing record for quoteprioritynum__c
    List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
                                  Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
                                  FROM Opportunity 
                                  WHERE Quting_Priority__c in :oppSet];
    
    //ignore system admins
    Profile pr = [select id from Profile where name='System Administrator'];
    
    for(Opportunity o:trigger.new){
        //Only check for priority size
        if(Trigger.isInsert){
            if(oppsList.size()>0){
                o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
            }
        } else if(Trigger.isUpdate){
            //Check Update for dupe numbers
            if(Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c && oppsList.size()>0){
                o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
            }
        }
    }
}

Try and let me know. Unfortunately I can't test this in a sandbox. :(
Bob_zBob_z
Hi  Apuroop,

Thank you for your help. It mostly works, but how do i get this trigger to ignore certain profiles. A you can see i tried to accomplish this in my trigger, but when i'm logged as a system administrator the trigger still executes when i want to change the number in the Quote Priority field. I was hoping to have this trigger ignore any user with the system administrator profile. 
ApuroopApuroop
How about this?
 
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    
    //Display error message if another opportunity has the same number in Quting_Priority__c field
    Set<decimal> oppSet = new Set<decimal>();
    for(Opportunity o : trigger.new){
        if(o.Quting_Priority__c != null){
            oppSet.add(o.Quting_Priority__c);
        }
    }
    //query all existing record for quoteprioritynum__c
    List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
                                  Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
                                  FROM Opportunity 
                                  WHERE Quting_Priority__c in :oppSet];
    
    //ignore system admins
    Id sysadminId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
    User currentUser = [Select Id, ProfileId FROM User WHERE Id =: UserInfo.getUserId()];
    
    if(currentUser.ProfileId != sysadminId){
        for(Opportunity o:trigger.new){
            //Only check for priority size
            if(Trigger.isInsert){
                if(oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            } else if(Trigger.isUpdate){
                //Check Update for dupe numbers
                if(Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c && oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            }
        }
    }
}

 
Bob_zBob_z
Thanks I will do more testing tomorrow morning and mark your post if it works. Looks good so far. 
Bob_zBob_z
Good morning Apuroop,
 Iappreciate your help with this trigger. I did more testing this morning and the trigger doesnt appear to be working 100% correctly.

he trigger seems to be finding other opportunities owned by another user and finding their records with the same number. The screenshots below show a list of opportunities by a user that shows there is no number 2 in the list, but when i login as that user and try to create a new opportunity and enter the number 2 in the Quoting Priority field, it displays the error from the trigger.
User-added image 
User-added image

List from another user:
User-added image
 
ApuroopApuroop
A system admin can create opps with the same Quting_priority.
Other users can't add an opp with the same Quting_priority if a record already exists AND is created by him/her.

Try this:
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    
    //Display error message if another opportunity has the same number in Quting_Priority__c field
    Set<decimal> oppSet = new Set<decimal>();
    for(Opportunity o : trigger.new){
        if(o.Quting_Priority__c != null){
            oppSet.add(o.Quting_Priority__c);
        }
    }
    //query all existing record for quoteprioritynum__c
    List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
                                  Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
                                  FROM Opportunity 
                                  WHERE Quting_Priority__c in :oppSet AND OwnerId =: UserInfo.getUserId()];
    
    //ignore system admins
    Id sysadminId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
    User currentUser = [Select Id, ProfileId FROM User WHERE Id =: UserInfo.getUserId()];
    
    if(currentUser.ProfileId != sysadminId){
        for(Opportunity o:trigger.new){
            //Only check for priority size
            if(Trigger.isInsert){
                if(oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            } else if(Trigger.isUpdate){
                //Check Update for dupe numbers
                if(Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c && oppsList.size()>0){
                    o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
                }
            }
        }
    }
}
This was selected as the best answer
Bob_zBob_z
Thank you for your patience Apuroop! The trigger is working correctly!!