Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I need to bulkify the trigger and error handler.Can someone point me if my trigger is bukified or not and handled error ?

 trigger KeyGenerator on Account (before insert,before update) {

    for(Account UpdatedAcc:Trigger.new)
    {
       if(UpdatedAcc.Key__c == null)
          {  

            String KeyStartWith = UpdatedAcc.Name.replace(' ','');
            KeyStartWith = KeyStartWith.toLowerCase();
            //Get the first 5 letter of Account Name
            if(KeyStartWith.length()<=5)
            {
             KeyStartWith=KeyStartWith.substring(0,KeyStartWith.length());
            }else
            {
                KeyStartWith=KeyStartWith.substring(0,5);
            }
            //Get the number generated randomly
            Double randomDouble=Math.random();
            //Crop the last five digits of this generated number
            String KeyEndWith=String.valueOf(randomDouble);
            KeyEndWith=KeyEndWith.substring(KeyEndWith.length()-5,KeyEndWith.length());

          try{
            UpdatedAcc.Key__c=KeyStartWith+KeyEndWith;
            }
           catch(Exception e){
            UpdatedAcc.addError('Failed to update Key');
           } 
          }  
     }
}
share|improve this question
    
possible duplicate of General trigger bulkification - best practices –  Christian Deckert Aug 21 at 18:20

1 Answer 1

up vote 3 down vote accepted

Yes, your trigger is bulkified in the sense that it handles SOQL queries and DML statements in a bulkified way (you don't have DML or SOQL). If the assignment of Key__c failed you will have working error handling - however If your other code fails you are not handling exceptions well.

What if Name is null for example - not sure it can happen - but if it can you would end up with an unhandled exception due to a null-pointer-exception on the replace call.

share|improve this answer
    
Name is standard field for all kind of objects and it is always required, but it can happend that it is an auto-number. From my point I can't see here any issue, try{} catch(){} block is most useful for DML operations, but in before triggers as this I don't see a point of using it. –  Artur Kępczyński Feb 11 at 5:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.