H: commandButton inside h: dataTable

I am using a JSF data table. One of the columns in the table is the command button.

When this button is pressed, I need to pass several parameters (for example, the value of the selected string) using the language of expression. These parameters must be passed to a managed JSF bean that can execute methods on them.

I used the following code snippet, but the value that I get on the JSF bean is always null.

<h:column> <f:facet name="header"> <h:outputText value="Follow"/> </f:facet> <h:commandButton id="FollwDoc" action="#{usermanager.followDoctor}" value="Follow" /> <h:inputHidden id="id1" value="#{doc.doctorid}" /> </h:column> 

Bean Method:

 public void followDoctor() { FacesContext context = FacesContext.getCurrentInstance(); Map requestMap = context.getExternalContext().getRequestParameterMap(); String value = (String)requestMap.get("id1"); System.out.println("Doctor Added to patient List"+ value); } 

How to pass values ​​to a managed JSF bean using a command button?

+6
jsf datatable
source share
1 answer

Use DataModel#getRowData() to get the current row in action.

 @ManagedBean @ViewScoped public class Usermanager { private List<Doctor> doctors; private DataModel<Doctor> doctorModel; @PostConstruct public void init() { doctors = getItSomehow(); datamodel = new ListDataModel<Doctor>(doctors); } public void followDoctor() { Doctor selectedDoctor = doctorModel.getRowData(); // ... } // ... } 

Use it instead of datatable.

 <h:dataTable value="#{usermanager.doctorModel}" var="doc"> 

And get rid of this h:inputHidden next to h:commandButton in the view.


An endless elegant alternative is to use f:setPropertyActionListener .

 public class Usermanager { private Long doctorId; public void followDoctor() { Doctor selectedDoctor = getItSomehowBy(doctorId); // ... } // ... } 

Using the following button:

 <h:commandButton action="#{usermanager.followDoctor}" value="Follow"> <f:setPropertyActionListener target="#{usermanager.doctorId}" value="#{doc.doctorId}" /> </h:commandButton> 

Connected:

+10
source share

All Articles