Update Primefaces DataTable only if validation succeeds - jsf

Let's say as for an example, I have some input fields like,
<p:panel id="panel" closable="false" toggleOrientation="horizontal" toggleable="true" header="New">
<p:focus context="panel"/>
<p:watermark for="txtCountryName" value="Enter a valid country name."/>
<p:watermark for="txtCountryCode" value="Enter a valid country code."/>
<p:messages id="systemMessages" globalOnly="true" redisplay="false" showDetail="true" showSummary="true" autoUpdate="false" closable="true"/>
<p:messages id="specificSystemMessages" for="paramId" globalOnly="false" redisplay="false" showDetail="true" showSummary="false" autoUpdate="false" closable="true"/>
<h:panelGrid id="panelGrid" columns="3" cellpadding="5">
<p:outputLabel for="txtCountryName" value="Country"/>
<p:inputText id="txtCountryName" value="#{countryManagedBean.txtCountryName}" label="Country name" required="true" maxlength="45">
<f:validateLength minimum="2" maximum="45"/>
</p:inputText>
<p:message for="txtCountryName" showSummary="false"/>
<p:outputLabel for="txtCountryCode" value="Country Code"/>
<p:inputText id="txtCountryCode" value="#{countryManagedBean.txtCountryCode}" required="true" maxlength="45" label="Country code">
<f:validateLength minimum="2" maximum="45"/>
</p:inputText>
<p:message for="txtCountryCode" showSummary="false"/>
<p:commandButton id="btnSubmit" update="dataTable panel messages" actionListener="#{countryManagedBean.insert}" icon="ui-icon-check" value="Save"/>
</h:panelGrid>
</p:panel>
And a DataTable as follows.
<p:panel id="dataTablePanel" toggleable="true" toggleOrientation="horizontal" closable="false" header="Data">
<p:dataTable id="dataTable" var="row" value="#{countryManagedBean}"
lazy="true"
pageLinks="10"
paginator="true"
sortMode="multiple"
resizableColumns="true"
sortOrder="descending"
editable="true"
filterEvent="keyup"
selection="#{countryManagedBean.selectedValues}"
rowsPerPageTemplate="5,10,15"
rows="10"
rowKey="#{row.countryId}"
rowIndexVar="rowIndex"
rowStyleClass="#{row.countryId eq countryManagedBean.id? 'selected-data-row' : null}"
editMode="row">
...
...
...
</p:dataTable>
</p:panel>
When this command button,
<p:commandButton id="btnSubmit" update="dataTable panel messages" actionListener="#{countryManagedBean.insert}" icon="ui-icon-check" value="Save"/>
is clicked, a row is added to the underlying database, if it satisfies all of the validation rules and the DataTable is updated using the update="dataTable panel messages" attribute.
I would like updating this DataTable if and only if all the validation criteria as specified on these input fields are satisfied and the row is actually created.
If anyone of these validation rules fails, then this DataTable should not be updated anymore which is quite unnecessary and causes some costly JPA criteria and/or JPQL queries to be executed. Is this possible, how?
It is Primefaces 3.5.

Try using remotecommand in that case.
Change your submit button as shown below.
<p:commandButton id="btnSubmit" action="#{countryManagedBean.insert}" icon="ui-icon-check" value="Save" oncomplete="handleRequest(xhr, status, args)"/>
Add p:remoteCommand as shown below.
<p:remoteCommand name="updateTable" update="dataTable">
This remote command will be used for updating your table.
And yes, add below js.
<script type="text/javascript">
function handleRequest(xhr, status, args) {
if(!args.validationFailed) {
updateTable();
}
}
</script>
HTH

try to add this code to your bakedbean countryManagedBean at the end of the insert function or whereever you check the validation.
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("validationFailed", "true");
This creates The callback param that you check with the javascript.

Related

p:remoteCommand update attribute VS p:commandButton update attribute?

