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:
- How to bind ‘Edit’-button to each row (i.e. to User-object)?
- How to obtain User-object in edit-form (second block of code)?
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 theeditmethod access theUserobject by<f:setPropertyActionListener>in JSF page orUIData#getRowData()in action method. In any case, you only need to ensure that theUIDatacomponent preserves exactly the same datamodel in the subsequent request.Examples can be found here: Using datatables
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.