JSF 2 multiple select listbox example

In JSF, <h:selectManyListbox /> tag is used to render a multiple select listbox – HTML select element with “multiple” and “size” attribute.


//JSF...
<h:selectManyListbox value="#{user.favFood1}">
   	<f:selectItem itemValue="Fry Checken" itemLabel="Food1 - Fry Checken" />
   	<f:selectItem itemValue="Tomyam Soup" itemLabel="Food1 - Tomyam Soup" />
   	<f:selectItem itemValue="Mixed Rice" itemLabel="Food1 - Mixed Rice" />
</h:selectManyListbox>

//HTML output...
<select name="j_idt6:j_idt8" multiple="multiple" size="3">	
	<option value="Fry Checken">Food1 - Fry Checken</option> 
	<option value="Tomyam Soup">Food1 - Tomyam Soup</option> 
	<option value="Mixed Rice">Food1 - Mixed Rice</option> 
</select> 	

h:selectManyListbox example

A JSF 2.0 example to show the use of “h:selectManyListbox” tag to render multiple select listbox, and populate the data in 3 different ways :

  1. Hardcoded value in “f:selectItem” tag.
  2. Generate values with a Map and put it into “f:selectItems” tag.
  3. Generate values with an Object array and put it into “f:selectItems” tag, then represent the value with “var” attribute.

1. Backing Bean

A backing bean to hold and generate data for the multiple select listbox values. The property to hold the multi-selected listbox value, must be a type of Collection or Array; Otherwise it will hits the following error message


WARNING: Target model Type is no a Collection or Array
javax.faces.FacesException: Target model Type is no a Collection or Array

package com.mkyong;

import java.io.Serializable;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{

	public String[] favFood1;
	public String[] favFood2;
	public String[] favFood3;

	//getter and setter methods...

	public String getFavFood1InString() {
		return Arrays.toString(favFood1);
	}
	
	public String getFavFood2InString() {
		return Arrays.toString(favFood2);
	}
	
	public String getFavFood3InString() {
		return Arrays.toString(favFood3);
	}
	
	//Generated by Map
	private static Map<String,Object> food2Value;
	static{
		food2Value = new LinkedHashMap<String,Object>();
		food2Value.put("Food2 - Fry Checken", "Fry Checken"); //label, value
		food2Value.put("Food2 - Tomyam Soup", "Tomyam Soup");
		food2Value.put("Food2 - Mixed Rice", "Mixed Rice");
	}
	
	public Map<String,Object> getFavFood2Value() {
		return food2Value;
	}
	
	//Generated by Object array
	public static class Food{
		public String foodLabel;
		public String foodValue;
		
		public Food(String foodLabel, String foodValue){
			this.foodLabel = foodLabel;
			this.foodValue = foodValue;
		}
		
		public String getFoodLabel(){
			return foodLabel;
		}
		
		public String getFoodValue(){
			return foodValue;
		}
		
	}
	
	public Food[] food3List;
	
	public Food[] getFavFood3Value() {
		
		food3List = new Food[3];
		food3List[0] = new Food("Food3 - Fry Checken", "Fry Checken");
		food3List[1] = new Food("Food3 - Tomyam Soup", "Tomyam Soup");
		food3List[2] = new Food("Food3 - Mixed Rice", "Mixed Rice");
		
		return food3List;
	}
	
}

2. JSF Page

A JSF page to demonstrate the use “h:selectManyListbox” tag.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
    <h:body>
    	
    	<h1>JSF 2 multi-select listbox example</h1>
    	<h:form>
    	
	    1. Hard-coded with "f:selectItem" : 
   		<h:selectManyListbox value="#{user.favFood1}">
   			<f:selectItem itemValue="Fry Checken" itemLabel="Food1 - Fry Checken" />
   			<f:selectItem itemValue="Tomyam Soup" itemLabel="Food1 - Tomyam Soup" />
   			<f:selectItem itemValue="Mixed Rice" itemLabel="Food1 - Mixed Rice" />
   		</h:selectManyListbox>
		
		<br /><br />
	    
	    2. Generated by Map :
   		<h:selectManyListbox value="#{user.favFood2}">
   			<f:selectItems value="#{user.favFood2Value}" />
   		</h:selectManyListbox>
   		
	    <br /><br />
	    
	    3. Generated by Object array and iterate with var :
   		<h:selectManyListbox value="#{user.favFood3}">
   			<f:selectItems value="#{user.favFood3Value}" var="f"
   			itemLabel="#{f.foodLabel}" itemValue="#{f.foodValue}" />
   		</h:selectManyListbox>
   		
	    <br /><br />
	    
    	    <h:commandButton value="Submit" action="result" />
	    <h:commandButton value="Reset" type="reset" />

    	</h:form>
    	
    </h:body>