I have the following block of code, when i update the "pickList" from the p:remoteCommand it gets updated.
<h:panelGrid columns="1">
<p:panel id="panel" header="Units"
style="margin-bottom:10px; background:#F3F2F2; margin-bottom:0px">
<p:pickList id="pickList"
value="#{AdminController.unitsPickListAll}" var="selectedUnit"
itemLabel="#{selectedUnit}" itemValue="#{selectedUnit}" />
</p:panel>
<h:panelGrid columns="1" styleClass="right-alignment">
<h:panelGroup>
<p:commandButton id="refereshButton" value="#{i18n.refresh}"
immediate="true" action="#{AdminController.getAllUnits}"
oncomplete="rc()" />
<h:outputText value="  " />
<p:commandButton id="saveButton" value="#{i18n.save}"
action="#{AdminController.updateUsedUnits}" />
</h:panelGroup>
</h:panelGrid>
</h:panelGrid>
<p:remoteCommand name="rc" update="panel" />
But when I use "update" attribute in the "refereshButton", the pickList does not get updated.
Below is the same code but without p:remoteCommand and with update attribute in refereshButton.
<h:panelGrid columns="1">
<p:panel id="panel" header="Units"
style="margin-bottom:10px; background:#F3F2F2; margin-bottom:0px">
<p:pickList id="pickList"
value="#{AdminController.unitsPickListAll}" var="selectedUnit"
itemLabel="#{selectedUnit}" itemValue="#{selectedUnit}" />
</p:panel>
<h:panelGrid columns="1" styleClass="right-alignment">
<h:panelGroup>
<p:commandButton id="refereshButton" value="#{i18n.refresh}"
immediate="true" action="#{AdminController.getAllUnits}"
update="pickList" />
<h:outputText value="  " />
<p:commandButton id="saveButton" value="#{i18n.save}"
action="#{AdminController.updateUsedUnits}" />
</h:panelGroup>
</h:panelGrid>
</h:panelGrid>
What this reason behind this behavior?
The reason you are getting different results is because you are doing different updates. You update panel from the remote command and pickList from the button.
Use update="panel" on your button to get the same result. This will also save you an Ajax request (and some server load).

<p:dataScroller> reloading automatically on entity edits

