Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Learning How to Manage Records in Visualforc

Save for later
  • 7 min read
  • 14 Oct 2016

article-image

In this article by Keir Bowden, author of the book, Visualforce Development Cookbook - Second Edition we will cover the following styling fields and table columns as per requirement

One of the common use cases for Visualforce pages is to simplify, streamline, or enhance the management of sObject records.

In this article, we will use Visualforce to carry out some more advanced customization of the user interface—redrawing the form to change available picklist options, or capturing different information based on the user's selections.

(For more resources related to this topic, see here.)

Styling fields as required

Standard Visualforce input components, such as <apex:inputText />, can take an optional required attribute. If set to true, the component will be decorated with a red bar to indicate that it is required, and form submission will fail if a value has not been supplied, as shown in the following screenshot:

learning-how-manage-records-visualforc-img-0

In the scenario where one or more inputs are required and there are additional validation rules, for example, when one of either the Email or Phone fields is defined for a contact, this can lead to a drip feed of error messages to the user. This is because the inputs make repeated unsuccessful attempts to submit the form, each time getting slightly further in the process.

Now, we will create a Visualforce page that allows a user to create a contact record. The Last Name field is captured through a non-required input decorated with a red bar identical to that created for required inputs. When the user submits the form, the controller validates that the Last Name field is populated and that one of the Email or Phone fields is populated. If any of the validations fail, details of all errors are returned to the user.

Getting ready

This topic makes use of a controller extension so this must be created before the Visualforce page.

How to do it…

  1. Navigate to the Apex Classes setup page by clicking on Your Name | Setup | Develop | Apex Classes.
  2. Click on the New button.
  3. Paste the contents of the RequiredStylingExt.cls Apex class from the code downloaded into the Apex Class area.
  4. Click on the Save button.
  5. Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Visualforce Pages.
  6. Click on the New button.
  7. Enter RequiredStyling in the Label field.
  8. Accept the default RequiredStyling that is automatically generated for the Name field.
  9. Paste the contents of the RequiredStyling.page file from the code downloaded into the Visualforce Markup area and click on the Save button.
  10. Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Visualforce Pages.
  11. Locate the entry for the RequiredStyling page and click on the Security link.
  12. On the resulting page, select which profiles should have access and click on the Save button.

How it works…

Opening the following URL in your browser displays the RequiredStyling page to create a new contact record: https://<instance>/apex/RequiredStyling.

Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.

Clicking on the Save button without populating any of the fields results in the save failing with a number of errors:

learning-how-manage-records-visualforc-img-1

The Last Name field is constructed from a label and text input component rather than a standard input field, as an input field would enforce the required nature of the field and stop the submission of the form:

<apex:pageBlockSectionItem >
  <apex:outputLabel value="Last Name"/>
  <apex:outputPanel id="detailrequiredpanel" layout="block" 
      styleClass="requiredInput">
    <apex:outputPanel layout="block" styleClass="requiredBlock" />
    <apex:inputText value="{!Contact.LastName}"/>
  </apex:outputPanel>
</apex:pageBlockSectionItem>

The required styles are defined in the Visualforce page rather than relying on any existing Salesforce style classes to ensure that if Salesforce changes the names of its style classes, this does not break the page.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime

The controller extension save action method carries out validation of all fields and attaches error messages to the page for all validation failures:

if (String.IsBlank(cont.name))
{
  ApexPages.addMessage(new ApexPages.Message(
    ApexPages.Severity.ERROR, 
    'Please enter the contact name'));
  error=true;
}

if ( (String.IsBlank(cont.Email)) && 
              (String.IsBlank(cont.Phone)) )
{
  ApexPages.addMessage(new ApexPages.Message(
    ApexPages.Severity.ERROR, 
    'Please supply the email address or phone number'));
  error=true;
}

Styling table columns as required

When maintaining records that have required fields through a table, using regular input fields can end up with an unsightly collection of red bars striped across the table.

Now, we will create a Visualforce page to allow a user to create a number of contact records via a table. The contact Last Name column header will be marked as required, rather than the individual inputs.

Getting ready

This topic makes use of a custom controller, so this will need to be created before the Visualforce page.

How to do it…

  1. First, create the custom controller by navigating to the Apex Classes setup page by clicking on Your Name | Setup | Develop | Apex Classes.
  2. Click on the New button.
  3. Paste the contents of the RequiredColumnController.cls Apex class from the code downloaded into the Apex Class area.
  4. Click on the Save button.
  5. Next, create a Visualforce page by navigating to the Visualforce setup page by clicking on Your Name | Setup | Develop | Visualforce Pages.
  6. Click on the New button.
  7. Enter RequiredColumn in the Label field.
  8. Accept the default RequiredColumn that is automatically generated for the Name field.
  9. Paste the contents of the RequiredColumn.page file from the code downloaded into the Visualforce Markup area and click on the Save button.
  10. Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Visualforce Pages.
  11. Locate the entry for the RequiredColumn page and click on the Security link.
  12. On the resulting page, select which profiles should have access and click on the Save button.

How it works…

Opening the following URL in your browser displays the RequiredColumn page: https://<instance>/apex/RequiredColumn.

Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.

The Last Name column header is styled in red, indicating that this is a required field. Attempting to create a record where only First Name is specified results in an error message being displayed against the Last Name input for the particular row:

learning-how-manage-records-visualforc-img-2

The Visualforce page sets the required attribute on the inputField components in the Last Name column to false, which removes the red bar from the component:

<apex:column >
  <apex:facet name="header">
    <apex:outputText styleclass="requiredHeader" 
        value="{!$ObjectType.Contact.fields.LastName.label}" />
  </apex:facet>
  <apex:inputField value="{!contact.LastName}" required="false"/>
</apex:column>

The Visualforce page custom controller Save method checks if any of the fields in the row are populated, and if this is the case, it checks that the last name is present. If the last name is missing from any record, an error is added. If an error is added to any record, the save does not complete:

if ( (!String.IsBlank(cont.FirstName)) || 
  (!String.IsBlank(cont.LastName)) )
{
  // a field is defined - check for last name
  if (String.IsBlank(cont.LastName))
  {
    error=true;
    cont.LastName.addError('Please enter a value');
}

String.IsBlank() is used as this carries out three checks at once: to check that the supplied string is not null, it is not empty, and it does not only contain whitespace.

Summary

Thus in this article we successfully mastered the techniques to style fields and table columns as per the custom needs.

Resources for Article:


Further resources on this subject: