Unable to Select Table Rows in PrimeFaces Using RadioButtons - jsf

I am trying to develop a web application using a PrimeFaces data table. I am having difficulty getting the object that corresponds to the selected row. Whenever I do that, a null value gets selected. Here is the relevant code:
<p:dataTable id="presTable" var="pres" value="#{presBean.presentations}"
rows="10" scrollable="true" scrollWidth="85%"
selection="#{presBean.selectedPres}" rowKey="#{pres.id}" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,25,100" widgetVar="presTable" filteredValue="#{presBean.filteredPres}" selectionMode="single">
</p:column>
<f:facet name="footer">
<p:commandButton id="updateButton" process="presTable" value="Update" action="#{presBean.printSelectedPres()}"/>
</f:facet>
</p:dataTable>
Java backing bean:
public Presentation getSelectedPres() {
System.out.println("Returning selected presentation: " + selectedPres);
return selectedPres;
}
public void setSelectedPres(Presentation selectedPres) {
System.out.println("Setting selected presentation to " + selectedPres);
this.selectedPres = selectedPres;
}
public void printSelectedPres() {
System.out.println("Printing list of checked presentations:");
System.out.println(selectedPres);
}

Add a column with seletionMode=single
<p:column selectionMode="single" style="width:16px;text-align:center"/>
you can find sample for radio button here : https://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml

Related

Primefaces lazy datatable : how to retrieve the visible list

I have a lazydatatable displaying thousands of cars. I ll have a buy button on the top of the page.
Basically, i want the user to buy all the cars visibles on the list when I press on the Buy Button. I m struggling to get a list limited to these cars.
How can I do?
xhtml
<p:dataTable var="car" value="#{carView.listCars}" paginator="true" rows="10" paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink}
{LastPageLink}" rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{carView.selectedCar}" id="carTable" lazy="true">
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
CarService
public void buy{
...
}
CarView
public void init(){
LazyCarDataModel cars= restService.getCars();
}
Using a p:datatable in lazy mode, you provide the data for the 'visible' list via the load method in your LazyDataModel. So if you keep that list in one way or another on the server (e.g. storing it in a #Viewscoped bean`), it is available when you click 'buy'.
Another way is to support multiple selection and have a 'select all' toggle box at the top of the selection. And then use the selected files server side

JSF: Cancel datatable row edit after data submission in Primefaces

I'm developing a web-app in JSF 2.1 + Primefaces 5.1. I have a datatable with editable rows. I catch the rowEdit event and call a DB procedure to do some validations of the new data and update the record when the user clicks the "check" button. But there's a problem: the datatable row in the GUI is updated whether the validations succeed or fail. I want the changes in the row data to be reversed to their previous state if the validations done in the DB procedure fail. How can I do that?
<p:dataTable id="users_table_id" var="user" value="#{usersBean.users}" rowKey="#{user.id}" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" emptyMessage="#{msgs.no_records}" sortBy="#{user.id}" sortOrder="ascending" rows="15" editable="true">
<f:facet name="header">
#{msgs.users}
</f:facet>
<p:ajax event="rowEdit" listener="#{usersBean.onRowEdit}"/>
<p:ajax event="rowEditInit" listener="#{usersBean.onRowEditInit}"/>
<p:column headerText="#{msgs.id}" sortBy="#{user.id}" styleClass="centered-column">
#{user.id}
</p:column>
<p:column headerText="#{msgs.description}" sortBy="#{user.description}" styleClass="centered-column">
<p:cellEditor>
<f:facet name="output">#{user.description}</f:facet>
<f:facet name="input"><p:inputText value="#{user.description}" styleClass="editable-cell"/></f:facet>
</p:cellEditor>
</p:column>
...
<p:column styleClass="datatable-row-editor">
<p:rowEditor/>
</p:column>
</p:dataTable>
#ManagedBean
#ViewScoped
public class UsersBean implements Serializable {
private List<DtoUser> users;
public void onRowEdit(RowEditEvent event) {
logger.entry();
DtoUser dtoUser = (DtoUser)event.getObject();
this.updateUser(dtoUser);
logger.exit();
}
public void updateUser(DtoUser dtoUser) {
try {
logger.entry(dtoUser);
DtoBoUsers dtoBoUsers = dtoUser.toDtoBoUsers();
DtoTypeGenericResponse genericResponse = usersService.updateUser(dtoBoUsers);
if (genericResponse.isError()) {
// error in user update
} else {
// update successful
}
logger.exit(dtoUser);
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e.fillInStackTrace()));
}
}
}

