0

When I am updating records, this trigger is giving an error. I don't know what I am doing wrong.

trigger Triggeronsequencenumber on Tapose__c (before insert,before update) {

 if(trigger.Isinsert){
       for(Tapose__c  tap:trigger.new){
            List<Tapose__c> lst = [SELECT id, Sequence_No__c,RecordTypeID 
                                   FROM Tapose__c 
                                   WHERE Sequence_No__c =: tap.Sequence_No__c 
                                   AND RecordTypeID =:tap.RecordTypeID];
           if(lst.size()>0)
                  tap.Sequence_No__c.addError('Sequence Number is already exist, plz choose another number'); 
         }
   }


  if(trigger.Isupdate){
      for(Tapose__c  tap2:trigger.old){
              for(Tapose__c  tap:trigger.new){
                      List<Tapose__c> lst1 = [SELECT id, Sequence_No__c,RecordTypeID 
                                              FROM Tapose__c 
                                              WHERE Sequence_No__c =: tap.Sequence_No__c AND RecordTypeID =:tap.RecordTypeID];
                       if(lst1.size()>0)
                         tap2.Sequence_No__c.addError('Sequence Number is already exist, plz choose another number'); 
              }
        }
  }
}
2
  • In general, you should try to include error messages and try to make your code easy to read. That will help us help you! In this case, the trained eye can immediately see the error, see my answer. Feb 20, 2014 at 7:37
  • What specific error are you getting?
    – tggagne
    Feb 20, 2014 at 16:53

2 Answers 2

2

yo can't add error to tap2, which is trigger.old

add error to trigger.old only allow in delete triggers

2

Doing any database interaction within a loop(iteration) is a very bad idea. It is simply not efficient, and that is why salesforce will block you from doing so. A collection of governor limits exists to which you code needs to adhere, else you will get an exception.

The solution is to implement all your apex with bulkification patterns in mind. You'll find many examples, blogs and questions about this subject which you can learn from. Please investigate the subject and try to re-write your trigger and test code( it is recommended you test for bulk transactions!).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .