JBoss.orgCommunity Documentation

Component Reference

A reference guide to the components of the RichFaces (draft) framework

Logo

Abstract

This book details each component in the RichFaces framework, including examples of their use in applications.


1. Introduction
1.1. Libraries
2. Common Ajax attributes
2.1. Rendering
2.1.1. render
2.1.2. ajaxRendered
2.1.3. limitRender
2.2. Queuing and traffic control
2.2.1. queue
2.2.2. requestDelay
2.2.3. ignoreDupResponses
2.3. Data processing
2.3.1. execute
2.3.2. immediate
2.3.3. bypassUpdates
2.4. Action and navigation
2.4.1. action
2.4.2. actionListener
2.5. Events and JavaScript interactions
2.5.1. onsubmit
2.5.2. onbegin
2.5.3. onclick
2.5.4. onsuccess
2.5.5. oncomplete
2.5.6. onerror
2.5.7. data
3. Common features
3.1. Positioning and appearance of components
3.2. Calling available JavaScript methods
I. a4j tag library
4. Actions
4.1. <a4j:actionParam>
4.2. <a4j:ajaxListener>
4.3. <a4j:commandButton>
4.4. <a4j:commandLink>
4.5. <rich:componentControl>
4.6. <a4j:hashParam>
4.7. <a4j:htmlCommandLink>
4.8. <a4j:jsFunction>
4.9. <a4j:poll>
4.10. <a4j:push>
4.11. <a4j:repeat>
4.12. <a4j:ajax>
5. Resources
5.1. <a4j:loadBundle>
5.2. <a4j:loadScript>
5.3. <a4j:loadStyle>
5.4. <a4j:keepAlive>
5.5. <a4j:mediaOutput>
6. Containers
6.1. <a4j:form>
6.2. <a4j:include>
6.3. <a4j:outputPanel>
6.4. <a4j:page>
6.5. <a4j:region>
7. Validation
7.1. <rich:ajaxValidator>
7.2. <rich:beanValidator>
7.3. <rich:graphValidator>
8. Processing management
8.1. <a4j:queue>
8.2. <a4j:log>
8.3. <a4j:status>
II. rich tag library
9. Tables and grids
9.1. <rich:column>
9.2. <rich:columnGroup>
9.3. <rich:columns>
9.4. <rich:dataDefinitionList>
9.5. <rich:dataFilterSlider>
9.6. <rich:dataGrid>
9.7. <rich:dataList>
9.8. <rich:dataOrderedList>
9.9. <rich:dataTable>
9.10. <rich:extendedDataTable>
9.11. Table filtering
9.12. Table sorting
10. Functions
10.1. rich:clientId
10.2. rich:component
10.3. rich:element
10.4. rich:findComponent
10.5. rich:isUserInRole

The Ajax components in the a4j library share common attributes to perform similar functionality. Most RichFaces components in the rich library that feature built-in Ajax support share these common attributes as well.

Most attributes have default values, so they need not be explicitly set for the component to function in its default state. These attributes can be altered to customize the behavior of the component if necessary.

The render attribute provides a reference to one or more areas on the page that need updating after an Ajax interaction. It uses the UIComponent.findComponent() algorithm to find the components in the component tree using their id attributes as a reference. Components can be referenced by their id attribute alone, or by a hierarchy of components' id attributes to make locating components more efficient. Example 2.1, “render example” shows both ways of referencing components. Each command button will correctly render the referenced panel grids, but the second button locates the references more efficiently with explicit hierarchy paths.


The value of the render attribute can also be an expression written using JavaServer Faces' Expression Language (EL); this can either be a Set, Collection, Array, or String.

rendered attributes

A common problem with using render occurs when the referenced component has a rendered attribute. JSF does not mark the place in the browser's Document Object Model (DOM) where the rendered component would be placed in case the rendered attribute returns false. As such, when RichFaces sends the render code to the client, the page does not update as the place for the update is not known.

To work around this issue, wrap the component to be rendered in an <a4j:outputPanel> with layout="none". The <a4j:outputPanel> will receive the update and render the component as required.

RichFaces allows for Ajax-enabled JSF applications to be developed without using any additional JavaScript code. However it is still possible to invoke custom JavaScript code through Ajax events.

This chapter covers those attributes and features that are common to many of the components in the tag libraries.

This chapter details the basic components that respond to a user action and submit an Ajax request.

The <a4j:actionParam> behavior combines the functionality of the JavaServer Faces (JSF) components <f:param> and <f:actionListener>.

Basic usage of the <a4j:actionParam> requires three main attributes:

Example 4.1, “<a4j:actionParam> example” shows a simple implementation along with the accompanying managed bean. When the Set name to Alex button is pressed, the application sets the name parameter of the bean to Alex, and displays the name in the output field.


The <a4j:actionParam> behavior can be used with non-Ajax components in addition to Ajax components. In this way, data model values can be updated without an JavaScript code on the server side.

The converter attribute can be used to specify how to convert the value before it is submitted to the data model. The property is assigned the new value during the Update Model phase.

Validation failure

If the validation of the form fails, the Update Model phase will be skipped and the property will not be updated.

