I want to get selected object from <h:selectOneMenu>
, but the problem is I couldn't find any generic converter for all type of entities.
My first question is, is there a generic converter for all type of entities? I don't want to write another converter again for each other entity. My second question is, is there a way to get selected object without any converter? I don't want to call the DB again and again.
I have a Car
entity with id
and name
properties.
My first question is, is there a generic converter for all type of entities?
This does indeed not exist in standard JSF. The JSF utility library OmniFaces has such a converter in its assortiment, the omnifaces.SelectItemsConverter
. All you need to do is to declare it as converter of an UISelectOne
or UISelectMany
component as follows:
<h:selectOneMenu ... converter="omnifaces.SelectItemsConverter">
See also the SelectItemsConverter
showcase. This converter relies on the toString()
of the object item. There's also another one, the omnifaces.SelectItemsIndexConverter
, which relies instead on the index of the object item in the options list, see also the SelectItemsIndexConverter
showcase.
There are currently no other JSF component/utility libraries offering the same.
Second question is, is there a way to get selected object without any converter?
No. Just use the OmniFaces one so that you don't need to create a custom converter which hits the DB. Or if you want to go overboard, create a custom renderer for <h:selectOneMenu>
which renders the item index as option value and is able to set it as model value, but that's a lot of more work than a simple converter and you'd still need to do some additional work in order to get the desired object from the list based on the index — which just doesn't make any sense.