Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

h:commandButton inside h:dataTable [duplicate]

Tags:

datatable

jsf

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?

like image 758
user394432 Avatar asked Oct 16 '10 23:10

user394432


1 Answers

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:

  • The benefits and pitfalls of @ViewScoped - Contains CRUD example using DataModel<E>.
like image 120
BalusC Avatar answered Oct 02 '22 15:10

BalusC