Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
PrimeFaces Beginner's Guide

You're reading from  PrimeFaces Beginner's Guide

Product type Book
Published in Nov 2013
Publisher Packt
ISBN-13 9781783280698
Pages 378 pages
Edition 1st Edition
Languages
Author (1):
Siva Prasad Reddy Katamreddy Siva Prasad Reddy Katamreddy
Profile icon Siva Prasad Reddy Katamreddy

Table of Contents (20) Chapters

PrimeFaces Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Introduction to PrimeFaces Introducing Sample Application TechBuzz Using PrimeFaces Common Utility Components Introducing the PrimeFaces Client Side Validation Framework Introducing Text Input Components Working with Selection Input Components Introducing Advanced Input Components Working with Data Components Introducing Advanced Data Visualization Components Working with Layout Components Introducing Navigation Components Drawing Charts Using PrimeFaces Themes Index

Chapter 6. Working with Selection Input Components

Selection components such as drop-down lists, checkboxes, and radio buttons are vey commonly used elements in web applications. But native HTML selection input components are very limited and don't provide enough features to build modern complex and rich user interfaces. To address this, PrimeFaces provides several selection input components with enhanced features and theming support.

In this chapter, we will cover the following components:

  • Creating the toggle button using SelectBooleanButton

  • Creating the On or Off options using SelectBooleanCheckbox

  • Introducing SelectManyCheckbox

  • Introducing SelectOneRadio

  • Introducing SelectOneButton

  • Introducing SelectManyButton

  • Creating drop-down lists using SelectOneMenu

  • Introducing SelectOneListbox

  • Introducing SelectManyMenu

  • Creating the overlay menu using SelectCheckboxMenu

  • Creating the overlay menu with a default command using SplitButton

  • Introducing the PickList component

  • Introducing the MultiSelectListbox component...

Creating the toggle button using SelectBooleanButton


The SelectBooleanButton component is used to select a yes or no decision with a toggle button:

<h:outputText value="Subscribe to Email Notifications: " />  
<p:selectBooleanButton value="#{selectionController.subscribed}" onLabel="Yes" offLabel="No" onIcon="ui-icon-check" offIcon="ui-icon-close" />

Here, the onLabel and offLabel attributes are mandatory. We can change the labels and icons using the onLabel, offLabel, onIcon, and offIcon attributes.

We can also add an event listener to the <p:selectBooleanButton> component using a nested <p:ajax> element.

Time for action – using the SelectBooleanButton component


Let us see how to save user preferences on subscribing to weekly e-mail notifications using the <p:selectBooleanButton> component, by performing the following steps:

  1. Create a User Preferences form:

    <h:form>
        <p:panel header="User Preferences" style="width: 400px; margin: 0 auto;">
        <p:messages autoUpdate="true"/>  
            <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
            <h:outputText value="Subscribe to Email Notifications: " />
            <p:selectBooleanButton value="#{selectionController.subscribeToEmailNotif}" onLabel="Yes" offLabel="No" onIcon="ui-icon-check" offIcon="ui-icon-close">  
                <p:ajax update="display" listener="#{selectionController.handleEmailSubscription}"/>  
            </p:selectBooleanButton>
        </h:panelGrid>  
        
        <h:panelGrid columns="1" id="display">  
            <h:outputText value="Subscribed to Email...

Creating the On or Off options using SelectBooleanCheckbox


The SelectBooleanCheckbox component is an extended version of the standard checkbox with theme integration. We can also add an event listener to the <p:selectBooleanCheckbox> component using a nested <p:ajax> element.

Time for action – using the SelectBooleanCheckbox component


Let us see how to use <p:selectBooleanCheckbox> along with the AJAX listener support, by performing the following step:

  1. Create the User Preferences form using <p:selectBooleanCheckbox> components:

    <h:form>
        <p:panel header="User Preferences" style="width: 500px;">
        <p:messages/>
        <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
    
            <h:outputText value="Show Online Status: " />
            <p:selectBooleanCheckbox value="#{selectionController.showOnlineStatus}" />
    
            <h:outputText value="Accept Private Messages: " />
            <p:selectBooleanCheckbox value="#{selectionController.recievePrivateMsgs}">
                <p:ajax update="display" listener="#{selectionController.updateUserpreferences}"/>
            </p:selectBooleanCheckbox>
    
        </h:panelGrid>
        <p:commandButton value="Submit" update="@form" actionListener="#{selectionController...

