使用setPropertyActionListener设置ENUM

时间:2013-03-22 13:48:37

标签: java jsf primefaces

我正在尝试使用setPropertyActionListener设置枚举属性,但我不知道该怎么做。这是实体:

@Entity
public class Invoice {
    public enum InvoiceStatus { ACTIVE, CANCELED }

        ...

        @Enumerated(EnumType.STRING)
    private InvoiceStatus status;

        ...

        public InvoiceStatus getStatus() {
        return status;
    }


    public void setStatus(InvoiceStatus status) {
        this.status = status;
    }

这是命令按钮,假设使用setPropertyActionListener将状态设置为ACTIVE

   ...

  <h:form id="invoiceCreatedSuccessfully">
        <p:dialog header="#{msg['title.success']}" widgetVar="invoiceCreatedSuccessfullyDialog" resizable="false" showEffect="fade" hideEffect="fade">  
            <h:panelGrid columns="2" rows="3" style="margin-bottom: 10px">  
                <h:outputText value="#{msg['message.invoiceCreatedSuccessfully']}" />
            </h:panelGrid>  
            <p:commandButton value="#{msg['label.acknowledged']}" actionListener="#{invoiceManager.reload}" action="viewInvoices">
                <f:setPropertyActionListener target="#{invoiceManager.invoice.status}" value="ACTIVE" />
            </p:commandButton>
        </p:dialog>
    </h:form>

未报告任何错误,但未设置DB中的字段“status”。有人可以告诉我为什么吗?

1 个答案:

答案 0 :(得分:0)

字符串不会直接转换为EL中的枚举,您需要在 faces-config 中自定义转换,jsf有一个适合您的枚举转换器,

<击>
<converter>
  <converter-for-class>java.lang.Enum</converter-for-class>
  <converter-class>javax.faces.convert.EnumConverter</converter-class>
</converter>

<击>

现在查看EnumConverter的源代码,看起来它只适用于转换器中的targetClass。

所以你需要扩展它以使用你的枚举

public class MyEnumConverter extends EnumConverter {
  public MyEnumConverter () {
    super(MyEnum.class);
  }
}

<converter>
  <converter-id>MyEnum</converter-id>
  <converter-class>com.test.MyEnumConverter</converter-class>
</converter>

在您的组件中添加<f:converter converterId="MyEnum"/>

如果你有很多枚举并且简单易用,你可以查看omnifaces http://showcase.omnifaces.org/converters/GenericEnumConverter