peterremec
peterremec

Reputation: 516

SelectOneMenu default value in edit mode

I have a editable datatable, containing column "Datatype". When editing this column, a selectOneMenu is used to select a value "String", "Number" or "Date". When I enter the edit mode, the "Datatype" column is set to "String" (the first item of data type list), but I would like it to be the current value of this column (like in Primefaces showcase: Click - for example if I click on a first row and third column of the second table, 'Fiat' should be selected and not the first item from selectOneMenu - 'BMW' -like in my case).

What could be the problem with my code?

xhtml:

<p:column headerText="Type" >
        <p:cellEditor>
                <f:facet name="output">
                        <h:outputText value="#{item.dataType.code}" />
                </f:facet>
                <f:facet name="input">
                        <p:selectOneMenu value="#{item.dataType}" converter="myConverter" >
                              <f:selectItems value="#{backingBean.dataTypeList}" var="dt" itemLabel="#{dt.code}" itemValue="#{dt}" />
                        </p:selectOneMenu>
                </f:facet>
        </p:cellEditor>
</p:column>

DataType class:

public class DataType implements Serializable {

    private BigDecimal id;
    private String code;
    private String descr;

    // Getters+Setters.
}

Using Primefaces 5.1.

I'm available for any additional information needed.

Upvotes: 2

Views: 1404

Answers (1)

BalusC
BalusC

Reputation: 1109635

Provided that the Converter implementation as identified by myConverter is properly doing its job, then this can happen if the entity in question, DataType, doesn't have equals() (and hashCode()) properly implemented.

Just add/autogenerate them in your entity. It should at least look like this:

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

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

This should also immediately solve the "Validation Error: Value is not valid" error when submitting the form.

All your entities should have them implemented. To avoid repeating boileplate, consider creating a base entity where all your entities extend from. See also Implement converters for entities with Java Generics.

Upvotes: 4

Related Questions