Variables from JavaScript functions can be used for the value attribute. In such an implementation, the noEscape attribute should be set to true. Using noEscape="true", the value attribute can contain any JavaScript expression or JavaScript function invocation, and the result will be sent to the server as the value attribute.

Figure 4.1. <a4j:commandButton>


The <a4j:commandButton> is similar to the JavaServer Faces (JSF) component <h:commandButton>, but additionally includes Ajax support. When the command button is clicked it generates an Ajax form submit, and when a response is received the command button can be dynamically rendered.

The <a4j:commandButton> requires only the value and render attributes to function. The value attribute specifies the text of the button and the render attribute specifies which areas are to be updated. The <a4j:commandButton> uses the onclick event instead of the onsubmit event, but otherwise uses all common Ajax attributes as listed in Chapter 2, Common Ajax attributes.

Set disabledDefault="true"

When attaching a JavaScript function to a <a4j:commandButton> with the help of a <rich:componentControl>, do not use the attachTo attribute of <rich:componentControl>. The attribute adds event handlers using Event.observe but <a4j:commandButton> does not include this event.

Figure 4.2. <a4j:commandLink>


The <a4j:commandLink> is similar to the JavaServer Faces (JSF) component <h:commandLink>, but additionally includes Ajax support. When the command link is clicked it generates an Ajax form submit, and when a response is received the command link can be dynamically rendered.

The <a4j:commandLink> requires only the value and render attributes to function. The value attribute specifies the text of the link and the render attribute specifies which areas are to be updated. The <a4j:commandLink> uses the onclick event instead of the onsubmit event, but otherwise uses all common Ajax attributes as listed in Chapter 2, Common Ajax attributes.

The following reference data is taken from the old <rich:componentControl> reference. The details may be different now that the component is part of the a4j tag library.

The <rich:componentControl> allows JavaScript API functions to be called on components after defined events. Initialization variants and activation events can be customized, and parameters can be passed to the target component.

The event, for, and operation attributes are all that is required to attach JavaScript functions to the parent component. The event attribute specifies the event that triggers the JavaScript API function call. The for attribute defines the target component, and the operation attribute specifies the JavaScript function to perform.


The attachTo attribute can be used to attach the event to a component other than the parent component. If no attachTo attribute is supplied, the <rich:componentControl> component's parent is used, as in Example 4.2, “rich:componentControl basic usage”.


The operation can receive parameters either through the params attribute, or by using <f:param> elements.


The name attribute can be used to define a normal JavaScript function that triggers the specified operation on the target component.

The attachTiming attribute can determine the page loading phase during which the <rich:componentControl> is attached to the source component:

immediate

attached during execution of the script.

onavailable

attached after the target component is initialized.

onload

attached after the page is loaded.

The <a4j:jsFunction> component allows Ajax requests to be performed directly from JavaScript code, and server-side data to be invoked and returned in JavaScript Object Notation (JSON) format to use in client-side JavaScript calls.

The <a4j:jsFunction> component has all the common Ajax action attributes as listed in Chapter 2, Common Ajax attributes; the action and actionListener attributes can be invoked and parts of the page can be re-rendered after a successful call to the JavaScript function. Example 4.5, “<a4j:jsFunction> example” shows how an Ajax request can be initiated from the JavaScript and a partial page update performed. The JavaScript function can be invoked with the data returned by the Ajax response.


The <a4j:jsFunction> component allows the use of the <a4j:actionParam> component or the JavaServer Faces <f:param> component to pass any number of parameters for the JavaScript function.

The <a4j:jsFunction> component is similar to the <a4j:commandButton> component, but it can be activated from the JavaScript code. This allows some server-side functionality to be invoked and the returned data to subsequently be used in a JavaScript function invoked by the oncomplete event attribute. In this way, the <a4j:jsFunction> component can be used instead of the <a4j:commandButton> component.

REVIEW COMMENT - a4j:repeat is not an action, should be moved. The <a4j:repeat> component is used to iterate changes through a repeated collection of components. It allows specific rows of items to be updated without sending Ajax requests for the entire collection. The <a4j:repeat> component forms the basis for many of the tabular components detailed in Chapter 9, Tables and grids.

The contents of the collection are determined using Expression Language (EL). The data model for the contents is specified with the value attribute. The var attribute names the object to use when iterating through the collection. This object is then referenced in the relevant child components. After an Ajax request, only the rows specified with the ajaxKeys attribute are updated rather than the entire collection. Example 4.6, “<a4j:repeat> example” shows how to use <a4j:repeat> to maintain a simple table.


The <a4j:repeat> component uses other attributes common to iteration components, such as the first attribute for specifying the first item for iteration, and the rows attribute for specifying the number of rows of items to display.

This chapter covers those components used to handle and manage resources and beans.

The <a4j:loadBundle> component is used to load resource bundles to aid in localization of an application. The bundles are localized to the locale of the current view, and properties are stored as a map in the current request attributes.

The <a4j:loadBundle> component allows bundles to be accessed by Ajax requests working in their own address scopes. This solves the problem of using the JSF <h:loadBundle> component with Ajax, where bundle information loaded with the page was unavailable for later Ajax requests.

Resource bundles are registered in the Faces configuration file, faces-config.xml.

Example 5.1. <a4j:loadBundle> example

