Converter not equating on transfer object (select one menu)

Posted: July 18, 2013 in web

xhtml

							<p:selectOneMenu value="#{car.category}"
								converter="#{categoryConverter}">
								<f:selectItem itemLabel="Select a category" />
								<f:selectItems value="#{car.categories}" var="category"
									itemLabel="#{category.name}" itemValue="#{category}" />
							</p:selectOneMenu>

Converter

@Model
public class CategoryConverter implements Converter {
    @Inject
    CategoryBean categoryBean;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        List<Category> categories = categoryBean.getCategories();
        if (categories != null) {
            for (Category category : categories) {
                if (category.getName().equals(value))
                    return category;
            }
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        // if (value == null || value.toString().isEmpty()) {
        return null;
        // } else {
        // return ((Category) value).getName();
        // }
    }

}

Category class (you need to override the equels method)

...
 @Override
    public boolean equals(Object object) {
        if (!(object instanceof Category)) {
            return false;
        }
        Category other = (Category) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
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