Enum and SelectOneMenu

UI Components for JSF
Post Reply
lmmoreira
Posts: 60
Joined: 08 Jul 2010, 14:15

18 May 2011, 15:34

Hi there

I would like to know if there is an example of the SelectOneMenu usage with Enums.

I do have it working fine with common entities and a genericConverter, but when I use Enuns they get the message of a invelid cast for String.

It is working fine when change it for a <H:SelectOneMenu>

My code for both is

Code: Select all


<p:selectOneMenu value="#{usuariosController.usuario.pessoa.sexo}" styleClass="dataTexts" var="item">
                        <f:facet name="EntityType">br.eximia.erh.entity.Sexo</f:facet>
                        <f:selectItems value="#{usuariosController.sexos}" var="sexo" itemLabel="#{sexo}" itemValue="#{sexo}"/>
                        <p:column>
                            #{item.sexo}
                        </p:column>
                    </p:selectOneMenu>




<h:selectOneMenu value="#{usuariosController.usuario.pessoa.sexo}" styleClass="dataTexts">
                        <f:facet name="EntityType">br.eximia.erh.entity.Sexo</f:facet>
                        <f:selectItems value="#{usuariosController.sexos}"/>
                    </h:selectOneMenu>

And I kind of dont want to make a function to convert it in a List of SelectItems
Tomcat 7 + jsf-api - 2.0.3-SNAPSHOT + Primefaces 2.1

healeyb
Posts: 365
Joined: 07 Apr 2010, 16:05

19 May 2011, 12:06

Have you tried itemLabel="#{sexo.name}"?

User avatar
Oleg
Expert Member
Posts: 3805
Joined: 02 Oct 2009, 09:41
Location: Germany, Black Forest

19 May 2011, 15:21

AFAIK, there is an undocumented EnumConverter in JSF. Try to register it in faces-config.xml

Code: Select all

<converter>
  <converter-for-class>java.lang.Enum</converter-for-class>
  <converter-class>javax.faces.convert.EnumConverter</converter-class>
</converter>
PrimeFaces Cookbook (2. edition): http://ova2.github.io/primefaces-cookbook/ Learning Angular UI Development with PrimeNG: https://github.com/ova2/angular-develop ... th-primeng Blog: https://medium.com/@OlegVaraksin

healeyb
Posts: 365
Joined: 07 Apr 2010, 16:05

19 May 2011, 17:58

Oleg, my understanding is that since the introduction of the enum
converter it should do it all for you.

User avatar
Oleg
Expert Member
Posts: 3805
Joined: 02 Oct 2009, 09:41
Location: Germany, Black Forest

19 May 2011, 18:43

Hi healeyb,

Yes, but I think you should register it explicitly.
PrimeFaces Cookbook (2. edition): http://ova2.github.io/primefaces-cookbook/ Learning Angular UI Development with PrimeNG: https://github.com/ova2/angular-develop ... th-primeng Blog: https://medium.com/@OlegVaraksin

healeyb
Posts: 365
Joined: 07 Apr 2010, 16:05

19 May 2011, 20:46

It's just that I use this all the time and I don't register it. I remember
looking into this when I was trying to get it working, I saw something
from someone like Ed Burns or BalusC or someone like that, and I
stopped using explicit converters. All my f:selectItems that return a
list of constant values use enums. I can post an example if required.

tony.herstell
Posts: 214
Joined: 29 Nov 2011, 00:40

17 Apr 2012, 00:14

Here is an example using Enums and SelectOne using an indirect off to internationalised messages
Showing usage in a dataTable (including filtering) and on its own.

[Pure J6EE [JSF]]

faces-config.xml

Code: Select all

<!-- Standard Enum Converter -->
	<converter>
        <converter-for-class>java.lang.Enum</converter-for-class>
        <converter-class>javax.faces.convert.EnumConverter</converter-class>
    </converter>
messages.properties

Code: Select all

all=All
#Event States
event_state=State
event_setup=Setup
event_open_for_entries=Open For Entries
event_closed_for_entries=Closed For Entries
event_running=Running
event_completed=Completed
event_cancelled=Cancelled

Code: Select all

public enum EventWorkflowStateKind {
    SETUP("event_setup"),
    OPEN_FOR_ENTRIES("event_open_for_entries"), 
    ENTRIES_CLOSED_FOR_ENTRIES("event_closed_for_entries"),
    RUNNING("event_running"),
    COMPLETED("event_completed"),
    CANCELLED("event_cancelled");

    private final String inlLabel;

