converter with producer method/field for p:selectOneMenu

Posted: August 27, 2012 in web

managed bean / producer

private List<Card> cards;

@Produces
public List<Card> getCards() {
return cards;
}

CardConverter

@Named
@FacesConverter(forClass = Card.class)
public class CardConverter implements Converter {

@Inject
List<Cards> cards;

public CardConverter() {
super();
}

public CardConverter(List<Card> cards) {
this.cards = cards;
}

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (cards == null) {
return null;
} else {
for (Card card : cards) {
if (card.getTitle().equals(value)) {
return card;
}
}
}

return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object object) {
if (object == null) {
return null;
} else {
return ((Card) object).getTitle();
}
}

}

xthml

<p:selectOneMenu value=”#{bean.activeCard}”
converter=”#{cardConverter}”>
<f:selectItem itemLabel=”Select Card”
itemValue=”null” />
<f:selectItems value=”#{bean.cards}” var=”card”
itemLabel=”#{card.title}”
itemValue=”#{card}”>
</f:selectItems>
</p:selectOneMenu>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s