This example shows a simple application capable of switching between different localized languages.

  1. Create resource bundles

    String resource bundles are contained in files with a .properties extension. The files consist of a list of entries, each with a unique name and a corresponding value. A seperate file is required for each language. Append the filename with the locale identifier (en for English, for example).

  2. Register bundles in Faces configuration file

    The resource bundles need to be registered in the Faces configuration file, faces-config.xml. The filename is defined with the <message-bundle> tag, without the locale code and without the extension. The supported locale codes are listed with <supported-locale> tags.

    
    
    <application>
        <locale-config>
            <default-locale>en</default-locale>
            <supported-locale>en</supported-locale>
            <supported-locale>de</supported-locale>
            <supported-locale>it</supported-locale>
        </locale-config>
        <message-bundle>demo.message</message-bundle>
    </application>

  3. Create method to set locale

    The JSF javax.faces.component.UIViewRoot.setLocale() method can be used to update the locale through a Java class:

    
    
    package demo;
    import java.util.Locale;
    import javax.faces.context.FacesContext;
    public class ChangeLocale {
        public String germanAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.GERMAN);
            return null;
        }
        public String englishAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.ENGLISH);
            return null;
        } 
        public String italianAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.ITALIAN);
            return null;
        }
    }
  4. Add <a4j:loadBundle> to the JSP page

    The <a4j:loadBundle> component is added to the application, and links to change the locale will update the displayed text.

    
    
    <h:form>
        <a4j:loadBundle var="msg" basename="demo.message"/>
        <h:outputText id="messageBundle" value="#{msg.greeting}"/>
        <a4j:commandLink value="De" action="#{changeLocale.germanAction}" reRender="messageBundle" />
        <a4j:commandLink value="Eng" action="#{changeLocale.englishAction}" reRender="messageBundle" />
        <a4j:commandLink value="It" action="#{changeLocale.italianAction}" reRender="messageBundle" />
    </h:form> 


Clicking on the different links will render the localized string as appropriate.


The <a4j:mediaOutput> component is used for generating images, video, sounds, and other resources defined on the fly.

The createContent attribute points to the method used for generating the displayed content. If necessary, the value attribute can be used to pass input data to the content generation method specified with createContent. The cacheable attribute specifies whether the resulting content will be cached or not.

The mimeType attribute describes the type of output content, and corresponds to the type in the header of the HTTP request. The element attribute defines XHTML element used to display the content:

Example 5.5. <a4j:mediaOutput> example

This example uses the <a4j:mediaOutput> component to generate a JPEG image of verification digits. The code on the application page is a single element:



<a4j:mediaOutput element="img" cacheable="false" session="false" createContent="#{mediaBean.paint}" value="#{mediaData}" mimeType="image/jpeg" />

The <a4j:mediaOutput> component uses the MediaBean.paint method to create the image. The method generates a random number, which is then converted into an output stream and rendered to a JPEG image. The MediaBean class is as follows:



