Wednesday, 22 January 2014

salesforce validation in trigger

Salesforce provides validation rules in configuration for standard as well as custom objects. Validation rule for standard object can be written by navigating to following:
set up --> customise --> standard object name --> validation rule

similarly for custom object you can write validation rule by navigating to following:
set up --> create --> objects --> click on the custom object --> scroll down and click on new(next to validation Rules)

Although, you can write validation using simple configuration, sometimes your requirements may not be fullfilled using validation rule especially when your validation criteria is bit complex or need querying in database to check previously created data. In such a case you can write your logic in trigger.

Lets write down a very basic trigger that will throw a validation errror message.

Scenario : Show error message on account if annual revenue is less than 2000.

The error message can be shown using adderror method as shown in the example below:

trigger validation_using_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       acc.adderror('Annual revenue cannot be less than 2000');
    }
 }
}



Above trigger will show error message at the top of the page. You can also display your message at a particular field, you only have to mention the field name in the adderror method as in the below example:

trigger validation_using_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       acc.AnnualRevenue.adderror('Annual revenue cannot be less than 2000');
    }
 }
}


Above triggers will also throw validation errors while inserting/updating records using data loader

While writing validation you have to make sure that your trigger is bulkified; that is you are properly iterating over for loop(trigger.new)

Also your trigger should run over before insert and before update contexts as you want the message be displayed before the record is created or updated. 

Also the adderror method should always be written in the trigger new context. Trigger will not show error message if you are iterating over some other collection which is not trigger.new

No comments:

Post a Comment