Oleksandr H
Oleksandr H

Reputation: 3015

JSF Primefaces set button enabled when table row is selected

I have a list of users in a table and with disabled Delete button. I need to enable the Delete button when I select the row in the table. How can I do this?

<p:dataTable value="#{userBean.patients}" var="item"
            selectionMode="single" rowKey="#{item.id}"
            selection="#{userBean.selected}"
onRowSelected="deleteButton.disabled='false';"> // HOW TO WRITE THIS EVENT CORRECTLY?????
// columns
</p:dataTable>
//This button must be enable after I click on any table row
<p:commandButton id="deleteButton" value="Delete" disabled="true" />

Maybe, I need to use onRowClick event. I dont know the name of this event

Upvotes: 2

Views: 13631

Answers (2)

Oleksandr H
Oleksandr H

Reputation: 3015

Thanks for jsfviky71 ! I write:

<h:form id="form">
<p:dataTable value="#{bean.patients}" var="item"
            selectionMode="single" rowKey="#{item.id}"
            selection="#{bean.selected}" >
     <p:ajax event="rowSelect" update=":form:deleteButton" listener="#{bean.onRowSelect}" />
 // data in rows
</p:dataTable>

<p:commandButton id="deleteButton" value="Delete" disabled="#{bean.disabled}"/>

And in my bean:

private Boolean disabled = true;

// getter and setter

public void onRowSelect(SelectEvent event) {
    disabled = false;
}

Hope this will help to others

Upvotes: 5

jsfviky
jsfviky

Reputation: 183

One solution could be using

<p:ajax event="rowSelect" update=":deleteButton" listener="#{bean.someListener}" />

inside datatable.

This catches the row selection event, calls a listener and updates the button.

Now you could define the listener in the backing bean that just updates the value of a boolean instance variable, that reflects the disabled/enabled status of the button in the view:

<p:commandButton id="deleteButton" value="Delete" disabled="#{bean.selectedBoolean}" />

You can take a look at primefaces showcase for a similar scenario:

http://www.primefaces.org/showcase/ui/datatableRowSelectionInstant.jsf

Hope this helps.

Upvotes: 4

Related Questions