    EventWorkflowStateKind(String inlLabel) {
        this.inlLabel = inlLabel;
    }
    public String getInlLabel() {
        return this.inlLabel;
    }

}
inside a panel grid (simple use) (CR=CreateUpdate[Writeable] and RD=ReadDelete[Read Only])

Code: Select all

                  <!-- state-->
                  <h:outputLabel for="stateCU" value="#{messages.event_state}" rendered="#{(eventManagementController.CRUDMode eq 'UPDATE')}"/>
                  <h:outputLabel for="stateCU" styleClass="mandatory" value="*" rendered="#{(eventManagementController.CRUDMode eq 'UPDATE')}"/>
                  <p:selectOneMenu id="stateCU" value="#{event.state}" required="true" rendered="#{(eventManagementController.CRUDMode eq 'UPDATE')}">
                    <f:selectItems value="#{eventManagementController.eventWorkflowStatusValues}" />
                  </p:selectOneMenu>
                  <p:message for="stateCU" rendered="#{(eventManagementController.CRUDMode eq 'UPDATE')}"/>

...

                  <!-- state -->
                  <h:outputLabel for="stateRD" value="#{messages.event_state}" />
                  <h:outputText id="stateRD" value="#{messages[event.state.inlLabel]}"/>


inside a data table

Code: Select all

         <p:dataTable id="eventsTable" value="#{events}" var="eachEvent" paginator="true" paginatorAlwaysVisible="false" emptyMessage="#{messages.events_no_events}" paginatorPosition="bottom"
               rows="5">
...
                  <p:column id="event_state_col" headerText="#{messages.event_state}" sortBy="#{messages[eachEvent.state.inlLabel]}"
                         filterBy="#{eachEvent.state}" filterOptions="#{eventManagementController.eventWorkflowStatusValues}" filterMatchMode="exact">
                  <h:outputText value="#{messages[eachEvent.state.inlLabel]}" />
               </p:column>

useful parts of the the Controller

Code: Select all


// Leverage EJB to get Transactional Support
@Stateful
// Lets be long running (multiple client-server round trips) - Needs Extended on
// PersistanceContext too to hold onto my objects and not get LIEs.
@ConversationScoped
// EL Can can find me...
@Named
public class EventManagementController

    // Access to the persistence store so we can read from the DB with Long
    // Running extension to go with Conversation Scope above.
    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager em;

    @SuppressWarnings("unused")
    @URLQueryParameter("cid")
    private String cid;

    // DON'T let any Entities be Proxied by WELD so just use class local.
    // According to this definition, JPA entities are technically managed beans.
    // However, entities have
    // their own special lifecycle, state and identity model and are usually
    // instantiated by JPA or using
    // new. Therefore we don't recommend directly injecting an entity class. We
    // especially recommend
    // against assigning a scope other than @Dependent to an entity class, since
    // JPA is not able to
    // persist injected CDI proxies.
    private List<EME_Event> events;

    private CRUDMode cRUDMode;

    // Inject this to make conversation magic happen
    @Inject
    private Conversation conversation;

    private SelectItem[] statusSelectOptions;

...
   
    private void setupEventWorkflowStatusValues() {
        this.statusSelectOptions = new SelectItem[EventWorkflowStateKind.values().length + 1];
        FacesContext fc = FacesContext.getCurrentInstance();
        Locale myLocale = fc.getExternalContext().getRequestLocale();
        ResourceBundle myResources = ResourceBundle.getBundle("messages", myLocale);
        int index = 0;
        this.statusSelectOptions[index++] = new SelectItem("", myResources.getString("all"));
        for (EventWorkflowStateKind state : EventWorkflowStateKind.values()) {
            this.statusSelectOptions[index++] = new SelectItem(state, myResources.getString(state.getInlLabel()));
        }
    }

    public SelectItem[] getEventWorkflowStatusValues() {
        return this.statusSelectOptions;
    }

    // In a sort of random way this allows for ANY use of a "list of Event",
    // anywhere, for this to "feed" the request... Dodgy...
    @Produces
    // EL Can can find me...
    @Named
    public List<EME_Event> getEvents() {
        this.logger.info("Getting the pre-fetched events ");
        this.logger.info("conversation:" + this.conversation.getId());
        return this.getAllEvents();
    }

    @SuppressWarnings("unchecked")
    private List<EME_Event> getAllEvents() {
        this.logger.info("Getting events from DB");
        if (this.events == null) {
            this.events = this.em.createQuery("select e from event e order by id desc").getResultList();
        }
        else {
            this.logger.info("Already have events set up");
        }
        return this.events;
    }


Post Reply

Return to “PrimeFaces”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 42 guests