Save SelectItem[] to List<Hotel> object
I have a List <Hotel>
object and I need to save it to a SelectItem[]
object. How do I code this?
public List <Hotel> hotel;
public SelectItem[] food;
// followed by getters and setters
I need to save the hotel
object to a food
object. How do I code this i开发者_C百科n Java?
Just construct SelectItem
objects with the desired value and label using its constructor. For example, with the hotel id
as value and hotel name
as label.
food = new SelectItem[hotels.size()];
for (int i = 0; i < hotels.size(); i++) {
Hotel hotel = hotels.get(i);
food[i] = new SelectItem(hotel.getId(), hotel.getName());
}
By the way, a List<SelectItem>
is also supported by <f:selectItems>
. That's easier to create.
food = new ArrayList<SelectItem>();
for (Hotel hotel : hotels) {
food.add(new SelectItem(hotel.getId(), hotel.getName()));
}
Unrelated to the concrete problem, based on your question history, you're using JSF 2.0. You can just use List<Hotel>
straight in the <f:selectItems>
without the need for ugly SelectItem
wrapper model. See also your previous question: How to populate options of h:selectOneMenu from database?
精彩评论