0

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 in Java?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Illep
  • 16,375
  • 46
  • 171
  • 302

1 Answers1

2

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?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I was trying [http://www.primefaces.org/showcase/ui/datatableFiltering.jsf ] the example and it gives an error when i try to add `List ` so i thought to use `SelectItem[]` instead. – Illep Aug 03 '11 at 19:18