+ Start a Discussion
Kiran MarketingKiran Marketing 

Not Allow One User to Enter Opportunities Worth more than 100K

I have a requirement where one of the user should not be alloowed to insert more than 100K opportunies however i am getting error when i am trying to accomplish the task with below code.

Error - Invalid Data.
Review all error messages below to correct your data.
Apex trigger OpportunityTrigger caused an unexpected exception, contact your administrator: OpportunityTrigger: execution of BeforeInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunityTrigger: maximum trigger depth exceeded Opportunity trigger event BeforeInsert for [new] Opportunity trigger event BeforeInsert for [new] Opportunity trigger event BeforeInsert for [new] Opportunity trigger event BeforeInsert for [new] Opportunity trigger event BeforeInsert for [new] O: []: Class.OpportunityTriggerHelperClass.isbeforeinsert: line 29, column 1
 
public class OpportunityTriggerHelperClass {
    
      Public Static Void isbeforeinsert(List<opportunity> OppList)
    {
     User CurrentUs =[Select name,username From User Where Username=:'kiranmarketing16-cltra@gmail.com']; 
String StruserName = CurrentUs.Username;
        List<Opportunity> InvalidOppList = New List<Opportunity>();
        List<Opportunity> validOppList = New List<Opportunity>();
        for(Opportunity Opp : OppList)
           {
              If(null!=StruserName && StruserName.equals('kiranmarketing16-cltra@gmail.com'))
              {
                               If(Opp.Amount > 1000)
                  {
                     InvalidOppList.add(new opportunity(Name=Opp.Name,CloseDate=Opp.CloseDate,
                                StageName=Opp.StageName, Amount=Opp.Amount) );
                      System.debug(InvalidoppList);
                      System.debug('This is true');
       Opp.Amount.addError('You have no previlages to add this opportunity because amount is greated that 100K');
                      }   
       validOppList.add(new opportunity(Name=Opp.Name,CloseDate=Opp.CloseDate,
                                        StageName=Opp.StageName, Amount=Opp.Amount));
            }
                  
             }  
               
      Insert ValidOpplist;

    }
  
}

 
Kiran MarketingKiran Marketing
Updated the code

New Error - Invalid Data.
Review all error messages below to correct your data.
Apex trigger OpportunityTrigger caused an unexpected exception, contact your administrator: OpportunityTrigger: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Class.OpportunityTriggerHelperClass.isbeforeinsert: line 27, column 1
 
public class OpportunityTriggerHelperClass {
    
      Public Static Void isbeforeinsert(List<opportunity> OppList)
    {
     User CurrentUs =[Select name,username From User Where Username=:'kiranmarketing16-cltra@gmail.com']; 
String StruserName = CurrentUs.Username;
        List<Opportunity> InvalidOppList = New List<Opportunity>();
        List<Opportunity> validOppList = New List<Opportunity>();
        for(Opportunity Opp : OppList)
           {
              If(null!=StruserName && StruserName.equals('kiranmarketing16-cltra@gmail.com'))
              {
                               If(Opp.Amount > 1000)
                  {
                     InvalidOppList.add(opp);
                      System.debug(InvalidoppList);
                      System.debug('This is true');
       Opp.Amount.addError('You have no previlages to add this opportunity because amount is greated that 100K');
                      }   
       validOppList.add(opp);
            }
                  
             
           }  
               
      Insert validOpplist;

    }
  
}

 
James WooleyJames Wooley
Why don't you do this via a validation rule on the Opportunity object?
 
AND(
     $User.Username = 'kiranmarketing16-cltra@gmail.com',
     Amount > 100000
)

Thanks,
James.
Kiran MarketingKiran Marketing
James

The entire requirement is more to this hence need to be done through an Apex Code in trigger. We used the validation rule earlier but due to some changes in requirment my lead suggested to write a triiger for this.

Regards
Kiran
James WooleyJames Wooley
There's a lot of issues with the code you have written
  1. You're not getting the running user to see if it is 'kiranmarketing16-cltra@gmail.com'. Do this using the UserInfo class.
  2. You're comparing the Opportuity amount to 1,000 but in your question you said 100,000
  3. Judging from your method name, this is being called before insert, but then you are inserting the records again, hence your error message for maximum depth reached. There is no need to insert again on a before insert trigger. I'd also suggest you need to think about updates as the user could just save the Opportunity then go in and change its value.
What is your full set of requirements?
Kiran MarketingKiran Marketing
James

I am truly sorry for my ameaturness i am just 3 months old in salesforce this is my first project indeed tried to answer your queries below.

1) I wanted to try with one user when it works then wanted to get the running user.
2) I could change the amount just used a random value to check if its working.

Trying this in my personal developer org first.

3) Yes i have called the trigger in before insert so you mean not to mention insert in 26th line if i dont then how would i differentiate whats the valid list of opportunities to be inserted. Like if the user is uploading opportunities through data loader in bulk then i should have the list of valid opportunities to be inserted right so i created that list. Once i disable that insert and validopplist its actually working fine, however i wanted to bulkyfy the code and capture valipopplist if for future requirement.

First want to get this right for Insert then i will work on Update and other senarios.

Truly appreciate your help. And sorry for being amature as i am confused about the error.

Regards
Rahul
SIVASASNKARSIVASASNKAR
Hi Kiran,

You can't do the DML operations on trigger.new as the before triggers will automaticaly save the record to database. you just remove the below code on your code . 
//Insert validOpplist; //Not required
public class OpportunityTriggerHelperClass {
    
      Public Static Void isbeforeinsert(List<opportunity> OppList)
    {
     User CurrentUs =[Select name,username From User Where Username=:'kiranmarketing16-cltra@gmail.com']; 
String StruserName = CurrentUs.Username;
        List<Opportunity> InvalidOppList = New List<Opportunity>();
        List<Opportunity> validOppList = New List<Opportunity>();
        for(Opportunity Opp : OppList)
           {
              If(null!=StruserName && StruserName.equals('kiranmarketing16-cltra@gmail.com'))
              {
                               If(Opp.Amount > 1000)
                  {
                     InvalidOppList.add(opp);
                      System.debug(InvalidoppList);
                      System.debug('This is true');
       Opp.Amount.addError('You have no previlages to add this opportunity because amount is greated that 100K');
                      }   
       validOppList.add(opp);
            }
                  
             
           }  
               
      //Insert validOpplist;

    }
  
}


DML operations are not suggested in before operations.
Kiran MarketingKiran Marketing
Thanks James and SIVASASNKAR

So whenever we write a before trigger it automatically saves in the object is that what i was missing.

 
James WooleyJames Wooley
public class OpportunityTriggerHelperClass {
    
    Public Static Void isbeforeinsert(List<opportunity> OppList) {
        for(Opportunity Opp : OppList) {
            if(UserInfo.getUserName() == 'kiranmarketing16-cltra@gmail.com' && Opp.Amount > 100000) {
                Opp.Amount.addError('You have no privileges to add this opportunity because amount is greater that 100K');
            }   
        } 
    }  
}
The above code is all you need for this requirement. Adding an error to a record will prevent it from inserting. This code will work in the exact same way as the validation rule I provided earlier.

I'd suggest using this as your starting point for the rest of your requirements.