commandButton inside p:datatable is not working [duplicate] - jsf

This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 5 years ago.
I know there are similiar questions here but none of the solutions worked for me. Before I used primeface datatable every thing was working perfectly but I needed paginator of primefaces so I switched to primeface's datatable instead of default jsf datatable. The problem is I have a column named action where somebuttons will be placed. For instance one of the button is "Buy". When I click this button the program will take from product database and add it to cart database. This is working perfectly with jsf datatable. But in primefaces datatable it's either not doing anything or gives null point exception. This is my xhtml file. It gives null point exception if I click buy button for the first item in the datatable if I click for anything else it's not doing anything.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Shopping</title>
<h:outputStylesheet library="css" name="Product-table.css" />
</h:head>
<body>
<h:outputLabel value="Welcome #{loginBean.name}"></h:outputLabel>
<br></br>
<br></br>
<div style="width: 100%;">
<div style="width: 75%; float: left;">
<h2>Products</h2>
<h:form>
<p:dataTable var="product" value="#{databaseBean.products}"
filteredValue="#{databaseBean.filteredProducts}"
widgetVar="productWidget" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink}
{PreviousPageLink} {PageLinks} {NextPageLink}
{LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15,20,25">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search:" />
<p:inputText id="globalFilter"
onkeyup="PF('productWidget').filter()" style="width:150px"
placeholder="Search text" />
</p:outputPanel>
</f:facet>
<p:column headerText="Id" filterBy="#{product.id}" filterMatchMode="contains">
<h:outputText value="#{product.id}" />
</p:column>
<p:column headerText="Name" filterBy="#{product.name}" filterMatchMode="contains" >
<h:outputText value="#{product.name}" />
</p:column>
<p:column headerText="Price" filterBy="#{product.price}" filterMatchMode="contains">
<h:outputText value="#{product.price}" />
</p:column>
<p:column headerText="Quantity" filterBy="#{product.quantity}" filterMatchMode="contains">
<h:outputText value="#{product.quantity}" />
</p:column>
<p:column headerText="Category" filterBy="#{product.category}" filterMatchMode="contains" >
<h:outputText value="#{product.category}" />
</p:column>
<p:column>
<f:facet name="header">Action</f:facet>
<h:form>
<h:commandButton type="submit" value="#{product.id}"
name="buyLink" action="#{databaseBean.addtoCart}">
<f:param name="productId" value="#{product.id}" />
<f:param name="userId" value="#{loginBean.name}" />
</h:commandButton>
</h:form>
</p:column>
</p:dataTable>
</h:form>
</div>
<div style="width: 25%; float: right;">
<h2>Cart</h2>
<p:dataTable value="#{databaseBean.cart}" var="product"
styleClass="product-table" headerClass="product-table-header"
rowClasses="product-table-odd-row,product-table-even-row">
<p:column>
<f:facet name="header">Product ID</f:facet>
#{product.productId}
</p:column>
<p:column>
<f:facet name="header">Quantity</f:facet>
#{product.quantity}
</p:column>
</p:dataTable>
</div>
</div>
<h:form>
<h:commandButton action="#{loginBean.logout}" value="logout"></h:commandButton>
</h:form>
This is the method that the button should call. As I said it's working perfectly in default jsf datatable so I do not think anything is wrong with the java code but the problem is in xhtml file.
public void addtoCart(){
//userId = getUserID();
ManageCart MC = new ManageCart();
FacesContext fc = FacesContext.getCurrentInstance();
Map<String,String> params =
fc.getExternalContext().getRequestParameterMap();
String productIdString = params.get("productId");
int productId = Integer.parseInt(productIdString);
MC.addToChart(userId, productId, 1);
cart = mc.listCart(userId);
products = mp.listProducts();
}
I would really appreciate any help.
Thank you.

I found the solution. I needed to delete tag <h:form></h:form> from the code block of action column and it works.

Related

AJAX errors on Primefaces page

I am trying to emulate the Primefaces Showcase to have a result set that uses filtering and a row expansion. I get errors whenever I try either one. The page loads without errors. In the code example, I have stripped the filtering to isolate the issue. It appears that any time an AJAX request is triggered it will give an error. The error is triggered when trying to use the row expansion as that uses an AJAX call to fetch the expanded row.
We are using Primefaces 8.0 on IBM Rad local server (Eclipse). Result set is pulled from DB2 using Hibernate and that part works.
Please help by suggesting why the AJAX fails everytime?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</h:head>
<h:body>
<ui:composition template="/template/maintemplate.xhtml">
<ui:define name="title">Search Results</ui:define>
<ui:define name="content">
<h:form id="formId">
#{searchResultsBean.init}
<p:dataTable id="parameterList" var="data"
value="#{searchResultsBean.parameterList}">
<p:column style="width:16px">
<p:rowToggler />
</p:column>
<p:column value="#{data.companyId}" >
<f:facet name="header">
<h:outputText value="Company ID" />
</f:facet>
<h:outputText value="#{data.companyId}" />
</p:column>
<p:column value="#{data.companyName}" >
<f:facet name="header">
<h:outputText value="Company Name" />
</f:facet>
<h:outputText value="#{data.companyName}" />
</p:column>
<p:column value="#{data.alertNumber}">
<f:facet name="header">
<h:outputText value="Alert Number" />
</f:facet>
<h:outputText value="#{data.alertNumber}" />
</p:column>
<p:column value="#{data.comment}">
<f:facet name="header">
<h:outputText value="Comment" />
</f:facet>
<h:outputText value="#{data.comment}" />
</p:column>
<p:rowExpansion>
<p:panelGrid columns="2" columnClasses="label,value"
style="width:300px">
<h:outputText value="Company ID" />
<h:outputText value="#{data.companyId}" />
<h:outputText value="Company Name" />
<h:outputText value="#{data.companyName}" />
<h:outputText value="Alert #" />
<h:outputText value="#{data.alertNumber}" />
<h:outputText value="Alert Description" />
<h:outputText value="$#{data.alertNumber}" />
</p:panelGrid>
</p:rowExpansion>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
Error received in console:
ReferenceError: ajaxWaitCursorOn is not defined
Specific error in primefaces generated javascript:
$(function(){PrimeFaces.cw("AjaxStatus","widget_j_id878804506_56ad391e",{id:"j_id878804506_56ad391e",delay:0,start:function(){ajaxWaitCursorOn()},success:function(){ajaxWaitCursorOff()}});});
Note 1: We tried changing it to use #Inject instead of calling the init method and got the same result.
Note 2: We verified that jQuery is loaded using a simple alert in the console.
The issue was this line above: template="/template/maintemplate.xhtml
It was loading a template file. We didn't make this, but copied it from another project. The template file had this line in for some reason: <p:ajaxStatus onstart="ajaxWaitCursorOn()" onsuccess="ajaxWaitCursorOff()" />
I am not sure if this answer provides value to anyone except for this: Check your template files if you have any.

How to reset <p:selectOneMenu> to default inside a <p:dialog> [duplicate]

This question already has answers here:
How to show details of current row from p:dataTable in a p:dialog and update after save
(1 answer)
p:resetInput does not reset the p:dialog when it is reopened
(1 answer)
Closed 2 years ago.
I have a problem with resetting the values of a <p: selectOneMenu> component that is housed within a <p: dialog> component, it turns out that I have declared the <p: dialog> on the same page where I show it with a < p: commandButton> and I want that when I finish editing the data and press the button again, the component <p: selectOneMenu> comes out with the initial values, and this is not happening, instead it keeps the selection I made previously. Thank you very much for the help you can give me. this is the code of the page. I don't think it is necessary to put the code for the backing beans but they do need it without problem.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<body class="areaContenido">
<ui:composition template="../resources/template/tgeneral.xhtml">
<ui:define name="content" class="areaContenido">
<h:form id="guser">
<p:growl id="msgs" showDetail="true" />
<p:dataTable var="usermio" value="#{userBean.lazyModel}" paginator="true" rows="10" class="FuentTable" rowKey="#{usermio.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="userTable" lazy="true">
<f:facet name="header">
<p:outputLabel value="Gestión de usuarios del sistema" style="font-weight: bold; text-align: center;"/>
</f:facet>
<p:column headerText="Id" width="5%">
<h:outputText value="#{usermio.id}" />
</p:column>
<p:column headerText="Usuario" width="15%" >
<h:outputText value="#{usermio.usuario}" />
</p:column>
<p:column headerText="Nombre" width="20%">
<h:outputText value="#{usermio.nombre}"/>
</p:column>
<p:column headerText="Apellidos" width="25%">
<h:outputText value="#{usermio.apellidos}" />
</p:column>
<p:column headerText="Rol" width="15%">
<h:outputText value="#{usermio.rol.rol}" />
</p:column>
<p:column headerText="Opt" width="15%">
<p:commandButton value="" update=":guser:userEdit" onclick="PF('userDial').show()" icon="ui-icon-pencil" ajax="true" >
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
<p:commandButton value="" update=":guser:userEdit" onclick="PF('cd').show()" icon="ui-icon-key" ajax="true">
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
<p:commandButton value="" update=":guser:userEdit" onclick="PF('cd').show()" icon="ui-icon-cancel" ajax="true">
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
</p:column>
<f:facet name="footer">
<p:button icon="ui-icon-plus" id="nuevo" value="Nuevo" href="/glitic/adm/register.xhtml" title="Nuevo usuario" />
</f:facet>
</p:dataTable>
<p:dialog header="Edición de datos" widgetVar="userDial" modal="true" showEffect="bounce" hideEffect="fade" resizable="false" class="Fuent" responsive="true" >
<p:outputPanel id="userEdit" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty userBean.selecteduser}" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{userBean.selecteduser.id}" />
<h:outputText value="Usuario" />
<p:inputText value="#{userBean.selecteduser.usuario}" id="username" required="true" requiredMessage="Se necesita el usuario"/>
<h:outputText value="Nombres" />
<p:inputText value="#{userBean.selecteduser.nombre}" id="nombre" required="true" requiredMessage="Se necesita el nombre"/>
<h:outputText value="Apellidos" />
<p:inputText value="#{userBean.selecteduser.apellidos}" id="apellidos" required="true" requiredMessage="Se necesita los apellidos"/>
<h:outputText value="Rol" />
<p:selectOneMenu id="sroles" value="#{userBean.selectedrol}" style="width:160px" effect="fold" >
<f:selectItem itemLabel="Escoja un rol para el usuario" itemValue="" />
<f:selectItems value="#{userBean.roles}" var="xroles" itemLabel="#{xroles.rol}" itemValue="#{xroles.id}" />
</p:selectOneMenu>
<h:outputText value="Guardar cambios:" />
<p:commandButton value="Guardar" action="#{cttobean.NVenta()}" ajax="false"/>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>