Introducing SelectManyCheckbox


The SelectManyCheckbox component is an extended version of the JSF standard SelectManyCheckbox component with theme integration.

Time for action – using the SelectManyCheckbox component


Let us see how we can use the <p:selectManyCheckbox> component, by performing the following steps:

  1. Create a form using the <p:selectManyCheckbox> components:

    <h:form id="form1" style="width:500px; margin: 0 auto;">  
        <p:messages autoUpdate="true"  escape="false" />
        <p:panel header="SelectManyCheckBox">
        <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">  
    
            <h:outputText value="Favourite Tags: " />  
            <p:selectManyCheckbox value="#{selectionController.favoriteTags}">  
                <f:selectItem itemLabel="JSF" itemValue="jsf" />  
                <f:selectItem itemLabel="PrimeFaces" itemValue="primefaces" />  
                <f:selectItem itemLabel="Spring" itemValue="spring" />  
            </p:selectManyCheckbox>
            
            <h:outputText value="Popular Tags: " />  
            <p:selectManyCheckbox value="#{selectionController...

Introducing SelectOneRadio


The SelectOneRadio component is an extended version of the JSF standard SelectOneRadio component with theme integration.

Time for action – using the SelectOneRadio component


Let us see how to use the <p:selectOneRadio> component, by performing the following steps:

  1. Create a form with <p:selectOneRadio> components:

    <h:form id="form" style="width: 500px; margin: 0 auto;">  
        <p:panel header="SelectOneRadio">
        <h:panelGrid columns="2" style="margin-bottom:5px" cellpadding="2">  
    
            <h:outputText value="Gender: " />  
            <p:selectOneRadio id="gender" value="#{selectionController.gender}">  
                <f:selectItem itemLabel="Male" itemValue="M" />  
                <f:selectItem itemLabel="Female" itemValue="F" />  
            </p:selectOneRadio>  
    
            <h:outputText value="Favourite Server: " />  
            <p:selectOneRadio id="server" value="#{selectionController.selectedServer}" layout="pageDirection">  
                <f:selectItems value="#{selectionController.servers}"/>  
            </p:selectOneRadio>
            
      ...

Introducing SelectOneButton


SelectOneButton is an input component to select options using regular buttons instead of radio buttons. The SelectOneButton component's behavior is similar to the SelectOneRadio component, except options are displayed as buttons instead of radios, as shown in the following screenshot:

Time for action – using the SelectOneButton component


Let us see how to use the <p:selectOneButton> component, by performing the following step:

  1. Create a form with the <p:selectOneButton> component with multiple options:

    <h:form>
        <p:panel header="SelectOneButton">
        <h:panelGrid style="margin-bottom:5px" cellpadding="3">  
            <p:selectOneButton value="#{selectionController.number}">
                <f:selectItem itemLabel="One" itemValue="1"/>
                <f:selectItem itemLabel="Two" itemValue="2"/>
                <f:selectItem itemLabel="Three" itemValue="3"/>
            </p:selectOneButton>
        </h:panelGrid>
        <p:commandButton value="Submit" update="display"/>  
        <h:outputText id="display" value="  Value : #{selectionController.number}" /> 
        </p:panel>
    </h:form>

What just happened?

We have used the <p:selectOneButton> component to display options as toggle buttons. When you click on any...

Introducing SelectManyButton


SelectManyButton is a multiselect component similar to the SelectManyCheckbox component, except options will be displayed as buttons instead of checkboxes, as shown in the following screenshot:

Time for action – using the SelectManyButton component


Let us see how to use the <p:selectManyButton> component, by performing the following step:

  1. Create a form with the <p:selectManyButton> component with multiple options:

    <h:form>
        <p:panel header="SelectManyButton">
        <h:panelGrid style="margin-bottom:5px" cellpadding="3">
            <p:selectManyButton value="#{selectionController.numbers}">
                <f:selectItem itemLabel="One" itemValue="1"/>
                <f:selectItem itemLabel="Two" itemValue="2"/>
                <f:selectItem itemLabel="Three" itemValue="3"/>
        </p:selectManyButton>
        </h:panelGrid>  
        
        <p:commandButton value="Submit" update="display"/>
        <h:outputText id="display"value="  Value : #{selectionController.numbers}" /> 
        </p:panel>
    </h:form>

What just happened?

We have used the <p:selectManyButton> component to display options as toggle buttons. When you select...

