selectOneMenu使用转换器的默认值问题

时间:2013-11-20 14:07:00

标签: jsf-2 primefaces converter

我正在使用<p:selectOneMenu>,如下所示:

<p:selectOneMenu id="choixProgramme" converter="#{programmeConverter}"
value="#{programmeController.selectedProgramme}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{programmeController.listProgrammes}"
    var="programme" itemLabel="#{programme.codeProgImmobilier}"
    itemValue="#{programme}" />
<p:ajax update="dataTableBien" />

我想显示Select One消息,但我收到此错误:

java.lang.String cannot be cast to xx.xxxxx.xxxx.xxxx.dto.ProgrammeDto

我试过了this solution,但我仍然遇到同样的问题。

被修改

我在noSelectionOption添加了<f:selectItem>:      

但我在getAsObject()中遇到了对话问题。

 java.lang.NumberFormatException: For input string: "Select One"

被修改

我的转换器:

@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
    if (arg2 == null || arg2.isEmpty()) {
        return null;
    }

    String programme = arg2;
    Long value = Long.valueOf(programme);
    ProgrammeDto result = new ProgrammeDto();
    result = programmeService.findById(value);
    return result;
}

@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

    if (arg2 == null) {
        return "";
    }
    if(arg2 instanceof ProgrammeDto) {
        if (((ProgrammeDto) arg2).getIdProgramme() == null) {
            return "";
        }
    }

            ProgrammeDto programme = new ProgrammeDto();

    if(arg2 instanceof ProgrammeDto) {

        programme = (ProgrammeDto) arg2;
        String codeProgramme = programme.getIdProgramme().toString();
        return (codeProgramme != null) ? String.valueOf(codeProgramme) : null;
    } else throw new ConverterException("Something wrong!" + arg2.hashCode() + arg2.toString());

}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您指定了一个空字符串的项目值,并且您很可能在转换器的getAsString()中有以下内容:

public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
    return ((ProgrammeDto) modelValue).getId();
}

但是,空字符串永远不能表示为有效的ProgrammeDto引用。

使用项目值#{null}而不是空字符串:

<f:selectItem itemLabel="Select One" itemValue="#{null}" />

或将noSelectionOption属性设置为true

<f:selectItem itemLabel="Select One" noSelectionOption="true" />

转换器的getAsString()现在可能会抛出NullPointerException而不是ClassCastException,但是应该明白如何解决这个问题。在投射并获得所需的字段之前,只需检查它是否为空。

public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
    return (modelValue != null) ? ((ProgrammeDto) modelValue).getId() : null;
}

另见:


更新:根据您更新的问题,PrimeFaces似乎没有考虑noSelectionOption并将标签视为商品值。在这种情况下,您需要明确指定项目值#{null}

<f:selectItem itemLabel="Select One" itemValue="#{null}" noSelectionOption="true" />

或检查getAsObject()是否提交的值可解析为Long

if (arg2 == null || !arg2.matches("[0-9]+")) {
    return null;
}