p:dataTable not updated by PrimeFaces.current().ajax().update

I am starting developpment with JSF and PrimeFace datatable. I have prepared the following xhtml page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Find Capital of Countries</title>
</h:head>
<h:body>
<h:form id="FrmTest">
<p:dataTable id="ListSites" value="#{testing.SiteSearch()}" var="lst" editable="true">
<f:facet name="header">
List of Sites
</f:facet>
<p:column>
<f:facet name="header">
Site Code
</f:facet>
#{lst.stCode}
</p:column>
<p:column headerText="Site Description">
<h:outputText value="#{lst.stDescription}" />
</p:column>
<p:column headerText="is Active">
<div style="text-align: center;">
<p:selectBooleanCheckbox value="#{lst.stActive}" />
</div>
</p:column>
<p:column>
<f:facet name="header">
Site Active
</f:facet>
<div style="text-align: center;">
<h:outputText value= "#{lst.stActive}" />
</div>
</p:column>
<p:column>
<f:facet name="header">
Modified By
</f:facet>
#{lst.modifiedBy}
</p:column>
<p:column>
<f:facet name="header">
Modification Date
</f:facet>
#{lst.modifiedDate}
</p:column>
<p:column>
<f:facet name="header">
Has Error
</f:facet>
#{lst.hasError}
</p:column>
<p:column>
<f:facet name="header">
Error Description
</f:facet>
#{lst.errorDescription}
</p:column>
<p:column>
<f:facet name="header">
Row State
</f:facet>
#{lst.rowState}
</p:column>
</p:dataTable>
<h:outputLabel value="Enter Country Name:"/>
<h:inputText id="country" binding="#{testing.country}"
valueChangeListener="#{testing.findCapitalListener}"
immediate="true"
onchange="document.getElementById('findcapital').click();" />
<br/>
<br/>
<h:outputLabel value="Capital is: " />
<h:inputText id="capital" binding="#{testing.capital}" immediate="true"/>
<br/>
<br/>
<h:commandButton value="Submit" partialSubmit="true" />
<div style="visibility: hidden" >
<h:commandButton id="findcapital" value="findcapital" partialSubmit="true" immediate="true" />
</div>
</h:form>
</h:body>
</html>
I want entry made in text box named country to update datatable named ListSites. The associated listener is called (system.out.println made) but the primeface update is not made. Here is the listener:
```
public void findCapitalListener(ValueChangeEvent cdl) {
String country = cdl.getNewValue().toString();
System.out.println("Country is : " + country);
StringBuilder capitalCountry = new StringBuilder();
findCapital(country, capitalCountry);
capital.setValue(capitalCountry.toString());
siteDto = listSiteDto.get(0);
siteDto.setStDescription(capitalCountry.toString());
listSiteDto.set(0, siteDto);
PrimeFaces.current().ajax().update("FrmTest:ListSites");
//System.out.println("Capital is : " + capital.getValue());
//System.out.println("New DTO Description : " + siteDto.getStDescription());
System.out.println("New list Description : " + listSiteDto.get(0).getStDescription());
}
```
The problem was due to the fact that the function populating the datatable (SiteSearch()) was retrieving data from the database. At that stage I wanted to refresh the page display before updating the database. I replaced the function by the list getter, things are working properly now.

