使用POJO和String值自动完成Primefaces

kam*_*lot 2 jsf autocomplete converter primefaces jsf-2

我需要具有带有字符串值的自动填充功能,因为不能通过自动填充方法将用户限制为提供的项目,但是他们应该能够在搜索字段中写入任何内容。如果他们愿意,他们也可以从建议中选择。

现在,我总是得到 /archive/overview.xhtml @ 28,57 itemLabel =“#{item.name}”:类'java.lang.String'没有属性'name'。

XHTML:

<p:autoComplete id="vyraz" value="#{archiveView.searchString}"
  completeMethod="#{archiveView.autocomplete}"
  var="item" itemLabel="#{item.name}" itemValue="#{item.name}"
  converter="archiveConverter" forceSelection="false" minQueryLength="2"
  autoHighlight="false" effect="fade">

  <p:column>
    <h:outputText value="#{item.name}"/>
    <h:outputText value=" (Barcode: #{item.barcode})" rendered="#{item.barcode ne null}"/>
  </p:column>

  <p:column>
   <h:outputText value="#{item.type.label}" style="font-weight: bold;"/>
  </p:column>
</p:autoComplete>
Run Code Online (Sandbox Code Playgroud)

豆:

private String searchString; // + getter and setter

public List<ArchiveAutoCompleteDto> autocomplete(String query) {
    // get and return from lucene index/database
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一点(Primefaces 5.2)?
谢谢!

Mar*_*iol 7

itemValuep:autocomplete当您不执行p:autocomple小部件的任何更新/刷新(这基本上意味着您无法执行update="@form"或类似操作)时,在简单的情况下,in中的property 可以用作转换器的轻量级替换。

因此,基本上有3种情况:

Pojo +转换器

var必须在某些表情上设置属性,才能在PrimeFaces中启用“ pojo模式”。

<p:autoComplete 
     value="#{backingBean.myPojo}"
     completeMethod="#{backingBean.autocomplete}
     var="pojo" itemLabel="#{pojo.label}"
     itemValue="#{pojo}" converter="pojoConverter">
</p:autoComplete>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,var="pojo"是类A的实例。value="#backingBean.myPojo}"是类型A的变量。itemValue="#{pojo}"当您请求建议列表时,将对结果进行评估,结果将传递到转换器,转换器将通过getAsString该转换器生成以html编码的值(例如:)v1
当您从列表中选择一个元素(例如:)时,该元素v1将被传递回转换器,在该转换器中getAsObject您将得到一个类型A的对象以在后备bean中进行设置。通常,转换器负责将Pojo转换为HTML值,反之亦然。

public interface Converter {

    // @return *K* the value to be used in html
    // @param obj is provided by the expression (itemValue="#{pojo}")
    public String getAsString(FacesContext context, UIComponent component, Object obj);

     // build the pojo identified by String *K*
     // @param value *K*
     public Object getAsObject(FacesContext context, UIComponent component, String value);         
}
Run Code Online (Sandbox Code Playgroud)

Pojo +琴弦

在这种情况下,您可以使用带有String字段的pojo来提取和在后备bean中使用。

<p:autoComplete value="#{backingBean.myStringValue}" 
    completeMethod="#{backingBean.autocomplete} 
    var="pojo" itemLabel="#{pojo.label}" 
    itemValue="#{pojo.stringKey}">
</p:autoComplete>
Run Code Online (Sandbox Code Playgroud)

流程是一样的,但是

  1. itemValue必须计算为String以避免ClassCasts。
  2. itemValue直接用作html值(就像它是由产生的Converter#getAsString),并设置为"#{backingBean.myStringValue}"一次选定。
  3. "#{backingBean.myStringValue}" 当然必须是字符串。

一切正常,直到您尝试执行刷新p:autoComplete小部件为止(例如update =“ @ form”)。Primefaces itemLabel使用来自支持bean的值为String的值重新评估(由于某种原因,因为它不将itemLabel存储在ViewState中)。因此,您会得到错误。实际上,除了提供情况1)之外,没有其他解决方案。

纯字符串值

这里没有覆盖。