I have a p:datascroller configured to display a list of entities and lazy loading them upon clicking the more button.
<h:form id="investigationOperationsForm">
<p:dataScroller
value="#{investigationManagerBackingBean.lazyLoadedInvestigationOperations}"
var="investigationOperation" chunkSize="9" lazy="true"
rowIndexVar="test">
<f:facet name="header">
Scroll down to load investigations
</f:facet>
<h:panelGrid columns="2" style="width:100%"
columnClasses="logo,detail">
<p:commandLink oncomplete="PF('investigationDialogW').show()"
update="investigationEditorForm" immediate="true">
<f:setPropertyActionListener value="#{investigationOperation}"
target="#{investigationManagerBackingBean.selection}" />
<p:graphicImage alt="Investigation Operation"
url="/images/common/investigation-operation.png" />
</p:commandLink>
<!-- h:outputText value="#{investigationOperation.name}" /-->
<p:outputPanel id="pnl">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Name:" />
<h:outputText value="#{investigationOperation.name}"
style="font-weight: bold" />
<h:outputText value="Description:" />
<h:outputText value="#{investigationOperation.shortDescription}"
style="font-weight: bold" />
</h:panelGrid>
<p:draggable for="pnl" />
</p:outputPanel>
</h:panelGrid>
<f:facet name="loader">
<p:outputPanel
visible="#{investigationManagerBackingBean.lazyLoadedInvestigationOperations.rowCount gt 10}"
rendered="#{investigationManagerBackingBean.lazyLoadedInvestigationOperations.rowCount gt 10}">
<p:commandLink value="More" />
</p:outputPanel>
</f:facet>
</p:dataScroller>
</h:form>
In addition, I have a dialog that pops up when the p:commandLink oncomplete method is executed where I can update the value of the current selection and persist the changes.
<p:dialog id="investigationDialog"
header="#{msg['inv-manager.invDialog.header.title']}"
widgetVar="investigationDialogW" minWidth="400" minHeight="400"
resizable="false" position="center center" modal="true">
<p:panel id="investigationEditorPanel">
<h:form id="investigationEditorForm">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="name"
value="#{msg['inv-manager.invDialog.nameFieldLabel']}" />
<p:inplace id="nameInplaceEditor" editor="true">
<p:inputText
value="#{investigationManagerBackingBean.selection.name}"
id="name" required="true" immediate="true"
label="#{msg['inv-manager.invDialog.nameFieldInputLabel']}" />
</p:inplace>
<h:outputLabel for="shortDescription"
value="#{msg['inv-manager.invDialog.shortDescriptionFieldLabel']}" />
<p:inplace id="shortDescriptionInplaceEditor" editor="true">
<p:inputText
value="#{investigationManagerBackingBean.selection.shortDescription}"
id="shortDescription" required="true" immediate="true"
label="#{msg['inv-manager.invDialog.shortDescriptionFieldInputLabel']}" />
</p:inplace>
<h:outputLabel for="description"
value="#{msg['inv-manager.invDialog.descriptionFieldLabel']}" />
<p:inputTextarea id="description" required="false"
label="#{msg['inv-manager.invDialog.descriptionFieldInputLabel']}"
immediate="true"
value="#{investigationManagerBackingBean.selection.description}" />
<p:commandButton id="okButton"
value="#{msg['inv-manager.invDialog.okButton']}" type="submit"
partialSubmit="true" process="investigationEditorForm"
action="#{investigationManagerBackingBean.createOrUpdate()}"
onclick="dlg.hide();" />
</h:panelGrid>
</h:form>
</p:panel>
</p:dialog>
The backing bean is configured to be #ViewScoped and everything works as defined. However, upon update the values of the p:datascroller are reset and the load method of the lazy loading model is executed and the datascroller is repopulated with new values from the database.
I have no reference to the datascroller or its containing form in the p:dialog and am wondering why the datascroller is being updated automagically? What am I missing in the equation. Have I overlooked something or something specific to the p:datascroller model that I need to consider when following this approach?
Look forward to the expertise of the community in resolving this issue.
Many thanks in advance :)

how to reload p:dataGrid programmatically?

I have a datagrid with subscribe and unsubscribe option so the user can subscribe and unsubscribe and vise verse.
now I want to reload the datagrid after subscription or unsubscription
I load the data of the grid like that
#PostConstruct
public void init() {
packages = packagehelper.getAllPackages();
getCurrentUserSubscritions();
}
and here is the xhtml file
<h:form id="form">
<p:growl id="growl" showDetail="true" sticky="false" life="8000" />
<p:dataGrid var="package" value="#{packageView.packages}" columns="3"
>
<p:column>
<f:facet name="header">
Cars for Sale
</f:facet>
<p:panel header="#{package.id}" style="text-align:center">
<h:panelGrid columns="2" style="width:100%">
<p:graphicImage width="100px" name="images/#{package.imageurl}"/>
<h:outputText value="#{package.name}" />
<h:outputText value="#{package.value} EGP for #{package.duration} Days " />
<h:outputText value="#{package.description}" />
<p:commandButton ajax="true" update=":pack" value="Subscribe" rendered="#{!packageView.IsPackageActive(package.id)}" action="#{packageView.Subscribe()}" >
<f:setPropertyActionListener value="#{package.id}" target="#{packageView.packageID}" />
<f:setPropertyActionListener value="#{package.duration}" target="#{packageView.packageDuration}" />
</p:commandButton>
<p:commandButton action="#{packageView.Unsubscribe}" update=":pack" ajax="true" value="Cancel" rendered="#{packageView.UserHasPackage(package.id) and packageView.IsPackageActive(package.id) }">
<f:setPropertyActionListener value="#{package.id}" target="#{packageView.packageID}" />
<f:setPropertyActionListener value="#{package.duration}" target="#{packageView.packageDuration}" />
</p:commandButton>
</h:panelGrid>
</p:panel>
</p:column>
</p:dataGrid>
</h:form>
When an suscribe or unsuscribe action is completed, you should actualize the DataGrid trough its ID, it is, set an ID to the DataGrid and put such id in the update property of the buttons.
For example:
<p:dataGrid id="datalist" .../>
<p:commandButton action="#{packageView.Unsubscribe}" update="datalist" .../>
And when the action of the button is submited set the packages in null, so when the update action of the DataGrid update the packages they should be called again of the persistence or data base.
It is important to consider how to reference the elements in update property. You can see this answer