How to filter on primefaces?

I'm using a modal window to select a value. After i make a selection and open the modal window again. I want the modal list be filtered on the selectedValue.
It goes back to the front page.
and if open modal again and select 'ABC', it should look like this:
this is look up and which list should be put in modal xhtml:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<p:panel id="dialog-content">
<h:form id="accountLookUpModal" style="width: 777px">
 
<p:panelGrid id="Info" columns="2" columnClasses="labelColumn,fieldColumn">
<!-- TYPE -->
<h:outputLabel id="AccountType" for="accountType" value="#{message['field.type']}" />
<p:selectOneMenu id="accountType" rendered="#{not empty account.criteria}" value="#{account.criteria.accountType}" converter="#{enumerationConverter}" disabled="#{account.disableLookUp}">
<p:ajax event="change" listener="#{account.filterOnType(true)}" update="#form, :dataTableForm"/>
<f:selectItems itemLabelEscaped="true" value="#{enumerationBean.getaccountTypeList()}" var="c" itemLabel="#{message[c.bundleKey]}" itemValue="#{c}"/>
</p:selectOneMenu>
</p:panelGrid>
</h:form>
<h:form id="dataTableForm" prependId="false" style="width:777px;">
<!-- INCLUDE Account Table -->
<ui:include src="/includes/accountLookUp.xhtml">
<ui:param name="PANEL_ID" value="accountActionPanel" />
<ui:param name="DT_ID" value="accountTable" />
<ui:param name="DT_DATA" value="#{account.accountTableLookUp}" />
<ui:param name="CR_BEAN" value="#{accountBean}" />
</ui:include>
</h:form>
</p:panel>
</ui:composition>
This is the xhtml used to select the update the list:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<p:dataTable id="#{DT_ID}" var="acc" emptyMessage="" value="#{DT_DATA.values}" rowIndexVar="index"
paginator="true" selection="#{DT_DATA.selectedValues}" rows="8" paginatorPosition="top"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
editable="false" lazy="true" sortBy="#{acc.name}" sortOrder="ascending"
liveResize="true" filterDelay="100">
<p:ajax event="filter" listener="#{DT_DATA.onFilter}" />
<p:ajax event="rowToggle" listener="#{account.expandLookUp(acc)}" immediate="true"/>
<p:column styleClass="ui-column-rowtoggler" exportable="false">
<p:rowToggler id="cdtlu#{DT_ID}RT"/>
</p:column>
<!-- filterBy="#{acc.name}" -->
<p:column id="accountName" sortBy="#{acc.name}" filterBy="#{acc.name}" >
<f:facet name="header">
<h:outputText id="cu#{DT_ID}accountName" value="#{message['field.name']}" />
</f:facet>
<h:outputText id="cu#{DT_ID}accountName" value="#{acc.name}"/>
</p:column>
<!-- filterBy="#{acc.city}" -->
<p:column id="accountCity" sortBy="#{acc.city}" filterBy="#{acc.city}" >
<f:facet name="header">
<h:outputText id="cu#{DT_ID}accountCity" value="#{message['field.city']}" />
</f:facet>
<h:outputText id="cu#{DT_ID}accountCity" value="#{acc.city}" />
</p:column>
<!-- filterBy="#{acc.countryCode}" -->
<p:column id="accountCountry" sortBy="#{acc.countryCode}" filterOptions="#{enumerationBean.accountList}" filterBy="countryCode" >
<f:facet name="header">
<h:outputText id="cu#{DT_ID}CountryCode" value="#{message['field.countryCode']}" />
</f:facet>
<h:outputText id="cu#{DT_ID}TCountryCode" value="#{message[acc.countryCode.bundleKey]}" />
</p:column>
<p:column id="sel" styleClass="ui-column-rowtoggler">
<f:facet name="header">
<h:outputText id="cu#{DT_ID}Sel" value="#{message['common.sel']}" />
</f:facet>
<p:commandButton action="save-dialog" id="cu#{DT_ID}BtnSel"
actionListener="#{companySearchBean.updateCompanyOwner(acc)}"
icon="ui-icon ui-icon-e-w" >
</p:commandButton>
</p:column>
</p:dataTable>
</ui:composition>
Now i would like to filter with 'name' so that it looks it last picture. I used filterValue but then filterBy doesn't work properly and it produces null. In the nutshell if I select 'ABC' and then open the modal again. it should only contain list contain name like 'ABC'.
I'm new to prime faces so any help would be appreciated. Also i apologize for terrible diagrams.

