3

I'm losing days with this strange problem, I double checked everything but my selectOneMenu simply doesn't works and I can't understand why.

So here are my codes:

My jsf

<p:selectOneMenu id="entityType"  
      value="#{entityBean.entity.type}" 
      style="width:240px;" 
      converter="entityTypeConverter"
      valueChangeListener="#{entityBean.entityTypeListener}"
      required="true">
      <f:selectItems value="#{entityBean.typeList}"
              var="et"
              itemLabel="#{et.name}"
              itemValue="#{et}" />
</p:selectOneMenu>

My converter:

    @FacesConverter("entityTypeConverter")
    public class EntityTypeConverter implements Converter {
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            Long id = Long.parseLong(value);

            return EntityType.findEntityType(id);
        }

        public String getAsString(FacesContext context, UIComponent component, Object value) {

            return value instanceof EntityType ? ((EntityType) value).getId().toString() : "";
        }
    }

It works as expected when I'm creating (it passes the selected value), but when I try to edit the entity the selected type actually never gets selected. I tried with primefaces 3.1.1 and 3.2 but I can't get the selected value when in view/edit mode.

What am I doing wrong?

Thanks in advance!

loop0.brs
  • 105
  • 1
  • 1
  • 9
  • The entity and entityType are just fantasy names – loop0.brs May 23 '12 at 19:43
  • use `p:ajax` instead of the valueChangeListener... – Daniel May 23 '12 at 19:55
  • Same problem without valueChangeListener. My problem is get the value selected when I load the edit page. I think the value="#{entityBean.entity.type}" and the converter should do this, but apparently this doesn't works with me. – loop0.brs May 23 '12 at 20:03

1 Answers1

10

That can happen if the equals() method of your EntityType class is missing or broken. Given the fact that you've an id property in your EntityType class which seems to identify the instance uniquely enough, the following minimal implementation should do it for you:

@Override
public boolean equals(Object other) {
    return (other instanceof EntityType) && (id != null)
        ? id.equals(((EntityType) other).id)
        : (other == this);
}

@Override
public int hashCode() {
    return (id != null)
        ? (this.getClass().hashCode() + id.hashCode())
        : super.hashCode();
}

hashCode() is just mandatory as per equals() contract.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452