views:

461

answers:

2

It's trivial but unfortunately I don't understand some processes 'behind the scenes' in JSF. So, I'm also interested in links to related articles.

The problem: I have a list of User-objects. And I represent this list as a dataTable.

<h:dataTable var="user" value="#{userService.allUsers}">
    <h:column>
        <f:facet name="header">
            <h:outputText value="Login"/>
        </f:facet>
        <h:outputText value="#{user.login}"/>
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Birthdate"/>
        </f:facet>
        <h:outputText value="#{user.birthDate}"/>
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Name"/>
        </f:facet>
        <h:outputText value="#{user.name}"/>
    </h:column>
    <h:column>
        <!--This form with button is not a real code, just my suggestion how these things should be done-->
        <h:form>
            <h:commandButton action="openEditForm" value="Edit"/>
        </h:form>
    </h:column>
</h:dataTable>

Now I want to add commandButton "Edit" to each table row. Click on this button should open some form with editable fields where we can change current values.

<!--It's not a real code, just my suggestion how these things should be done-->
<h:form>
    <h:inputText value="#{user.login}"/>
    <h:inputText value="#{user.birthDate}"/>
    <h:inputText value="#{user.name}"/>
    <h:commandButton action="saveEdits" value="Save"/>
</h:form>

So, I have 2 questions:

  1. How to bind 'Edit'-button to each row (i.e. to User-object)?
  2. How to obtain User-object in edit-form (second block of code)?
+2  A: 
<h:commandLink id="editlink" value="#{msg.edit}" action="myEditPageNavRule">
    <f:setPropertyActionListener value="#{user}"
        target="#{userBean.user}" />
 </a4j:commandLink>

where #{user} is your dataTable var. Depending on the scope of your userBean, you will have the appropriate data when opening the edit page. (It will work with session-scope for sure, and if your navigationRule doesn't have 'redirect', you will have it with request scope, I think).

The above code just sets the current User object to the target property.

Bozho
+2  A: 
  1. Just by action="#{user.edit}" or maybe better (more common approach as business logic doesn't belong in model objects) action="#{userService.edit}" and then in the edit method access the User object by <f:setPropertyActionListener> in JSF page or UIData#getRowData() in action method. In any case, you only need to ensure that the UIData component preserves exactly the same datamodel in the subsequent request.

    Examples can be found here: Using datatables

  2. If you declare it as a managed bean, it's already available in the scope. If you want to refer it from another managed bean, then make use of managed property injection.

    Example can be found here: Communication in JSF.

BalusC