datatable <p:ajax> exception

Trying to do some simple primefaces datatable ajax work and get the following exception:
javax.servlet.ServletException: /default.xhtml #17,76 Parent not an instance of ClientBehaviorHolder: org.primefaces.component.datatable.DataTable#5fdb7adc
I'm using primefaces 3.3.1. My .xhtml code is here (I copied some of it from the primefaces site to see if I could get this working), anybody got any ideas?
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" >
<h:head>
</h:head>
<h:body>
<center>
<h:form id="form">
<p:dataTable id="personTable" var="client" value="#{tableBean.persons}"
selection="#{tableBean.person}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{tableBean.onUserSelect}"
update=":form:displayf" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{tableBean.onUserUnselect}"
update=":form:displayf" />
<f:facet name="header">
Click "View" button after selecting a row to see details
</f:facet>
<p:column headerText="Name">
#{client.name}
</p:column>
<p:column headerText="Address">
#{client.address}
</p:column>
<p:column headerText="Phone" >
#{client.phone}
</p:column>
</p:dataTable>
<p:dialog id="dialog" header="Car Detail" widgetVar="carDialog" resizable="false"
showEffect="explode" hideEffect="explode">
<h:panelGrid id="displayf" columns="2" cellpadding="4">
<h:outputText value="Name:" />
<h:outputText value="#{tableBean.person.name}" />
<h:outputText value="Address:" />
<h:outputText value="#{tableBean.person.address}" />
<h:outputText value="Phone:" />
<h:outputText value="#{tableBean.person.phone}" />
</h:panelGrid>
</p:dialog>
</h:form>
</center>
</h:body>
</html>

Resources