Wednesday, January 25, 2012

Simple Method to Identify Blank Fields in Visualforce

I've often wondered why there is no ISBLANK() equivalent in Apex for developers to use when validating a Visualforce page. Maybe Salesforce always intended for developers to use the required attribute for the standard Visualforce components.

The problem with relying on field settings, Visualforce required attributes or object validation rules is that there is no consistent presentation of the error messages. For different sites, especially public ones, sometimes the validation errors need to be tailored specifically for the site.

To help this process along, I modularized the concept of ISBLANK() in the simple instance method below.
/**
 * Determine whether a given object is blank
 * or not, in the same manner as the ISBLANK()
 * Visualforce function.
 *
 * @param  o The object to examine
 * @return   Whether the object is blank
 */
public Boolean isBlank(Object o) {
    return o == null;
}   // public Boolean isBlank(Object o)

With this simple method (or variations thereof), developers can iterate through a List<Schema.SObjectField> of required fields and use controller.isBlank(Object) to validate the fields.
for (Schema.SObjectField field : requiredFields) {

    if (isBlank(application.get(field))) {
        addRequiredFieldError(field);
        isValid = false;
    }   // if (isBlank(application.get(field)))
    
}   // for each Schema.SObjectField in requiredFields