【问题标题】:Passing parameter to completeMethod of p:autoComplete将参数传递给 p:autoComplete 的 completeMethod
【发布时间】:2012-01-07 21:01:11
【问题描述】:

我在我的项目的搜索表单中使用 PrimeFaces p:autoComplete 小部件。用户可以选择他想要包含多少和哪些表单元素(搜索参数),所以我需要为每个表单元素传递一个 ID 到 completeMethod。我尝试添加 onfocus=".." 以将对象传递给 bean,但只有在第一次加载元素时才会激活。

我的问题:如何将属性传递给completeMethod

元素的XHTML(简单):

<p:autoComplete value="#{filter.value}" label="dynamic search attribute"
                completeMethod="#{myBean.complete}" />

豆子(简单):

@Named("myBean")
public class MyController implements Serializable {

    public List<String> complete(String query) {
        List<String> results = new ArrayList<String>();
        // ... code
        return results;
    }
}

理论上这似乎是完美的解决方案:

<p:autoComplete value="#{filter.value}" label="dynamic search attribute"
                completeMethod="#{myBean.complete(filter)}" />

还有 bean:

@Named("myBean")
public class MyController implements Serializable {

    public List<String> complete(String query, FilterObject o) {
        List<String> results = new ArrayList<String>();
        // ... database query based on FilterObject o
        return results;
    }
}

【问题讨论】:

    标签: jsf-2 autocomplete primefaces


    【解决方案1】:

    您可以将其设置为属性:

    <p:autoComplete value="#{filter.value}" label="dynamic search attribute" completeMethod="#{myBean.complete}">
        <f:attribute name="filter" value="#{filter}" />
    </p:autoComplete>
    

    通过UIComponent#getCurrentComponent()获取它:

    public List<String> complete(String query) {
        FacesContext context = FacesContext.getCurrentInstance();
        FilterObject o = (FilterObject) UIComponent.getCurrentComponent(context).getAttributes().get("filter");
        // ...
    }
    

    或者,由于 #{filter} 在您的情况下似乎已经在 EL 范围内,您也可以离开 &lt;f:attribute&gt; 并通过在 Application#evaluateExpressionGet() 的帮助下以编程方式评估 EL 表达式来获取它:

    public List<String> complete(String query) {
        FacesContext context = FacesContext.getCurrentInstance();
        FilterObject o = context.getApplication().evaluateExpressionGet(context, "#{filter}", FilterObject.class);
        // ...
    }
    

    或者,如果它也是一个@Named bean,那么你可以在父 bean 中 @Inject 它:

    @Inject
    private FilterObject o;
    

    【讨论】:

    • 我尝试了两种建议的解决方案,它们都非常有效。我选择了第二种方法,所以我不需要该属性。非常感谢!
    • 不客气。请注意,我添加了一个 @Inject 建议,它也可能对您有用。
    猜你喜欢
    • 2016-06-16
    • 2016-06-23
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2013-11-19
    • 2011-01-06
    相关资源
    最近更新 更多