Saturday, November 5, 2011

JavaScript Hack to Render Red Bar for Required apex:selectList

I'm surprised that Salesforce doesn't support rendering apex:pageBlockSectionItem elements with the same red bar that identifies a required element.

All I wanted was for ...


... to look like ...


So, for consistency of developing a Visualforce page that has a consistent look-and-feel, I came up with a script snippet that seems to work to add the red bar to any apex:pageBlockSectionItem with the dataStyleClass set to "requiredData".

Here's the code:
/**
 * Add the Salesforce "required" appearance to an 
 * input cell.
 *
 * @param td The input cell to give a "required" 
 *           appearance.
 */
function addRequiredAppearance(td) {
    
    // Construct the wrapper div that goes inside 
    // the td.
    
    var requiredInputDiv = 
            document.createElement("div");

    requiredInputDiv.setAttribute(
            "class", "requiredInput");
    
    // Construct and append the div that renders 
    // as the red bar.
    
    var requiredBlockDiv = 
            document.createElement("div");

    requiredBlockDiv.setAttribute(
            "class", "requiredBlock");

    requiredInputDiv.appendChild(
            requiredBlockDiv);
    
    // Move each child from the td inside the 
    // wrapper div.
    
    while (td.firstChild) {
        requiredInputDiv.appendChild(
                td.removeChild(td.firstChild));
    }   // while (td.firstChild)
    
    // Append the wrapper div inside the td.
    
    td.appendChild(requiredInputDiv);
}   // function addRequiredAppearance(td)

// Iterate through every marked element to add 
// the required appearance.

jQuery(".requiredData").each(function (i) {
    addRequiredAppearance(this);
});

With the desired apex:pageBlockSectionItem elements marked, this code adds the red bar to compliment a Visualforce input element that has the required attribute set to "true".

As mentioned in the discussion thread, Salesforce may at any time change the way they render required fields. Since this was only tested in Winter '12, the hack may not work in a later release if applied as-is. However, the concept should still hold true, and as long as the function is modified appropriately all should be well.

Note: This hack uses the jQuery library for selecting marked elements.