Creating drop-down lists using SelectOneMenu


The SelectOneMenu component is an extended version of the standard SelectOneMenu component with theme integration. We can create a basic drop-down list using <p:selectOneMenu> as follows:

<p:selectOneMenu value="#{selectionController.number}">
    <f:selectItem itemLabel="Select One" itemValue="" />
    <f:selectItem itemLabel="One" itemValue="1" />
    <f:selectItem itemLabel="Two" itemValue="2" />
    <f:selectItem itemLabel="Three" itemValue="3" />
</p:selectOneMenu>

The <p:selectOneMenu> component provides the following attributes to customize it's behavior:

  • effect: Name of the toggle animation. Default value is fade. Available effect options are blind, bounce, clip, drop, explode, fold, highlight, puff, pulsate, scale, shake, size, slide, and none.

  • effectSpeed: Duration of toggle animation in milliseconds. Default value is 400.

  • editable: If true, selected items become editable. Default value is false...

Time for action – using SelectOneMenu with editable and filter features


Let's look at how to create a drop-down menu with editable options, by performing the following step:

  1. Create a SelectOneMenu drop-down list using the editable and filter attributes:

    <p:selectOneMenu value="#{selectionController.selectedOption}" effect="fade" editable="true" filter="true" filterMatchMode="startsWith">  
        <f:selectItem itemLabel="Select One" itemValue="" />
        <f:selectItem itemLabel="One" itemValue="One" />
        <f:selectItem itemLabel="Two" itemValue="Two" />
        <f:selectItem itemLabel="Three" itemValue="Three" />  
    </p:selectOneMenu>

What just happened?

As we have set the editable attribute to true, we can select an existing option, select and edit an existing option, or write an entirely new option. When you click on the drop-down list icon, it will display the list of options along with a filter input textbox. When you type in the filter text, options will be filtered...

Time for action – using SelectOneMenu with POJOs


