如何使用POJO列表和POJO属性作为选择值使用Primefaces自动完成

时间:2012-03-09 15:50:24

标签: jsf-2 autocomplete primefaces

在我们当前的项目中,我们希望用Primefaces的<h:selectOneMenu>替换<p:autocomplete>。选择项是Pojos(JPA实体)列表。与primefaces showcases中给定示例的不同之处在于,我们希望实体的主键属性(id)作为选择值,因此可以轻松地将其作为视图参数传递:

<f:metadata>
    <f:viewParam name="playerId" value="#{playerPreRenderViewListener.searchCriteria.playerId}" />
    <f:viewParam name="year" value="#{playerPreRenderViewListener.searchCriteria.year}" />
</f:metadata>
<h:form>
    <h:inputText value="#{playerPreRenderViewListener.searchCriteria.year}"/>
    <p:autoComplete var="player" itemLabel="#{player.name}" itemValue="#{player.id}"
        completeMethod="#{playerBean.completePlayer}" forceSelection="true"
        converter="#{playerConverter}" 
        value="#{playerPreRenderViewListener.searchCriteria.playerId}">
    </p:autoComplete>
    <h:commandButton value="Submit" action="showTeam?faces-redirect=true&amp;includeViewParams=true" />
</h:form>

不幸的是,上面的示例将导致PropertyNotFoundException:

  

itemLabel =“#{player.name}”:在类型java.lang.Long上找不到属性'name'

问题是var属性属于Long类型而非Player。使用简单<h:selectMenu>时,它与<f:selectItems>

配合使用
<f:selectItems var="player" value="#{playerBean.listPlayers}" itemLabel="#{player.name}" itemValue="#{player.id}" />

有人知道如何处理这个问题吗?

1 个答案:

答案 0 :(得分:2)

您可以添加一个返回属于当前活动playerId的播放器的辅助bean方法,并将此currentPlayer设置为辅助bean的value属性:

public Player getCurrentPlayer() {
  // find player by playerId and return
}

在视图中:

<p:autoComplete var="player" itemLabel="#{player.name}" itemValue="#{player}"
        completeMethod="#{playerBean.completePlayer}" forceSelection="true"
        converter="#{playerConverter}" 
        value="#{playerPreRenderViewListener.currentPlayer}">