package demo;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class MediaBean {
    public void paint(OutputStream out, Object data) throws IOException {
        Integer high = 9999;
        Integer low = 1000;
        Random generator = new Random();
        Integer digits = generator.nextInt(high - low + 1) + low;
        if (data instanceof MediaData) {            
            MediaData paintData = (MediaData) data;
            BufferedImage img = new BufferedImage(paintData.getWidth(),paintData.getHeight(),BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = img.createGraphics();
            graphics2D.setBackground(paintData.getBackground());
            graphics2D.setColor(paintData.getDrawColor());
            graphics2D.clearRect(0,0,paintData.getWidth(),paintData.getHeight());
            graphics2D.setFont(paintData.getFont());
            graphics2D.drawString(digits.toString(), 20, 35);
            ImageIO.write(img,"png",out);
        }
    }
}

Another class, MediaData is required by the value attribute for keeping data to be used as input for the content creation method. The MediaData class is as follows:



package demo;
import java.awt.Color;
import java.awt.Font;
import java.io.Serializable;
public class MediaData implements Serializable {
    private static final long serialVersionUID = 1L;
    Integer Width=110;
    Integer Height=50;
    Color Background=new Color(190, 214, 248);
    Color DrawColor=new Color(0,0,0);
    Font font = new Font("Serif", Font.TRUETYPE_FONT, 30);
    /* Corresponding getters and setters */
    ...
}

The <a4j:mediaOutput> component uses the MediaBean and MediaData classes to generate a new image on each page refresh, which appears as shown in Figure 5.1, “<a4j:mediaOutput> example result”

Figure 5.1. <a4j:mediaOutput> example result



Serializable interface

A bean class passed using the value attribute of <a4j:mediaOutput> should implement the Serializable interface so that it will be encoded to the URL of the resource.

This chapter details those components in the a4j tag library which define an area used as a container or wrapper for other components.

The <a4j:include> component allows one view to be included as part of another page. This is useful for applications where multiple views might appear on the one page, with navigation between the views. Views can use partial page navigation in Ajax mode, or standard JSF navigation for navigation between views.

The viewId attribute is required to reference the resource that will be included as a view on the page. It uses a full context-relative path to point to the resource, similar to the paths used for the <from-view-id> and <to-view-id> tags in the faces-config.xml JSF navigation rules.

Example 6.1. A wizard using <a4j:include>

The page uses <a4j:include> to include the first step of the wizard:



<h:panelGrid width="100%" columns="2">
    <a4j:keepAlive beanName="profile" />
    <rich:panel>
        <f:facet name="header">
        <h:outputText value="A wizard using a4j:include" />
        </f:facet>
        <h:form>
            <a4j:include viewId="/richfaces/include/examples/wstep1.xhtml" />
        </h:form>
    </rich:panel>
</h:panelGrid>

The first step is fully contained in a separate file, wstep1.xhtml. Subsequent steps are set up similarly with additional Previous buttons.



<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich">
    
    <div style="position:relative;height:140px">
        <h:panelGrid rowClasses="s1row" columns="3" columnClasses="wfcol1,wfcol2,wfcol3">
            <h:outputText value="First Name:" />
            <h:inputText id="fn" value="#{profile.firstName}" label="First Name" required="true" />
            <rich:message  for="fn" />
            
            <h:outputText value="Last Name:" />
            <h:inputText  id="ln" value="#{profile.lastName}"  label="Last Name"  required="true" />
            <rich:message  for="ln" />
        </h:panelGrid>
        <div class="navPanel" style="width:100%;">
            <a4j:commandButton style="float:right" action="next" value="Next &gt;&gt;"/>
        </div>
    </div>
</ui:composition>

The navigation is defined in the faces-config.xml configuration file:



<navigation-rule> 
   <from-view-id>/richfaces/include/examples/wstep1.xhtml</from-view-id> 
   <navigation-case> 
      <from-outcome>next</from-outcome> 
      <to-view-id>/richfaces/include/examples/wstep2.xhtml</to-view-id> 
   </navigation-case> 
</navigation-rule>  
<navigation-rule> 
   <from-view-id>/richfaces/include/examples/wstep2.xhtml</from-view-id> 
   <navigation-case> 
      <from-outcome>previous</from-outcome> 
      <to-view-id>/richfaces/include/examples/wstep1.xhtml</to-view-id> 
   </navigation-case> 
   <navigation-case> 
      <from-outcome>next</from-outcome> 
      <to-view-id>/richfaces/include/examples/finalStep.xhtml</to-view-id> 
   </navigation-case> 
</navigation-rule>  
<navigation-rule> 
   <from-view-id>/richfaces/include/examples/finalStep.xhtml</from-view-id> 
   <navigation-case> 
      <from-outcome>previous</from-outcome> 
      <to-view-id>/richfaces/include/examples/wstep2.xhtml</to-view-id> 
   </navigation-case> 
</navigation-rule> 


The <a4j:page> component encodes a full HTML-page structure using only one tag. It renders complete <!DOCTYPE>, <html>, <head>, <title>, and <body> tags using the specified attributes and facets. Additionally, the <a4j:page> component solves an incompatibility issue between early versions of MyFaces and the Ajax4jsf framework.

The pageTitle attribute is rendered as a <title> element. The component uses the head facet to define the contents of the HTML <head> element. The format facet defines the page layout format for encoding the <!DOCTYPE> element. There rest of the contents of the <a4j:page> component are rendered as part of the <body> element.


When using the Ajax4jsf framework with MyFaces version 1.2.2 and lower, the <f:view> JSP tag does not receive control for encoding contents during the RENDER_RESPONSE phase. As a result, Ajax fails to receive control and send responses. The <a4j:page> component solves this problem by wrapping the Ajax areas to be updated. Later versions of MyFaces do not have this problem, and as such do not require the use of the <a4j:page> component.

This chapter covers those components that validate user input. The components enhance JSF validation capabilities with Ajax support and the use of Hibernate validators.

The <rich:ajaxValidator> component provides Ajax validation for JSF inputs. It is added as a child component to a JSF tag, and the event attribute specifies when to trigger the validation.


The <rich:ajaxValidator> component can also work with custom validators made using the JSF Validation API in the javax.faces.validator package, or with Hibernate Validator. Refer to the Hibernate Validator documentation for details on how to use Hibernate Validator.

Example 7.2. Using <rich:ajaxValidator> with Hibernate Validator

This example shows the use of <rich:ajaxValidator> with Hibernate Validator. It validates the entered name, email, and age.



<h:form id="ajaxValidatorForm2">
    <rich:panel>
        <f:facet name="header">
            <h:outputText value="User Info:" />
        </f:facet>
        <h:panelGrid  columns="3">
            <h:outputText value="Name:" />
            <h:inputText value="#{validationBean.name}" id="name" required="true">
                <rich:ajaxValidator event="onblur" />
            </h:inputText>
            <rich:message for="name" />
            <h:outputText value="Email:" />
            <h:inputText value="#{validationBean.email}" id="email">
                <rich:ajaxValidator event="onblur" />
            </h:inputText>
            <rich:message for="email" />
            <h:outputText value="Age:" />
            <h:inputText value="#{validationBean.age}" id="age">
                <rich:ajaxValidator event="onblur" />
            </h:inputText>
            <rich:message for="age" />
        </h:panelGrid>
    </rich:panel>
</h:form>

The validation is performed using the ValidationBean class:



package org.richfaces.demo.validation;
import org.hibernate.validator.Email;
import org.hibernate.validator.Length;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import org.hibernate.validator.Pattern;
public class ValidationBean {
    private String progressString="Fill the form in";
    
    @NotEmpty
    @Pattern(regex=".*[^\\s].*", message="This string contains only spaces")
    @Length(min=3,max=12)
    private String name;
    @Email
    @NotEmpty
    private String email;
    
    @NotNull
    @Min(18)
    @Max(100)
    private Integer age;
    
    public ValidationBean() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void success() {
        setProgressString(getProgressString() + "(Stored successfully)");
    }
    public String getProgressString() {
        return progressString;
    }
    public void setProgressString(String progressString) {
        this.progressString = progressString;
    }
}

Figure 7.1. <rich:ajaxValidator> example result



The <rich:beanValidator> component provides model-based constraints using Hibernate Validator. This allows Hibernate Validator to be used similar to its use with Seam-based applications.

The summary attribute is used for displaying messages about validation errors.

Example 7.3. <rich:beanValidator> example

This example shows the bean-based validation of a simple form, containing the user's name, email, and age. The <rich:beanValidator> component is defined in the same way as for JSF validators.



<h:form id="beanValidatorForm">
    <rich:panel>
        <f:facet name="header">
            <h:outputText value="#{validationBean.progressString}" id="progress"/>
        </f:facet>
        <h:panelGrid columns="3">
            <h:outputText value="Name:" />
            <h:inputText value="#{validationBean.name}" id="name">
                <rich:beanValidator summary="Invalid name"/>
            </h:inputText>
            <rich:message for="name" />
            <h:outputText value="Email:" />
            <h:inputText value="#{validationBean.email}" id="email">
                <rich:beanValidator summary="Invalid email"/>
            </h:inputText>
            <rich:message for="email" />
            <h:outputText value="Age:" />
            <h:inputText value="#{validationBean.age}" id="age">
                <rich:beanValidator summary="Wrong age"/>
            </h:inputText>
            <rich:message for="age" />
            <f:facet name="footer">
                <a4j:commandButton value="Submit" action="#{validationBean.success}" reRender="progress"/>
            </f:facet>
        </h:panelGrid>
    </rich:panel>
</h:form>

The accompanying bean contains the validation data:



package org.richfaces.demo.validation;
import org.hibernate.validator.Email;
import org.hibernate.validator.Length;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import org.hibernate.validator.Pattern;
public class ValidationBean {
    private String progressString="Fill the form in";
    
    @NotEmpty
    @Pattern(regex=".*[^\\s].*", message="This string contains only spaces")
    @Length(min=3,max=12)
    private String name;
    @Email
    @NotEmpty
    private String email;
    
    @NotNull
    @Min(18)
    @Max(100)
    private Integer age;
    
    public ValidationBean() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void success() {
        setProgressString(getProgressString() + "(Stored successfully)");
    }
    public String getProgressString() {
        return progressString;
    }
    public void setProgressString(String progressString) {
        this.progressString = progressString;
    }
}

Figure 7.2. <rich:beanValidator> example result



The <rich:graphValidator> component is used to wrap a group of input components for overall validation with Hibernate Validators. This is different from the <rich:beanValidator> component, which is used as a child element to individual input components.

The summary attribute is used for displaying messages about validation errors.

Example 7.4. <rich:graphValidator> example

This example shows the validation of a simple form, containing the user's name, email, and age. The <rich:graphValidator> component wraps the input components to validate them together.



<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich">

    <h:form id="graphValidatorForm">
        <a4j:region renderRegionOnly="true">
            <rich:panel id="panel">
                <f:facet name="header">
                    <h:outputText value="User Info:" />
                </f:facet>
                <rich:graphValidator summary="Invalid values: ">
                    <h:panelGrid columns="3">
                        <h:outputText value="Name:" />
                        <h:inputText value="#{validationBean.name}" id="name">
                            <f:validateLength minimum="2" />
                        </h:inputText>
                        <rich:message for="name" />
                        <h:outputText value="Email:" />
                        <h:inputText value="#{validationBean.email}" id="email" />
                        <rich:message for="email" />
                        <h:outputText value="Age:" />
                        <h:inputText value="#{validationBean.age}" id="age" />
                        <rich:message for="age" />
                    </h:panelGrid>
                </rich:graphValidator>
                <a4j:commandButton value="Store changes" />
            </rich:panel>
        </a4j:region>
    </h:form>
</ui:composition>

The accompanying bean contains the validation data:



package org.richfaces.demo.validation;
import org.hibernate.validator.Email;
import org.hibernate.validator.Length;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import org.hibernate.validator.Pattern;
public class ValidationBean {
    private String progressString="Fill the form in";
    
    @NotEmpty
    @Pattern(regex=".*[^\\s].*", message="This string contains only spaces")
    @Length(min=3,max=12)
    private String name;
    @Email
    @NotEmpty
    private String email;
    
    @NotNull
    @Min(18)
    @Max(100)
    private Integer age;
    
    public ValidationBean() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void success() {
        setProgressString(getProgressString() + "(Stored successfully)");
    }
    public String getProgressString() {
        return progressString;
    }
    public void setProgressString(String progressString) {
        this.progressString = progressString;
    }
}

Figure 7.3. <rich:graphValidator> example result



The optional value attribute can be used to define a value bound to the bean. The bean properties are then validated again after the model has been updated.

Example 7.5. Using the value attribute



<h:form id="graphValidatorForm2">
    <a4j:region renderRegionOnly="true">
        <rich:graphValidator summary="Invalid values: " value="#{dayStatistics}">
            <table>
                <thead>
                    <tr>
                        <th>Activity</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody>
                    <a4j:repeat value="#{dayStatistics.dayPasstimes}" var="pt"
                        id="table">
                        <tr>
                            <td align="center" width="100px"><h:outputText
                                value="#{pt.title}" /></td>
                            <td align="center" width="100px"><rich:inputNumberSpinner
                                minValue="0" maxValue="24" value="#{pt.time}" id="time">
                            </rich:inputNumberSpinner></td>
                            <td><rich:message for="time" /></td>
                        </tr>
                    </a4j:repeat>
                </tbody>
            </table>
        </rich:graphValidator>
        <a4j:commandButton value="Store my details"
            actionListener="#{dayStatistics.store}" reRender="panel" />
        <rich:messages infoClass="green" errorClass="red" />
    </a4j:region>
</h:form>

Figure 7.4. Result from using the value attribute



This chapter covers those components that manage the processing of information, requests, and updates.

The <a4j:queue> component manages a queue of Ajax requests to control message processing.

The queue can be disabled by setting the disabled attribute to true. The size attribute specifies the number of requests that can be stored in the queue at a time; smaller queue sizes help prevent server overloads. When the queue's size is exceeded, the sizeExceededBehavior determines the way in which the queue handles the requests:

The <a4j:queue> component features several events relating to queuing actions:

The <a4j:status> component displays the status of current Ajax requests; the status can be either in progress or complete.

The startText attribute defines the text shown after the request has been started and is currently in progress. This text can be styled with the startStyle and startStyleClass attributes. Similarly, the stopText attribute defines the text shown once the request is complete, and text is styled with the stopStyle and stopStyleClass attributes. Alternatively, the text styles can be customized using facets, with the facet name set to either start or stop as required. If the stopText attribute is not defined, and no facet exists for the stopped state, the status is simply not shown; in this way only the progress of the request is displayed to the user.


The <a4j:status> component works for each Ajax component inside the local region. If no region is defined, every request made on the page will activate the <a4j:status> component. Alternatively, the <a4j:status> component can be linked to specific components in one of two ways:

  • The for attribute can be used to specify the component for which the status is to be monitored.

  • With an id identifier attribute specified for the <a4j:status>, individual components can have their statuses monitored by referencing the identifier with their own status attributes.

Example 8.3. Updating a common <a4j:status> component



<a4j:region id="extr">
    <h:form>
        <h:outputText value="Status:" />
        <a4j:status id="commonstatus" startText="In Progress...." stopText="" />

        <a4j:region id="intr">
            <h:panelGrid columns="2">
                <h:outputText value="Name" />
                <h:inputText id="name" value="#{userBean.name}">
                    <a4j:support event="onkeyup" reRender="out" status="commonstatus" />
                </h:inputText>

                <h:outputText value="Job" />
                <h:inputText id="job" value="#{userBean.job}">
                    <a4j:support event="onkeyup" reRender="out" status="commonstatus" />
                </h:inputText>

                <h:panelGroup /> 

            </h:panelGrid>
        </a4j:region>
        <a4j:region>
            <br />
            <rich:spacer height="5" />
            <b><h:outputText id="out"
                value="Name: #{userBean.name}, Job: #{userBean.job}" /></b>
            <br />
            <rich:spacer height="5" />
            <br />
            <a4j:commandButton ajaxSingle="true" value="Clean Up Form"
                reRender="name, job, out" status="commonstatus">
                <a4j:actionparam name="n" value="" assignTo="#{userBean.name}" />
                <a4j:actionparam name="j" value="" assignTo="#{userBean.job}" />
            </a4j:commandButton>
        </a4j:region>

    </h:form>
</a4j:region>


Documentation in development

Some concepts covered in this chapter may refer to the previous version of Richfaces , version 3.3.3. This chapter is scheduled for review to ensure all information is up to date.

This chapter covers all components related to the display of tables and grids.

The <rich:column> component facilitates columns in a table or other UIData component. It supports merging columns and rows, sorting, filtering, and customized skinning.

In general usage, the <rich:column> component is used in the same was as the JavaServer Faces (JSF) <h:column> component. It requires no extra attributes for basic usage, as shown in Example 9.1, “Basic column example”.


Columns can be merged by using the colspan attribute to specify how many normal columns to span. The colspan attribute is used in conjunction with the breakBefore attribute on the next column to determine how the merged columns are laid out. Example 9.2, “Column spanning example”.


Similarly, the rowspan attribute can be used to merge and span rows. Again the breakBefore attribute needs to be used on related <rich:column> components to define the layout. Example 9.3, “Row spanning example” and the resulting Figure 9.4, “Complex headers using column groups” show the first column of the table spanning three rows.


For details on filtering and sorting columns, refer to Section 9.11, “Table filtering” and Section 9.12, “Table sorting”.

The <rich:columnGroup> component combines multiple columns in a single row to organize complex parts of a table. The resulting effect is similar to using the breakBefore attribute of the <rich:column> component, but is clearer and easier to follow in the source code.

The <rich:columnGroup> can also be used to create complex headers in a table. Example 9.4, “Complex headers using column groups” and the resulting Figure 9.4, “Complex headers using column groups” demonstrate how complex headers can be achieved.


The <rich:columns> component allows for dynamic sets of columns for tables. Columns and rows can be merged, and the look and feel can be highly customized. The component gets a list from a data model and creates a corresponding set of columns in a <rich:dataTable> component. The <rich:columns> component also supports header and footer facets.

Basic usage of the <rich:columns> component requires the value attribute, which points to the data model; the var attribute, which holds the current variable for the collection of data; and the index attribute, which holds the current counter. The id attribute is used for when the individuals rows require identifiers for Ajax events.


The output can be customized to display specific columns and rows. The columns attribute specifies the number of columns. The rowspan attribute specifies the number of rows to display; if the attribute is set to 0, all remaining rows in the table are displayed. The begin and end attributes are used to specify the first and last zero-based iteration items to display in the table. Columns can be adjusted using the colspan, rowspan, and breakBefore attributes the same as with the <rich:column> component.

The <rich:columns> component can be used alongside <rich:column> components.


For details on filtering and sorting columns, refer to Section 9.11, “Table filtering” and Section 9.12, “Table sorting”.

The <rich:dataDefinitionList> component renders a list of items with definitions. The component uses a data model for managing the list items, which can be updated dynamically.

The var attribute names a variable for iterating through the items in the data model. The items to iterate through are determined with the value attribute by using EL (Expression Lanugage). The first attribute specifies which item in the data model to start from, and the rows attribute specifies the number of items to list. The title attribute is used for a floating tool-tip. Example 9.7, “<rich:dataDefinitionList> example” shows a simple example using the <rich:dataDefinitionList> component.


The <rich:dataFilterSlider> components is a slider control that can be used for filtering data in a table. The range and increment of the slider control are defined using the startRange, endRange, and increment attributes.

The slider is bound to a UIData component specified with the for attribute. The forValRef attribute refers to the value attribute used by the target component, and the filterBy attribute specifies which object member to filter according to the slider.

The handleValue attribute keeps the current handle position on the slider control; filtering is based on this value. The storeResults attribute allows the <rich:dataFilterSlider> component to keep the target UIData component in session.

The event defined with the submitOnSlide attribute is triggered when the handle value on the slider is changed.


The <rich:dataGrid> component is used to arrange data objects in a grid. Values in the grid can be updated dynamically from the data model, and Ajax updates can be limited to specific rows. The component supports header, footer, and caption facets.

Figure 9.7. The <rich:dataGrid> component


The <rich:dataGrid> component requires the value attribute, which points to the data model, and the var attribute, which holds the current variable for the collection of data. The number of columns for the grid is specifed with the columns attribute, and the number of elements to layout among the columns is determined with the elements attribute. The first attribute references the zero-based element in the data model from which the grid starts.


As the component is based on the <a4j:repeat> component, it can be partially updated with Ajax. The ajaxKeys attribute allows row keys to be defined, which are updated after an Ajax request.


The <rich:dataList> component renders an unordered list of items. The component uses a data model for managing the list items, which can be updated dynamically.

The type attribute refers to the appearance of the bullet points. The values of the attribute correspond to the type parameter for the <ul> HTML element:

The var attribute names a variable for iterating through the items in the data model. The items to iterate through are determined with the value attribute by using EL (Expression Lanugage). The first attribute specifies which item in the data model to start from, and the rows attribute specifies the number of items to list. The title attribute is used for a floating tool-tip. Example 9.7, “<rich:dataDefinitionList> example” shows a simple example using the <rich:dataDefinitionList> component.


The <rich:dataOrderedList> component renders an ordered list of items from a data model. Specific rows can be updated dynamically without updating the entire list.

The type attribute defines the appearance of the numerating list markers for the list. The possible values for the type attribute are as follows:

The first attribute specifies which item in the data model to start from, and the rows attribute specifies the number of items to list. The title attribute defines a pop-up title. To only update a sub-set of the rows in the list, use the ajaxKeys attribute, which points to an object that contains the specified rows.


The <rich:dataTable> component is used to render a table, including the table's header and footer. It works in conjunction with the <rich:column>, <rich:columnGroup>, and <rich:columns> components to list the contents of a data model.

The value attribute points to the data model, and the var attribute specifies a variable to use when iterating through the data model. The first attribute specifies which item in the data model to start from, and the rows attribute specifies the number of items to list. The header, footer, and caption facets can be used to display text, and to customize the appearance of the table through skinning. demonstrates a simple table implementation.


The <rich:dataTable> component is based on the <a4j:repeat> component, and as such it can be partially updated using Ajax. The ajaxKeys attribute defines the rows to be updated during an Ajax request.

For details on filtering and sorting data tables, refer to Section 9.11, “Table filtering” and Section 9.12, “Table sorting”.

The <rich:extendedDataTable> component builds on the functionality of the <rich:dataTable> component, adding features such as data scrolling, row and column selection, and rearranging of columns.

The <rich:extendedDataTable> component includes the following attributes not included in the <rich:dataTable> component:

activeClassheightselection
activeRowKeynoDataLabelselectionMode
enableContextMenuonselectionchangetableState
groupingColumnselectedClass 

The <rich:extendedDataTable> component does not include the following attributes available with the <rich:dataTable> component:

Basic use of the <rich:extendedDataTable> component requires the value and var attributes, the same as with the <rich:dataTable> component. Refer to Section 9.9, “<rich:dataTable>” for details.

The height attribute is mandatory, and defines the height of the table on the page. This is set to 500px by default. The width of the table can be set by using the width attribute. As with the <rich:dataTable> component, the look of the <rich:extendedDataTable> component can be customized and skinned using the header, footer, and caption facets.

Example 9.14. <rich:extendedDataTable> example


<rich:extendedDataTable id="edt" value="#{extendedDT.dataModel}" var="edt" width="500px" height="500px" selectedClass="dataTableSelectedRow" sortMode="single" selectionMode="multi" selection="#{extendedDT.selection}" rowKeyVar="rkvar" tableState="#{extendedDT.tableState}">
    <rich:column id="id" headerClass="dataTableHeader" width="50" label="Id" sortable="true" sortBy="#{edt.id}" sortIconAscending="dataTableAscIcon" sortIconDescending="dataTableDescIcon">
        <f:facet name="header">
            <h:outputText value="Id" />
        </f:facet>
        <h:outputText value="#{edt.id}" />
    </rich:column>
    <rich:column id="name" width="300" headerClass="dataTableHeader" label="Name" sortable="true" sortBy="#{edt.name}" sortIconAscending="dataTableAscIcon" sortIconDescending="dataTableDescIcon" filterBy="#{edt.name}" filterEvent="onkeyup" visible="false"> 
        <f:facet name="header"> 
            <h:outputText value="Name" />
        </f:facet>
        <h:outputText value="#{edt.name}" />
    </rich:column>
    <rich:column id="date" width="100" headerClass="dataTableHeader" label="Date" sortable="true" comparator="#{extendedDT.dateComparator}" sortIconAscending="dataTableAscIcon" sortIconDescending="dataTableDescIcon">
        <f:facet name="header">
            <h:outputText value="Date" />
        </f:facet>
        <h:outputText value="#{edt.date}"><f:convertDateTime pattern="yyyy-MM-dd HH:mm:ss" />
        </h:outputText>
    </rich:column>
    <rich:column id="group" width="50" headerClass="dataTableHeader" label="Group" sortable="true" sortBy="#{edt.group}" sortIconAscending="dataTableAscIcon" sortIconDescending="dataTableDescIcon">
        <f:facet name="header">
            <h:outputText value="Group" />
        </f:facet>
        <h:outputText value="#{edt.group}" />
    </rich:column>
</rich:extendedDataTable>

Figure 9.12. <rich:extendedDataTable> example



Example 9.14, “<rich:extendedDataTable> example” shows an example extended data table. The implementation features a scrolling data table, selection of one or more rows, sorting by columns, grouping by column, and a filter on the Name column.

Row selection is determined by the selectionMode attribute. Setting the attribute to none allows for no row selection capability. Setting the selectionMode attribute to single allows the user to select a single row at a time using the mouse. With the selectionMode attribute set to multi, the user can select multiple rows by holding down the Shift or Ctrl keys while clicking. The selection attribute points to the object that tracks which rows are selected. Figure 9.13, “Selecting multiple rows” shows the table from the example with multiple rows selected.

Figure 9.13. Selecting multiple rows


The example uses the filter facet of the <rich:column> component to display the text field. A user can type their criteria into the text field to customize the filter of the column below. For full details on filtering tables, refer to Section 9.11, “Table filtering”.

When hovering the mouse over a column header, a menu button appears to the right-hand side, as shown in Figure 9.14, “Column menu”. This menu allows the user to sort the contents of the column, group the table by the column, or hide and show columns.

Figure 9.14. Column menu


Each column can allow sorting by setting the <rich:column> component's sortable attribute to true. The value of the data model to sort by is specified with the sortBy attribute. In addition to using the menu for sorting, columns can be quickly sorted either ascending or descending by clicking on the directional icon next to the column title. The directional icons are defined in each <rich:column> component with the sortIconAscending and sortIconDescending attributes, for ascending and descending icons respectively. For full details on sorting tables, refer to Section 9.12, “Table sorting”.

Grouping the table's entries by a column will organize the table into collapsible sections, as shown in Figure 9.15, “Grouping table entries by column”.

Figure 9.15. Grouping table entries by column


The checkboxes in the column menu under the Columns sub-menu will hide or show the respective columns, as shown in Figure 9.16, “Hiding columns”.

Figure 9.16. Hiding columns


Columns in a <rich:extendedDataTable> component can be rearranged by the user by dragging each column to a different position. The label attribute for the <rich:column> component is displayed during dragging, as shown in

Figure 9.17. Dragging columns


Once the contents of the table have been rearranged and customized by the user, the tableState attribute can be used to preserve the customization so it can be restored later. The tableState attribute points to a backing-bean property which can in turn be saved to a database separate from standard JSF state-saving mechanisms.

Read this chapter for details on special functions for use with particular components. Using JavaServer Faces Expression Language (JSF EL), these functions can be accessed through the data attribute of components. Refer to Section 2.5.7, “data” for details on the data attribute.