How to populate options of h:selectOneMenu from database?

前端 未结 5 1870
情话喂你
情话喂你 2020-11-21 05:03

I am creating a web application, where you have to read a list of objects / entities from a DB and populate it in a JSF . I am unable to

5条回答
  •  甜味超标
    2020-11-21 05:20

    Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.

    In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:

    
    

    ... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.

提交回复
热议问题