Friday, April 21, 2017

Display Validation rule Errors on a Visualforce Page

One among the most useful features in Salesforce is Validation rules in an object. With Validation rules, e can provide a formula / conditional check and if it met, we display an error message to end user and thus stopping user from saving the record.  The advantage of validation rules is that it validates records when entered in forms and also through other means like data loader. So, if there are any conditions which are mandatory, better to have them in Validation rules, even though you have custom forms.

A simple example in my application is, we can't allow users to provide weight less than 1 LBS. To accomplish this, we added a validation rule as below.

And, in our application, we are having Visualforce pages for the forms as we have some complex functionalities which can't be accomplished through default layouts.

In order to display errors on forms like mandatory field / invalid value , we simply need to provide a visualforce component / tag "<apex:pagemessages />" in the layout as per our design. By adding this, upon save of an object, if there are any errors in data, they are listed in pagemessages section.

But, Validation rules, don't come under default errors of a data record. They actually through DML Exceptions. So, in order to show the validation errors, in the Apex class save method, we need to catch the  DML exceptions and just provide the exception to Apexpage messages. It parses the error messages and displays them in page messages. Below is sample code.

public class customController
{
    public object__C obj {get;set;}
    
    public customController(ApexPages.StandardController ctlr)
    {
        //Consturctor, define obj here.
    }
    
    public pagereference custommSave()
    {
        try
        {
            upsert obj;
            return new pagereference('/'+obj.id);
        }         
        catch(DmlException ex){
            ApexPages.addMessages(ex);
            return null;
        }
        catch(Exception ex){
            //Handle exception
            return null;
        }
    }
}

Happy coding!