Monday, May 30, 2011

Internationalized h:selectOneMenu using a Enum

Using JSF2.0 it is now very easy to add internalionsed enums to your drop down (h:selectOneMenu) options. All you need to do is this:

<h:selectOneMenu id="colourSelect" value="#{colourController.colour}">
    <f:selectItems value="#{colourController.colours}"
                   var="colour"
                   itemValue="#{colour}"
                   itemLabel="#{enumBundle[colour.name()]}">
    </f:selectItems>
</h:selectOneMenu>

Simples! That may be enough for you to get going. Read on if you need more config info.

In faces config, add:
    <application>
        <resource-bundle>
            <base-name>/enumBundle</base-name>
            <var>enumBundle</var>
        </resource-bundle>
    </application>

Create a file '/src/main/resources/enumBundle.properties' (if using maven, otherwise place it in your default package) and add this to it:

RED=Colour Red
BLUE=Colour Blue
GREEN=Colour Green

Thats the resource bundle setup, now you just need the bean:

import java.io.Serializable;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;


@ConversationScoped
@Named("colourController")
public class ColourController implements Serializable {

    public enum Colour {
        RED, BLUE, GREEN
    }
    
    public Colour[] getColours(){
        return Colour.values();
    }

    public void colour(Colour colour) {
        System.out.println("colour: '" + colour.name() + "' was selected.");
    }
}

You DO NOT need to write your own converter (I have seen this recommended elsewhere) as JSF has it's own built in converter. This is all you need to do. I wasted a couple of hours on this, hopefully saves someone out there some time, let me know!

2 comments:

JP @ setting java classpath said...

Good post man, in my view Enum in Java are great feature and most versatile and very useful under certain scenario. In my opinion following are some of benefits of enum in java :
1) Enum is type-safe you can not assign anything else other than predefined enum constant to an enum variable.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.By the way I have also blogged my experience as 10 examples of enum in java , let me know how do you find it.

Anonymous said...

thank you do much, GOD bless YOU