static-max
static-max

Reputation: 779

Set f:param in external h:commandButton (JSF2)

I really love actionListener and the possibility to pass whole objects as as parameter, instead needing to pass values as String or creating (hidden) form fields. I'm using JSF 2.1 (Mojarra) and RichFaces (for popupPanel).

Currently I'm stuck with the following problem:

I create a table with a button that opens a popup. In that popup, the user can edit the data of the current user/object in the table.

When I click the button in the popup to save the edits, how can I submit the values from the popup AND tell the bean action which userObject I'm edited?

Currently, my workaround is using a hidden inputText field in the popup, but I don't like it this way. Is there an alternative?

This is what I try to achieve (minimized):

<h:datatable value="#{bean.users}" var="user">
  <h:column>
    Username #{user.name}
  </h:column>
  <h:column>
    <input onclick="showPopup()"/>
  </h:column>
</h:datatable>

<rich:popupPanel>
  <h:inputText value="#{bean.text}" />
  <h:commandButton value="Action" actionListener="#{bean.doSomething}">
    <f:attribute name="selected" value="#{userObjectFromDatatable}" />  <-- HOW? -->
  </h:commandButton>
</rich:popupPanel>

Upvotes: 2

Views: 1375

Answers (1)

kolossus
kolossus

Reputation: 20691

Looks pretty straightforward for you to preserve the selected the userObject in a conversation-like scope as in @ViewScoped. See this article for details on the @ViewScope. As an example, Declare a variable of the desired type as an instance variable in your backing bean

  UserObject userObject;
  //getters and setters

In your table you'll now have something like the following to set the selected object in your backing bean

   <h:commandButton value="Action" actionListener="#{bean.doSomething}">
    <f:setPropertyActionListener value="#{user}" target="#{bean.userObject}"/> 
   </h:commandButton>

By setting the variable in your backing bean from within the table, the viewscope will ensure that any other operation you perform on that object will be with the same instance, provided you stay on the same JSF view and you do not navigate away from it.

Upvotes: 1

Related Questions