Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to completeMethod of p:autoComplete

I'm using the PrimeFaces p:autoComplete widget in a search form of my project. The user can choose how many and which form-elements (search parameters) he wants to include so I need to pass an ID to the completeMethod for each of them. I've tried adding onfocus=".." to pass the object to the bean but that only would be activated when the element first is loaded.

My question: How can I pass an attribute to the completeMethod?

XHTML of the element (simple):

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

The bean (simple):

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

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

In theory this would seem like the perfect solution:

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

And again the 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;
    }
}
like image 471
Simon Plangger Avatar asked Nov 28 '11 11:11

Simon Plangger


1 Answers

You can set it as an attribute:

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

and get it by UIComponent#getCurrentComponent():

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

Alternatively, as that #{filter} appears in your case to be already in the EL scope, you can also leave the <f:attribute> away and get it by evaluating the EL expression programmatically with help of Application#evaluateExpressionGet():

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

Or, if it is also a @Named bean, then you can just @Inject it in the parent bean:

@Inject
private FilterObject o;
like image 82
BalusC Avatar answered Nov 07 '22 07:11

BalusC