Thursday, 3 February 2011

In my opinion, Apex page messages is one of the most useful and straightforward Salesforce development features available. When developing custom functionality inside Visualforce pages, we can leverage page messages to give a user direct feedback. We could inform them for example that an action has been successful, or explain why an error has occurred.

The controller code to create a new page message and add it to the current page:

To display the messages on the page is simply a case of using the apex:pageMessages tag, like so:

<apex:pageMessages/>

In the following example I have taken the majority of code from a previous blog post concerning creating a check-all checkbox on a data table. I have added apex messages in the previously empty perform action method to illustrate how they can be used. The following logic is applied in this method:

If no contacts are selected, an error message will be generated.

If all contacts are selected, a warning message will warn that the maximum amount of contacts have been selected.

In at least one contact has been selected, a confirmation message will be displayed, including a list of the selected contacts' names.

This is just a brief exploration of messages, but still shows how they can greatly improve the user experience. For more about messages, see the full apex page messages class definition, which includes the full enumeration of severity values. Also note that individual apex:pageMessage tags can be used to split up the messages to display at different points on the page and control their content directly on the page, should you so desire.