Groupios-folderShape

By Barkha Jain

 

While working on Visualforce (VF) pages, we generally make some fields required on the page using the Apex tag “<Apex:inputField>” as shown below:

<apex:inputField value=”{!Account.Name}”  required=”true” />

This works perfectly in most cases and is a great VF attribute. Unfortunately, the validations get fired on those fields with every Ajax call (i.e., every time we make a call to controller) on the page. So if there is requirement where the user should get a validation message only when they are actually submitting the form — and not when page is running some internal process — this required attribute does not fulfill the purpose. To accomplish such requirements, we can use custom required blocks.

Demo walkthrough…

Create a VF component to display the red bar before the input fields in the same way as it is displayed for standard required fields.

VF Component: RequiredBlock

<apex:component access=”global” id=”requiredblock”>

  <style>

      .requiredDiv{

      background-color:#c00;

             height: 17px;

             width: 3px;

             display: inline;

             position: absolute;

             margin-top: 2px;

      }

      input, select, textarea {

         margin-left:4px;

   }

  </style>

  <div class=”requiredDiv”></div>                                

</apex:component>

Implementation on VF page

Scenario #1 — single field implementation:

Static required field

<apex:pageBlockSectionItem>

<apex:outputLabel value=”Account Type” for=”typeField”/>

<apex:outputPanel id=”typeField”>

<c:RequiredBlock />

<apex:inputField value=”{!Account.Type}” />

<!– Field specific error message –>

                       <div class=”errorMsg” style=”display:{!IF(AND(isError, ISBLANK(Account.Type)), ‘block;’, ‘none;’)}”>

                       <strong>Error:</strong>&nbsp; You must enter this value.

                   </div>

</apex:outputPanel>

</apex:pageBlockSectionItem>

Scenario #2 — fieldset implementation. (Make your field required in the fieldset to make it show as required on your VF page.)

Apex logic

First, create a map to store field specific error messages (FieldLabel → ErrorMessage):

map<String, String> fieldErrors = new map<String, String>();

Next, create a method to validate data before save, when user submits the form:

// To check if all required fields are populated or not

   public void requiredFieldValidation(){

          isError = false;

          fieldErrors.clear();

      for (Schema.fieldsetMember f : Schema.Sobjecttype.Account.fieldsets.FIELD_SET_NAME.getFields()){

                 if(acc.get(f.getFieldPath()) == null){

         fieldErrors.put(f.getLabel(), ‘You must enter a value.’);

         isError = true;

             }

        }

        if(!isError){ //save your data }

   }

Then, create a delimited string of all field labels with errors to display on the page:

public String SEPARATOR = ‘~’;  

public String delimitedStrOfErrorKeys {get{

      List<String> errorFields = new List<String>(fieldErrors.keySet());

if(!errorFields.isEmpty())

      return SEPARATOR + string.join(errorLst, SEPARATOR) + SEPARATOR;

   }set;}

VF page

RequiredBlock for Dynamic fields

<apex:pageBlockSection title=”My Dynamic Section” columns=”2″ >

 <apex:repeat value=”{!$ObjectType.Account.FieldSets.Field_Set_Name}” var=”f”>

<apex:pageBlockSectionItem id=”sectionItem” >                                                   

   <apex:outputLabel value=”{! f.Label}” for=”fieldPanel”/>

   <apex:outputPanel id=”fieldPanel”>

         

          <!– required red bar –>

          <c:RequiredBlock rendered=”{! OR(f.Required, f.DBRequired)}” />

         

          <!– Input field –>

          <apex:inputField value=”{! Account[f]}” />

         

          <!– Field specific error message –>

          <div class=”errorMsg” style=”display:{!IF(CONTAINS(delimitedStrOfErrorKeys, SEPARATOR + f.Label + SEPARATOR), ‘block;’, ‘none;’)}”>

          <strong>Error:</strong>&nbsp; {! IF(CONTAINS(delimitedStrOfErrorKeys, SEPARATOR + f.Label + SEPARATOR), fieldErrors[f.Label], ”)}

          </div>

         

   </apex:outputPanel>             

</apex:pageBlockSectionItem>

 </apex:repeat>

</apex:pageBlockSection>

<apex:commandButton action=”{! requiredFieldValidation}” value=”Validate & Save” />

This implementation would give the user a custom “required field” functionality with the standard SFDC UI, along with all the validations handled at server side.

VFpage

 

Join the Conversation

Your email address will not be published. Required fields are marked *