6

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

When this button is clicked I need to pass few parameters (like a value of the selected row) using the Expression language. This paramaters need to be passed to the JSF managed bean which can execute methods on them.

I have used the following snippet of code but the value i am getting 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 can I pass values to the JSF managed bean with a commandbutton?

Tiny
  • 27,221
  • 105
  • 339
  • 599
user394432
  • 71
  • 1
  • 1
  • 4

1 Answers1

11

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

@ManagedBean
@ViewScoped
public class Usermanager {
    private List<Doctor> doctors;
    private DataModel<Doctor> doctorModel;

    @PostConstruct
    public void init() {
        doctors = getItSomehow();
        doctorModel = new ListDataModel<Doctor>(doctors);
    }

    public void followDoctor() {
        Doctor selectedDoctor = doctorModel.getRowData();
        // ...
    }

    // ...
}

Use it in the datatable instead.

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

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


An -less elegant- alternative is to use f:setPropertyActionListener.

public class Usermanager {
    private Long doctorId;

    public void followDoctor() {
        Doctor selectedDoctor = getItSomehowBy(doctorId);
        // ...
    }

    // ...
}

With the following button:

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

Related:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    IMO, the "less elegant" approach appears more intuitive for the uninitiated. How is the other approach preferred? – s_t_e_v_e Nov 01 '12 at 20:28