In this section, we will demonstrate how to use SelectOneMenu backed by a collection of POJOs by using a converter, by performing the following steps:

  1. Create a SelectOneMenu component using List<Tag> POJOs:

    <p:selectOneMenu value="#{selectionController.selectedTag}" converter="tagConverter">  
        <f:selectItem itemLabel="Select One" itemValue="" />  
        <f:selectItems value="#{selectionController.tagPojos}" var="tag" itemLabel="#{tag.label}" itemValue="#{tag}"/>  
    </p:selectOneMenu>
  2. Initialize List<Tag> POJOs in the managed bean:

    @ManagedBean
    @RequestScoped
    public class SelectionController 
    {
        private List<Tag> tagPojos;
        private Tag selectedTag;
    
        public SelectionController() 
        {
        tagPojos = new ArrayList<Tag>();
            tagPojos.add(new Tag(1, "JavaSE", "java-se", "Java Programming Language"));
            tagPojos.add(new Tag(2, "JavaEE", "java-ee", "Java Enterprise Edition"));
     ...

Time for action – grouping options in SelectOneMenu


Let us see how to display SelectOneMenu options in groups, by performing the following step:

  1. Create the SelectOneMenu component with option groups using the SelectItemGroup and SelectItem objects:

    @ManagedBean
    @RequestScoped
    public class SelectionController 
    {
        private List<SelectItem> tagItems = new ArrayList<SelectItem>();
        private String selectedTagItem;
        
        public SelectionController() 
        {
            SelectItemGroup g1 = new SelectItemGroup("JavaSE");
            g1.setSelectItems(new SelectItem[] {new SelectItem("Threads", "Threads"), new SelectItem("JDBC", "JDBC")});
        
            SelectItemGroup g2 = new SelectItemGroup("JavaEE");
            g2.setSelectItems(new SelectItem[] {new SelectItem("JPA", "JPA"), new SelectItem("JMS", "JMS"), new SelectItem("EJB", "EJB")});
    
            tagItems.add(g1);
            tagItems.add(g2);
        }
    }
    <p:selectOneMenu value="#{selectionController.selectedTagItem}">
        <f:selectItem...

Introducing SelectOneListbox


The SelectOneListbox component is an extended version of the standard SelectOneListbox component with theme integration. Basic usage of <p:selectOneListbox> is as follows:

<p:selectOneListbox value="#{selectionController.number}">
    <f:selectItem itemLabel="One" itemValue="1" />
    <f:selectItem itemLabel="Two" itemValue="2" />
    <f:selectItem itemLabel="Three" itemValue="3" />
</p:selectOneListbox>

The preceding <p:selectOneListbox> component will be rendered as shown in the following screenshot:

We can also use POJOs to populate <p:selectOneListbox> options. Let us see how to populate SelectOneListbox using POJOs.

Time for action – using SelectOneListbox with POJOs


Let's look at creating a SelectOneListbox backed by a collection of POJOs using a converter, by performing the following step:

  1. Create a form with the SelectOneListbox component using POJOs:

    <h:form>
        <p:panel header="SelectOneListbox">
        <h:panelGrid columns="2" style="margin-bottom:5px" cellpadding="3">
            <h:outputText value="Listbox Using POJO: " />  
            <p:selectOneListbox value="#{selectionController.selectedTag}" var="t" converter="#{tagConverter}">  
                <f:selectItems value="#{selectionController.tagPojos}" var="tag" 
                    itemLabel="#{tag.label}" itemValue="#{tag}"/>  
                <p:column>  
                    #{t.label} - #{t.value}  
                </p:column>
            </p:selectOneListbox>
        </h:panelGrid>
    
        <p:commandButton value="Submit" update="display" />  
        <h:outputText id="display" value="Listbox Using POJO: #{selectionController...

Introducing SelectManyMenu


The SelectManyMenu component is an extended version of the standard SelectManyMenu component with theme integration. SelectManyMenu is similar to SelectOneListbox but provides the ability to select multiple options. To select multiple options, you can press Ctrl and select Options or use the showCheckbox="true" attribute, which displays a checkbox for each option.

Time for action – using SelectManyMenu


Let us see how to use <p:selectManyMenu> with POJOs and the showCheckbox attribute, by performing the following step:

  1. Create a form with <p:selectManyMenu> components:

    <h:form>
        <p:panel header="SelectManyMenu">
        <h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
        <h:outputText value="Basic SelectManyMenu: " />
        <p:selectManyMenu  value="#{selectionController.numbers}">
            <f:selectItem itemLabel="One" itemValue="1" />
            <f:selectItem itemLabel="Two" itemValue="2" />
            <f:selectItem itemLabel="Three" itemValue="3" />
        </p:selectManyMenu>
    
        <h:outputText value="SelectManyMenu using POJO: " />  
        <p:selectManyMenu value="#{selectionController.selectedTagsFromPojos}" var="t" showCheckbox="true" converter="#{tagConverter}">  
        <f:selectItems value="#{selectionController.tagPojos}" var="tag" itemLabel="#{tag.label}" itemValue...

Creating the overlay menu using SelectCheckboxMenu


SelectCheckboxMenu is a multiselect component that displays options in an overlay. When you click on the SelectCheckboxMenu component, it will display a list of options each with a checkbox to select, and contains a filter text field to filter out the options.

Time for action – using SelectCheckboxMenu


Let us see how to use <p:selectCheckboxMenu> to select multiple options, by performing the following step:

  1. Create a form with the <p:selectCheckboxMenu> component as follows:

    <h:form>
        <p:panel header="SelectCheckboxMenu" style="width: 400px; height: 500px; margin: 0 auto;">
        <p:messages autoUpdate="true"/>  
        <h:panelGrid style="margin-bottom:5px" cellpadding="3">
            <p:selectCheckboxMenu value="#{selectionController.selectedSearchInOptions}" 
                    label="Search In" filter="true" filterText="Filter" filterMatchMode="startsWith" 
                    panelStyle="width:220px">  
                <f:selectItems value="#{selectionController.searchInOptions}" />  
            </p:selectCheckboxMenu>
        </h:panelGrid>  
        <p:commandButton value="Submit" update="display"/>
        <h:outputText id="display" value="Value : #{selectionController.selectedSearchInOptions}" />...

Creating the overlay menu with a default command using SplitButton


The SplitButton component displays a command button with an adjacent drop-down list icon. When you click on the button, the action associated with that button will be performed. When you click on the drop-down list icon it will display a list of other available options.

Time for action – using SplitButton


Let us see how we can use the <p:splitButton> component, by performing the following step:

  1. Create a form with the <p:splitButton> component with My Account as the default action, and Change Password and Logout as other options:

    <h:form>
        <p:splitButton value="My Account" actionListener="#{selectionController.showAccount}" >  
            <p:menuitem value="Change Password" url="changePwd.jsf" />  
            <p:menuitem value="Logout" ajax="false"  actionListener="#{selectionController.logout}"/>  
        </p:splitButton>
    </h:form>

What the just happened?

The preceding code displays SplitButton as shown in the following screenshot:

We have used <p:splitButton> with default action My Account, which triggers the action listener method selectionController.showAccount(). We have provided the other action items using <p:menuitem> elements.

Introducing the PickList component


PickList is a dual list input component that is used for transferring data between two different collections with the following features:

  • Drag-and-drop-based reordering

  • Transition effects

  • POJO support

  • Filtering

  • Captions

  • Checkbox selection

  • Client-server callbacks

PickList uses custom domain model org.primefaces.model.DualListModel, which contains source and target lists.

Time for action – using the basic PickList component


Let us see how we can create a PickList component to grant and revoke privileges to and from users, by performing the following steps:

  1. Initialize DualListModel in the managed bean:

    public class PickListController 
    {
        private DualListModel<String> privileges;
        public PickListController() 
        {
            
            List<String> privilegesSource = new ArrayList<String>();
            List<String> privilegesTarget = new ArrayList<String>();
    
            privilegesSource.add("Create User");
            privilegesSource.add("Delete User");
            privilegesSource.add("Disable User");
            privilegesSource.add("Remove Buzz Post");
    
            privileges = new DualListModel<String>(privilegesSource, privilegesTarget);
        }
        //setter and getter for privileges
    }
  2. Use the <p:pickList> component to create a PickList component:

    <p:pickList id="pickList" 
                value="#{pickListController.privileges}" 
        ...

Time for action – using the advanced PickList component


Let's look at creating a PickList component backed by a collection of POJOs using converter, by performing the following steps:

  1. Create a user-role management form with the PickList component:

    <p:growl id="msg" escape="false" />
    
    <p:pickList id="pojoPickList" value="#{pickListController.roles}" converter="#{roleConverter}"
                var="role" itemValue="#{role}" itemLabel="#{role.roleName}" 
                showSourceControls="true" showTargetControls="true" 
                showSourceFilter="true" showTargetFilter="true" 
                showCheckbox="true" filterMatchMode="contains" effect="bounce">
    
        <f:facet name="sourceCaption">Available Roles</f:facet>
        <f:facet name="targetCaption">Assigned Roles</f:facet>
    
        <p:ajax event="transfer" listener="#{pickListController.onTransfer}" update="msg" />
    
        <p:column style="width:100%">
            #{role.roleName}
        </p:column>
    
    </p:pickList...

Introducing the MultiSelectListbox component


MultiSelectListbox is a selection component that can be used to select an item from a collection of items with the parent-child hierarchical relationship.

For example, in e-commerce applications, we can display various types of categories and associated subcategories using MultiSelectListbox.

For the MultiSelectListbox component, we need to give a list of SelectItem instances, where each item can be a SelectItemGroup instance with its associated child SelectItem instances.

Time for action – using the MultiSelectListbox component


Let us see how to create a MultiSelectListbox component to display categories and its subcategories based on the selected category, by performing the following steps:

  1. Instantiate List<SelectItem> instances with details of categories and subcategories:

    public class CatalogController 
    {
        private List<SelectItem> categories;    
        private String selectedCategory;
    
        public CatalogController() 
        {        
            categories = new ArrayList<SelectItem>();
    
            SelectItemGroup homeAppliancesGrp = new SelectItemGroup("Home Appliances");
            SelectItemGroup homeDecorGrp = new SelectItemGroup("Home & Decor");
            SelectItem clocks = new SelectItem("Wall Clocks");
            SelectItem candleHolders = new SelectItem("Candle Holders");
            SelectItem artPrints = new SelectItem("Art Prints");
            homeDecorGrp.setSelectItems(new SelectItem[] { clocks, candleHolders,artPrints });
            SelectItem...

Summary


In this chapter, we have learned how to use various PrimeFaces selection input components such as SelectManyCheckbox, SelectOneRadio, SelectOneMenu, SelectOneListbox, SelectManyMenu, PickList, and so on. In the next chapter, we will learn about PrimeFaces advanced input components such as Calendar, Rating, Spinner, Slider, File Upload, and so on.

lock icon The rest of the chapter is locked
You have been reading a chapter from
PrimeFaces Beginner's Guide
Published in: Nov 2013 Publisher: Packt ISBN-13: 9781783280698
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}