"why selectonemenu send itemlabel to the converter?" Code Answer


i'm not sure why you got the item label instead of the item value inside getasobject(). perhaps your getasstring() is doing it wrong and it is returning student name based on the student id.

at any way, i can tell that your itemvalue is definitely not right.

<h:selectonemenu id="studlist" value="#{studbean.selectedstudent}">  
    <f:selectitems value="#{studbean.student}" var="s" 
        itemvalue="#{s.studid}" itemlabel="#{s.name}" />
    <f:converter converterid="studentconverter" />

a converter is intented to be used to convert between a complex java object and a string representation so that it can be passed around as a http request parameter. however, you're specifying the student id as item value instead of the whole student object. you need to specify the whole student object instead. you should also ensure that #{studbean.selectedstudent} refers to a student property, not some long property representing the student id.

when you fix the itemvalue as follows:

<h:selectonemenu id="studlist" value="#{studbean.selectedstudent}">  
    <f:selectitems value="#{studbean.student}" var="s" 
        itemvalue="#{s}" itemlabel="#{s.name}" />
    <f:converter converterid="studentconverter" />

and your converter as follows (trivial nullchecks omitted):

public string getasstring(facescontext context, uicomponent component, object value) {
    // this method is called when item value is to be converted to http request parameter.
    // normal practice is to return an unique identifier here, such as student id.
    student student = (student) value;
    long id = student.getstudid();
    return string.valueof(id);

public object getasobject(facescontext context, uicomponent component, string value) {
    // this method is called when http request parameter is to be converted to item value.
    // you need to convert the student id back to student.
    long id = long.valueof(value);
    student student = somestudentservice.find(id);
    return student;

then it ought to work.

alternatively, you could keep your itemvalue as you initially had and remove the <f:converter> altogether, but then you have to change #{studbean.selectedstudent} to point to a long property representing the student id.

By kokemomuke on October 14 2022

Answers related to “why selectonemenu send itemlabel to the converter?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.