</html>

result.xhtml…


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      >
 
    <h:body>
    	
    	<h1>JSF 2 multi-select listbox example</h1>
    	
    	<h2>result.xhtml</h2>
    	
    	<ol>
    		<li>user.favFood1 : #{user.favFood1InString}</li>
    		<li>user.favFood2 : #{user.favFood2InString}</li>
    		<li>user.favFood3 : #{user.favFood3InString}</li>
    	</ol>
    </h:body>

</html>

3. Demo

jsf2-multi-select-listbox-example-1

When “submit” button is clicked, link to “result.xhtml” page and display the submitted multi-selected listbox values.

jsf2-multi-select-listbox-example-2

How to pre-select multiple listbox values ?

The value of “f:selectItems” tag is selected if it matched to the “value” of “h:selectManyListbox” tag. In above example, if you set favFood1 property to “Fry Checken” and “Tomyam Soup” :


@ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public String[] favFood1 = {"Fry Checken", "Tomyam Soup"};

	//...

The “favFood1” listbox values, “Fry Checken” and “Tomyam Soup” are selected by default.

Download Source Code

Reference

  1. JSF <h:selectManyListbox /> JavaDoc
  2. http://www.w3schools.com/tags/att_select_multiple.asp

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
7 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
JacksonbirburSandeepChOpperMikael Falkvidd Recent comment authors
newest oldest most voted
Jackson
Guest
Jackson

Hi Mkyong
Need idea on how to implement richfaces tooltip(rich:tooltip) for the multiselect

birbur
Guest
birbur

Well i guess something changed cuz i dont have this attributes anymore in selectItems.
i only got value , binding and id…
can you explain how to use it now?

Sandeep
Guest
Sandeep

About How to pre-select multiple listbox values , its fine if its a String, what in case of custom objects ? Ok, the background of this question is , I am trying to implement something like this : http://stackoverflow.com/questions/21501768/custom-objects-in-primefaces-picklist and I was wondering if this solution could help me , the first answer in this post : http://stackoverflow.com/questions/12874394/how-to-create-a-picklist-in-jsf-tried-moving-items-using-js-jquery-but-submit , and I was researching more on h:selectManyListBox, and your tutorial looks good. So now, back to my question :) Thanks!

Mikael Falkvidd
Guest
Mikael Falkvidd

Thanks a lot for the clear examples mkyong.

A note to anyone using JPA/Hibernate and is getting the following error when using @ManytoMany mapping:
“failed to lazily initialize a collection, could not initialize proxy – no Session: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy – no Session”

h:selectManyListbox needs to have the attribute collectiontype set to the type of collection your entity is using. In my case, I had to add collectionType=”java.util.HashSet” since my entity is using a Set.

The post that finally let me see the light was http://manuel-palacio.blogspot.se/2011/02/hibernate-jsf-2-and-manytomany.html

I hope this can help anyone else with this problem.

ChOpper
Guest
ChOpper

Hi,

Just to say thanks Mikael Falkvidd.
I was losing faith until I found your link and resolved my problem.

Cheers.

Mikael Falkvidd
Guest
Mikael Falkvidd

Great to hear ChOpper!

Gustavo
Guest
Gustavo

Thank you so much! very neat explanation :)

Soma sekhar
Guest
Soma sekhar

whats the difference between listbox and dropdown box?

trackback
JSF 2 multiple select dropdown box example

[…] forget about “h:selectManyMenu” tag, there is really no reason to use it. The “h:selectManyListbox” tag is a good […]