Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send additional parameter to Ajax event listener

I am having an Ajax listener who should redirect to item view page. However since I am using generic type as model I would like to specify additionally in my common data table controller what is the view with a second parameter.

Unfortunately one can choose between two listener approaches one using event parameter which helps identifying the object and the second one gives you the opportunity to send free param but lacks the event.

template:

<p:dataTable value="#{aObj.objList}" var="item" ... selectionMode="single">
              
  <p:ajax event="rowSelect" listener="#{aObj.viewItem}" />
  <p:ajax event="rowSelect" listener="#{aObj.viewItem('myItemView?_id=')}" />

  ...
</p:dataTable>

controller:

public void viewItem(SelectEvent event) {
  // ...
}
    
public void viewItem(String viewUrl) {
  // ...
}

I can add additional properties to the bean but since it is generic and providing model items doesn't feel right to pollute it.

Is there any workaround?

like image 961
kidwon Avatar asked Aug 25 '16 11:08

kidwon


2 Answers

You could set an attribute in your data table and read it in your select listener. To do so, use <f:attribute name="..." value="..."/>. From the documentation:

Constraints

Must be nested inside a UIComponent custom action.

Description

Locate the closest parent UIComponent custom action instance (...). If the associated component already has a component attribute with that name, take no action. Otherwise, call the isLiteralText() method on the argument value. If it returns true, store the value in the component’s attribute Map under the name derived above. If it returns false, store the ValueExpression in the component’s ValueExpression Map under the name derived above.

So, taking the attribute you tried to set in your comment, you should use it like:

XHTML:

<p:dataTable value="#{aObj.objList}" var="item" .... selectionMode="single">

  <f:attribute name="test" value="abc" />
  <p:ajax event="rowSelect" listener="#{aObj.viewItem}" />

  ...
</p:dataTable>

Listener:

public void viewItem(SelectEvent event) {
  String test = (String) event.getComponent().getAttributes().get("test");
  // ...
}
like image 98
Jasper de Vries Avatar answered Oct 02 '22 22:10

Jasper de Vries


When you want to add request parameters, which are specific to the ajax tag, you can do at the onstart method:

<p:ajax onstart="cfg.ext.params.push({name: 'name', value: 'value'});"/>

Usually, you should solve parameters using the model.

like image 39
Tires Avatar answered Oct 02 '22 21:10

Tires