jsf required=true destroys setPropertyActionListener?

Using primefaces 4.0 and jsf 2.2.5
stmt.xhtml has 2 includes. IncludeDetail.xhtml and IncludeDuo.xhtml. IncludeDuo also includes IncludeDetail.
In IncludeDetail.xhtml the <ui:composition> Element owns no <form>, id-Attribute or any other special elements. Only <h:panelGrid>, <h:selectOneMenu> and <h:selectOneMenu>. Nothing special.
IncludeDuo.xhtml owns <p:layout> and <p:message> as child elements of <ui:composition>. Deeper inside the <p:layout> we find this piece of code:
<h:panelGrid columns="1" style="padding-left: 10px">
<h:outputText value="AS" />
<h:selectManyMenu value="#{regelBean.selectedASForNewElement}" required="true" style="height:115px">
<f:selectItems value="#{aSBean.elementList}" var="var" itemLabel="#{var.vaSl}"
itemValue="#{var.vaSl}" />
</h:selectManyMenu>
</h:panelGrid>
If I remove required="true" everything works as expected. If I leave it there, the following setPropertyActionListener won't do it's job anymore:
<h:form id="form1">
<p:dialog header="Neue Regel" widgetVar="newDuoDialog" resizable="false" id="newDuoDlg" showEffect="fade"
hideEffect="fade" modal="true" styleClass="newDialog" width="1220">
<ui:insert name="insertDuo">
<ui:include src="/includes/duoRegelStmt.xhtml" />
</ui:insert>
</p:dialog>
<p:growl id="msgs" showDetail="true" life="20000"/>
<div class="nvg-dataTable">
<p:dataTable id="dt1" var="tVar" value="#{stmtBean.elementList}"
scrollable="false" styleClass="nvg-mainTable" paginator="true"
paginatorAlwaysVisible="false" rows="10"
rowsPerPageTemplate="10,25,100" paginatorPosition="bottom"
currentPageReportTemplate="({startRecord}-{endRecord} von {totalRecords})"
emptyMessage="Keine Statements gefunden" filteredValue="#{stmtBean.filteredElements}">
<p:column styleClass="padding2" style="width:6%">
<p:commandButton value="?" update=":dlgForm"
oncomplete="PF('detDialog').show()" icon="" title="Detail">
<f:setPropertyActionListener value="#{tVar}" target="#{stmtBean.selectedElement}" />
</p:commandButton>
<p:commandButton value="N" update=""
oncomplete="PF('newDuoDialog').show()" icon="" title="Neue Regel mit diesem Statement als Grundlage">
<f:setPropertyActionListener value="#{tVar}" target="#{stmtBean.selectedElement}" />
</p:commandButton>
[ ... ]
Is this a bug or am I misusing sth?
This is expected behaviour: As you are setting the property on submit of the form the property is only set when the form is successfully submitted, which is not the case when validation fails i.e. a required field is empty.
Use process="#this" on the p:commandButton so the form is not submitted. This should work for you as you just want to open the dialog and set the property.