Datatable is not updated after adding records

I have an init() function that returns a list of emails that will be displayed in a Primefaces datatable. And I have a commandButton that extract emails and persist them in the dataTable. These new records show up in the dataTable only if I log out and log in.
This is my init() function ( my managed Bean is annotated with #ManagedBean(name = "mailMB") and #SessionScoped) :
#PostConstruct
public void init() {
emails = new ArrayList();
idCustomer = (String) session.getAttribute("idCustomer");
System.out.println(idCustomer + " this is it");
cust = customerBusinessLocal.findById(idCustomer);
System.out.println(cust.getName());
datas = dataBusinessLocal.findByCustomer(cust);
System.out.println(datas.size());
for (Data d : datas) {
for (Email e : mailBusinessLocal.mailsByData(d)) {
emails.add(e);
}
}
public List<Email> getEmails() {
return emails;
}
In my page xhtml i've implemented the code below:
<h:form id="form">
<p:commandButton value="Extract" update="tableemails" id="ajax" widgetVar="extractButton"
action="#{mailMB.searchEmails()}"
icon="ui-icon-disk" styleClass="ui-priority-primary"
onstart="blockUIWidget1.block()"
oncomplete="blockUIWidget1.unblock()"/>
<pe:blockUI target="formulaire" widgetVar="blockUIWidget1">
<h:panelGrid columns="2">
<img src="../../pictures/animated-loading-bar.gif" width="264" height="34" alt="animated-loading-bar"/>
<h:outputText value="Please wait..." style="white-space: nowrap;"/>
</h:panelGrid>
</pe:blockUI>
<p:panel id="display" header="Emails" >
<p:dataTable id="tableemails" value="#{mailMB.emails}" var="item" rowsPerPageTemplate="5,10,15" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
paginator="true" rows="10" styleClass="case-table" emptyMessage="No records found with given criteria" paginatorPosition="bottom"
filteredValue="#{mailMB.filteredMails}" rowKey="#{item.id}"
selection="#{mailMB.selectedMail}" selectionMode="single" >
<p:ajax event="rowSelect" update=":form:display"/>
<p:column styleClass="blockable" filterStyle="width: 250px" filterBy="#{item.email} " sortBy="#{item.email}">
<f:facet name="header">
<h:outputText value="Email"/>
</f:facet>
<h:outputText value="#{item.email}"/>
</p:column>
</p:dataTable>
</p:panel>
</h:form>
it looks like you do not reload your List<Email> emails after persisting some new data. #PostConstract is executed once after your bean is created (sincce it's #SessionScoped it's created once per session), thats why you see changes only after another login. Add a method repopulateEmails() that would load data from database and run it after you add/remove something, just add it to your persist() method.
public void persist()
{
....
getEntityManager().persist(getInstance());
getEntityManager().flush();
emails = null;
......
}
public List<Email> getEmails(){
if(emails == null){
emails = repopulateEmails();
}
return emails;
}

No data load my outputText of Primefaces?

I have a question I have a DataTable, where I have a button in a column edit, capture the Id of the record, and make a list that record to load the data in the object system, peroHola, I have a question I have a DataTable, where I have a button in a column edit, capture the Id of the record, and make a list that record to load the data in the object system, but my text box value is charging.
<p:dataTable id="dataTable" var="sis" value="#{listSistMB.system}"
paginator="true" rows="10" rowIndexVar="rowIndex" selection="#{listSistMB.system}"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
<h:outputText value="Status" />
</f:facet>
<p:selectBooleanButton value="#{sis.stStatus}" onLabel="A" offLabel="I" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Edit" />
</f:facet>
<p:commandButton id="selectEdit" action="#{listSistMB.editSystem}"
icon="ui-icon-search" title="Editar System">
<f:param name="codCode" value="#{sis.cdCode}"/>
</p:commandButton>
</p:column>
</p:dataTable>
In the controller I headed this way the system object.
#Component("listSistMB")
#Scope("view")
public class MantenanceSystemController implements Serializable{
private System system = new System();
public String editSystem(){
try {
String cdCode = (String)FacesContext.getCurrentInstance().getExternalContext().
getRequestParameterMap().get("codCode");
system = confSistemaService.buscarPorId(Long.valueOf(cdCode));
} catch (Exception e) {
e.printStackTrace();
}
return "register-system";
}
It's not charging me the value of the text box.
<p:inputText value="#{listSistMB.system.nbNomCorto}" />
The MantenanceSystemController bean is in #Scope("view")
If the p:dataTable and p:inputText are not on the same view, the information will be lost when changing views.
Consider a different scope (e.g., Conversation) for the bean.

Primefaces Datatable RowSelect Event

I have the following in my xhtml
<h:form id="clientTableForm" prependId="false">
<p:dataTable id="clientTable" widgetVar="clientTableVar"
var="client" value="#{resendEmailController.lazyDataModel}"
paginator="true" rows="15"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {CurrentPageReport}"
rowsPerPageTemplate="5,10,15,20,25,50,75,100"
paginatorPosition="bottom" pageLinks="5" lazy="true"
sortBy="#{client.cclnCode}" sortOrder="ascending"
selection="#{resendEmailController.selectedClient}"
selectionMode="single" filterDelay="500" scrollable="true"
scrollHeight="380">
<p:ajax event="rowSelect"
listener="#{resendEmailController.changeClient}"
update="_accountTableForm_accountTable" />
<p:column id="cclnCodeColumn" headerText="Client Code"
style="width:25%;" sortBy="#{client.cclnCode}"
filterBy="#{client.cclnCode}" filterMaxLength="10">
<h:outputText value="#{client.cclnCode}"
converter="#{trimStringConverter}" />
</p:column>
<p:column id="cclnNamenColumn" headerText="Client Name"
style="width:75%" sortBy="#{client.cclnName}"
filterBy="#{client.cclnName}" filterMaxLength="50">
<h:outputText value="#{client.cclnName}"
converter="#{trimStringConverter}" />
</p:column>
</p:dataTable>
</h:form>
</p:layoutUnit>
<script type="text/javascript">
$(document).ready(function()
{
autoSelectClient();
});
function autoSelectClient()
{
if (clientTableVar.isEmpty() == false)
{
clientTableVar.selectRow(1, false);
}
}
</script>
And I have this in my backing bean
public void changeClient(SelectEvent selectEvent)
{
ResendEmailClient client = (ResendEmailClient) selectEvent.getObject();
selectedClient = client;
String cclnCode = client.getCclnCode();
selectedAccounts = getService().listAccounts(cclnCode);
}
I would just like to ask why the "selectedClient" variable in the backing bean is NULL when executed by the "autoSelectClient();". But if I clicked the rows the "selectedClient" is already set.
As you can see in my backing bean I can get the value I want by getting the object inside the SelectEvent but I just want to know what is the cause of the difference.
Also if possible can any also suggest how to replicate the emulate the second scenario so that the "selectedClient" is already set before the "changeClient()" is invoked.
Using
JSF 2.1
PrimeFaces 3.5
Mojarra 2.1
try to send your datatable id in process of your ajax selection event like this:
<p:ajax event="rowSelect" listener="#{resendEmailController.changeClient}" update="_accountTableForm_accountTable" process="clientTable" />
Because when you call your event the real situation of your selection has no sent.

Resources