我有一个RoleStatus
枚举,它是映射到DB中整数的Role
实体的属性(但该部分无关紧要)。我想在List<Role>
中提供一个<p:dataTable>
,其中一列应该<h:selectOneMenu>
RoleStatus
实体的Role
属性。如何使用或不使用OmniFaces来实现此功能?
这是枚举:
public enum RoleStatus {
ACTIVE(1, "Active"),
DISABLE(2, "Disable");
private final int intStatus;
private final String status;
private RoleStatus(int intStatus, String status) {
this.intStatus = intStatus;
this.status = status;
}
public int getIntStatus() {
return status;
}
public String getStatus() {
return status;
}
}
这是支持bean:
@ManagedBean
@ViewScoped
public class RoleController {
private List<Role> roles;
@ManagedProperty("#{roleService}")
private IRoleService roleService;
@PostConstruct
public void init() {
roles = roleService.getRoles();
}
public List<Role> getRoles() {
return roles;
}
}
最后,数据表中我希望<h:selectOneMenu>
实体的RoleStatus
属性Role
,将所有可用的枚举值显示为选项项目选项。
<h:form id="roleForm">
<p:dataTable value="#{roleController.roles}" var="role">
<p:column>
<h:outputText value="#{role.roleid}" />
</p:column>
<p:column>
<h:inputText value="#{role.role}" />
</p:column>
<p:column>
<h:inputText value="#{role.description}" />
</p:column>
<p:column>
<h:selectOneMenu value="#{role.roleStatus}">
<!-- How??? -->
</h:selectOneMenu>
</p:column>
</p:dataTable>
</h:form>
我怎样才能做到这一点?我需要OmniFaces SelectItemsConverter
吗?
答案 0 :(得分:6)
您不需要转换器。 JSF已经有一个内置的枚举转换器。
如果没有OmniFaces,请按以下方式将枚举值作为<h:selectOneMenu>
的可用项提供:
将此方法添加到RoleController
:
public RoleStatus[] getRoleStatuses() {
return RoleStatus.values();
}
这样,#{roleController.roleStatuses}
可以使用所有枚举值。
然后使用此下拉列表:
<h:selectOneMenu value="#{role.roleStatus}">
<f:selectItems value="#{roleController.roleStatuses}" var="roleStatus"
itemValue="#{roleStatus}" itemLabel="#{roleStatus.status}" />
</h:selectOneMenu>
注意:由于这些值是静态/应用程序范围的,因此将方法移动到单独的@ApplicationScoped
bean并不会有什么坏处。
使用OmniFaces,你可以删除额外的getter并直接通过<o:importConstants>
导入枚举:
在模板顶部的某处添加(假设它在com.example
包中):
<o:importConstants type="com.example.RoleStatus" />
这样,枚举类本身可由#{RoleStatus}
使用(注意大小写!)。
然后使用此下拉列表:
<h:selectOneMenu value="#{role.roleStatus}">
<f:selectItems value="#{RoleStatus.values()}" var="roleStatus"
itemValue="#{roleStatus}" itemLabel="#{roleStatus.status}" />
</h:selectOneMenu>