JSF Primefaces SelectOneMenu

Makky picture Makky · Nov 22, 2013 · Viewed 18.3k times · Source

Person can have only one car , but in the datatable I want to display all the cars in the list but select the one user person belongs to. This way user can update any person's car on the fly.

Let say I have two tables

Person

id 
name 
car_id

Cars

id
name

Ideally , person should have Cars id as primary key but that is not the case. So each person has car ,right.

Now I am displaying list of person in datatable e.g.

------------------------------------
Name | Car 
----------------------------------------
ABC | 1
DDD | 2

But I want to show like :

------------------------------------
Name | Car 
----------------------------------------
ABC | Toyota
DDD | Ford

The existing code :

<p:dataTable value="#{test.persons} var="person">
    <p:column headerText="Name"> 
        #{person.name}
    </p:column>
    <p:column headerText="Name"> 
        #{person.carID}
    </p:column>
</p:dataTable>

But I want to do something like:

<p:dataTable value="#{test.persons} var="person">
    <p:column headerText="Name"> 
        #{person.name}
    </p:column>
    <p:column headerText="Car">
        <p:selectOneMenu value="#{test.selectedCar}"
            converter="entityConverter">
            <f:selectItems value="#{spMBean.cars}" var="car" 
                itemLabel="#{car.name}" itemValue="#{car}" />
        </p:selectOneMenu>
    </p:column>
</p:dataTable>

If someone can help me with this, I'll highly appreciate that.

Answer

BalusC picture BalusC · Nov 22, 2013

You want to associate the selected car with the individual person.

However, you're binding the dropdown value to a generic backing bean property instead of to the invidivual person. All those dropdowns in all those rows in the same data table now point to one and same backing bean property. Upon submitting, the selected value of every single row will override each other until the backing bean property ends up with the selected value of the last row.

This doesn't make sense. You need to bind the dropdown value to the individual person.

<p:selectOneMenu value="#{person.car}">

This is easiest if Person entity has a private Car car property instead of a private Long carID. You can of course keep the available items in a separate bean.