Saturday 28 September 2013

Using Custom Label With Trigger


I have seen many of the developer trying to set custom Error Message on Edit page Layout. So here we can do this using Custom Labels.

Custom Label
Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

The purpose of this post is that many time we got a condition to set an error message while writing an Trigger. So here the method to add custom error message on Edit PageLayout

First of all create an Custom Label
Go to
Home --> Setup --> Create --> Custom Labels

The red box or the "Value" field is the error message which is going to be seen by the user on the edit page.


After creating a Custom Label, create a Visualforce page as below which is having an error message

1:  <apex:page >  
2:     <apex:pageMessage severity="info" strength="1" summary="{!$Label.AccountTriggerErrorMessage}"/>  
3:  </apex:page>  

Now add a Trigger on Account Object as below, in this trigger we are adding an error message too.

1:  Trigger TriggerForCustomLabelAccount on Account (before insert, before update) {  
2:  //Check for Event  
3:  if(Trigger.isBefore) {  
4:  //Check for Event Type  
5:  if(Trigger.isInsert || Trigger.isUpdate) {  
6:  //Loop through Account  
7:  for(Account account : Trigger.New) {  
8:  //Check for Account Revenue  
9:  if(account.AnnualRevenue == Null)  
10:  //Here adding error message when condition matches  
11:  account.addError(label.AccountTriggerErrorMessage);  
12:  }  
13:  }  
14:  }  
15:  }  

Now After doing all this, Edit an Account record or create a new one, there will a custom error message on Edit page when condition satisfies.


May the force.com with you, happy coding !!



No comments:

Post a Comment