update primefaces or jsf view after ajax call on submit button

I am trying to update a primefaces form (wizard-first step) after an ajax command button request with no success. The command button that makes the actual ajax call is on a dialog. I would like after submitting the request to force my view to refresh.
The command button deletes a record from a datatable. It works fine, record is deleted but when dialog is hidden the datatable keeps displaying the deleted record. I would like to force it somehow to refresh. Any ideas? Could I do it from my backing bean reviewManagerBean.deleteProtocol() method?
Here is the code (my BackBean is viewScoped):
<h:form id="reviewManagerForm">
...
<pe:masterDetail id="masterDetail" level="#{reviewManagerBean.currentLevel}" showBreadcrumb="false" selectLevelListener="#{reviewManagerBean.levelListener}" >
<f:facet name="header" >
<h:panelGroup layout="block" style="margin-top: 10px;" >
<h:panelGroup styleClass="levelTitle ui-state-default ui-corner-all wizard-breadcrumbs#{reviewManagerBean.currentLevel eq 1 ? 'ui-state-hover' : ''}">
<h:outputText value="1: Protocol picker"/>
</h:panelGroup>
...
<p:messages id="mainMessagesPanel" showDetail="true" closable="true" />
</h:panelGroup>
</f:facet>
<pe:masterDetailLevel level="1">
<p:panel id="panel1" header="List of available protocols">
<p:dataTable id="protocolsDataTable" var="cRProtocol" rowKey="#{cRProtocol.revProtId}" value="#{reviewManagerBean.cRReviewProtocolList}"
widgetVar="protocolsTable"
...
selection="#{reviewManagerBean.selectedReviewProtocol}"
selectionMode="single" >
...
<p:ajax event="rowSelect" listener="#{reviewManagerBean.setSelectedRow}" />
<p:ajax event="rowUnselect" listener="#{reviewManagerBean.unsetSelectedRow}"/>
...
<p:column sortBy="#{cRProtocol.revProtTitle}" headerText="Title" style="width:200px;text-align:center;">
<h:outputText value="#{cRProtocol.revProtTitle}" />
</p:column>
...
<p:column>
<p:commandButton value="Delete" onclick="dlg5.show()"
update=":reviewManagerForm:deleteSingleProtocol"
disabled="#{reviewManagerBean.checkifProtocolIsOpen(cRProtocol)}"
ajax="true" process=":reviewManagerForm:deleteSingleProtocol" />
</p:column>
</p:dataTable>
</p:panel>
...
<p:dialog id="dialog-deleteprotocol" header="Delete Image Type" widgetVar="dlg5" dynamic="true" modal="true" resizable="false">
<p:panelGrid id="deleteSingleProtocol">
<p:row>
<p:column>
<h:outputText value="Id:" style="font-weight:bold; padding-right:10px" />
</p:column>
<p:column>
<h:outputText value="#{reviewManagerBean.selectedReviewProtocol.revProtId}" />
</p:column>
</p:row>
...
<p:column>
<p:commandButton id='protocolDelete'
value='Delete'
action='#{reviewManagerBean.deleteProtocol()}'
ajax="true"
onclick="dlg5.hide()" icon="ui-icon-disk"
update=":reviewManagerForm:protocolsDataTable"
process=":reviewManagerForm:deleteSingleProtocol" />
</p:column>
</p:row>
</p:panelGrid>
</p:dialog>
Your datatable should be re-rendered properly, you would have gotten an exception otherwise (something like component with id :reviewManagerForm:protocolsDataTable could not be found).
This means that #{reviewManagerBean.cRReviewProtocolList} will get called again. You need to remove the item from that list. This is appropriately done from #{reviewManagerBean.deleteProtocol}.
When #{reviewManagerBean.cRReviewProtocolList} is called after the removal, your datatable will get updated.

Resources