How to rendered <p:selectOneMenu> [duplicate] - jsf-2

This question already has an answer here:
Ajax update/render does not work on a component which has rendered attribute
(1 answer)
Closed 7 years ago.
I am unable to rendered a selectOneMenu but only to disable the item
for example this is working:
<p:panel header="Field Chooser">
<h:panelGrid columns="2" cellpadding="5">
<p:selectOneMenu id="l1" value="#{acqBean.gb1}">
<f:selectItem itemLabel="Group By" itemValue="" />
<f:selectItems value="#{acqBean.level1}" />
<p:ajax update="l2" listener="#{acqBean.handleGroupChange}"/>
</p:selectOneMenu>
<p:selectOneMenu id="l2" value="#{acqBean.gb2}" disabled="#{acqBean.renderLevel2}">
<f:selectItems value="#{acqBean.level2}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
</p:panel>
public void handleGroupChange() {
if (gb1 != null && !gb1.equals("")) {
level2 = level2Data.get(gb1);
renderLevel2 = false;
} else {
level2 = new HashMap<String, String>();
renderLevel2 = true;
}
}
and this one not:
<p:selectOneMenu id="l2" value="#{acqBean.gb2}" rendered="#{acqBean.renderLevel2}">
<f:selectItems value="#{acqBean.level2}" />
</p:selectOneMenu>
Any advice please
Thanks

You can't ajax-update a component which is by itself conditionally rendered. You can only ajax-update a component which is always rendered. The simple reason is, when the component is not rendered, then there's basically nothing in the resulting HTML code which can be selected and manipulated by JavaScript based on the ajax response.
So, put the <p:selectOneMenu> with the rendered attribute in for example a <h:panelGroup> without the rendered attribute and refer it instead in your ajax update.
<p:selectOneMenu id="l1" value="#{acqBean.gb1}">
<f:selectItem itemLabel="Group By" itemValue="" />
<f:selectItems value="#{acqBean.level1}" />
<p:ajax update="l2group" listener="#{acqBean.handleGroupChange}"/>
</p:selectOneMenu>
<h:panelGroup id="l2group">
<p:selectOneMenu id="l2" value="#{acqBean.gb2}" rendered="#{acqBean.renderLevel2}">
<f:selectItems value="#{acqBean.level2}" />
</p:selectOneMenu>
</h:panelGroup>
See also:
Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?

Related

DataTable clearFilter() not working properly

I have a complicate JSF that contain dataTable with filter in each one of the columns.
In order to make sure that the generate button will fetch all the data first I need to clear all the filters when the user press the button.
I try to do use onclick but then I couldn’t see the blockUI I also try on complete (ajax) but again it was not working properly with all the other items (blockUI ,message).
I decided to try to clear the filters via server side but only dataTable.reset() is working.
I have no more ideas how to clean the filters ???
Is this API working ?
Appreciate your help
Thanks
<h:panelGrid columns="1" style="width: 100%">
<p:panel id="vt-panel">
<h:panelGrid columns="5" cellpadding="2" >
<h:outputText value="Start Date" />
<p:calendar id="vt-start" value="#{vtRepBean.startDate}" binding="#{startDateComponent}" maxlength="9" size="9" pattern="dd-MMM-yy" title="dd-MMM-yy" required="true" maxdate="#{vtRepBean.endDate}">
<p:ajax event="dateSelect" listener="#{vtRepBean.handleStartDateSelect}" update=":mainForm:vt-end"/>
</p:calendar>
<h:outputText value="End Date" />
<p:calendar id="vt-end" value="#{vtRepBean.endDate}" maxlength="9" size="9" pattern="dd-MMM-yy" title="dd-MMM-yy" required="true" mindate="#{vtRepBean.startDate}">
<p:ajax event="dateSelect" listener="#{vtRepBean.handleEndDateSelect}" update=":mainForm:vt-start"/>
</p:calendar>
<p:commandButton
id="genVtBtn"
value="Generate"
actionListener="#{vtRepBean.handleVTGenerateButton}"
update=":mainForm:vt-panel,:mainForm:vt-panel-table">
</p:commandButton>
</h:panelGrid>
</p:panel>
</h:panelGrid>
<p:growl id="vt_message" showDetail="true" autoUpdate="true"/>
<h:panelGroup id="vt-panel-table">
<p:dataTable id="vtDataTable"
widgetVar="vtWidget"
var="reportObject"
value="#{vtRepBean.reportObjectsList}"
rendered="#{vtRepBean.renderVTReport}"
filteredValue="#{vtRepBean.filteredVTList}"
paginator="true"
paginatorPosition="bottom"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="50,100,200"
rows="50"
style="width: 100%">
<p:columnGroup type="header">
<p:row>
<p:column colspan="5" headerText="VT request"/>
<p:column colspan="1" headerText="Dis" />
</p:row>
<p:row>
<p:column headerText="CREATE DATE" sortBy="#{reportObject.log.createDate}" filterBy="#{reportObject.log.createDate}" filterMatchMode="contains"/>
<p:column headerText="IP" sortBy="#{reportObject.log.ip}" filterBy="#{reportObject.log.ip}" filterMatchMode="contains"/>
</p:row>
</p:columnGroup>
<p:column >
<h:outputText value="#{reportObject.log.createDate}"/>
</p:column>
<p:column >
<h:outputText value="#{reportObject.log.ip}"/>
</p:column>
</p:dataTable>
<p:commandLink rendered="#{vtRepBean.renderVTReport}" ajax="false" onclick="PrimeFaces.monitorDownload(showStatus, hideStatus)">
<p:graphicImage value="resources/images/excel.png" title="excel" style="border-color: white"/>
<p:dataExporter id="xlsReport"
type="xls"
target="vtDataTable"
fileName="VTReport"
postProcessor="#{vtRepBean.postProcessXLS}"/>
</p:commandLink>
</h:panelGroup>
<p:blockUI widgetVar="blockVTPanel" trigger="genvtBtn" block="vt-panel">
<div class="disable-scroll">
<p:graphicImage value="resources/images/ajax-loader.gif"/>
</div>
</p:blockUI>
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("mainForm:vtDecomDataTable");
if (!dataTable.getFilters().isEmpty()) {
logger.info("dataTable.getFilters().isEmpty() :" + dataTable.getFilters().isEmpty());
dataTable.getFilters().clear();// not working
dataTable.getFilteredValue().clear();// not working
dataTable.setFilteredValue(null);// not working
dataTable.setFilters(null);// not working
dataTable.setFilterMetadata(null);// not working
dataTable.reset();// working
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.update("mainForm:vtDecomDataTable");
}
To clear all the inputs of the filters you can do it by javascript:
<p:commandButton onclick="PF('vtWidget').clearFilters()" />
vtWidget is the widgetVar of the datatable.
Basically clearFilters() will clear the fields for you and call filter(), and the filter function would update your datatable, which in turns will empty the filtered list.
Note: This would work only if the filters were inputText. If you have custom components then you should implement your own clear based on the components that you have.
Sometimes if you have custom components, you need to empty the filtered list manually, as you did in the comments!
This is how i solved my problem.
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("PF('widget_orderDataTable').clearFilters()");
Hope its help.
For clearing custom filters you can use primefaces resetInput, along with clearFilters() discussed in other answers, and a custom actionListener method. See code snippets below:
<p:dataTable id="dataTable" widgetVar="dataTable"
value="#{bean.listOfObjects}" var="object">
<p:commandButton value="Clear All Filters"
onclick="PF('dataTable').clearFilters()"
actionListener="#{controller.clearAllFilters}"
update="dataTable">
<p:resetInput target="dataTable" />
</p:commandButton>
Controller.java
public void clearAllFilters() {
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:dataTable");
if (!dataTable.getFilters().isEmpty()) {
dataTable.reset();
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.update("form:dataTable");
}
}
I hope this helps anyone looking to clear custom filters.
For Primefaces 7 and above, use the following:
public void clearAllFilters() {
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:dataTable");
if (!dataTable.getFilters().isEmpty()) {
dataTable.reset();
PrimeFaces.current().ajax().update("form:dataTable");
}
}

Show dialog when the input data is validated <p:confirmDialog> [duplicate]

This question already has an answer here:
How to display dialog only on complete of a successful form submit
(1 answer)
Closed 6 years ago.
For my school project I have to realize a mini website where I use primefaces framework. In a form I want after pressing the Save button two things:
1 - Validate the data entered. that's why I put
<p:message for="date" /> and <p:message for="zone" />
As the values ​​are not correct, the dialog box should not be displayed.
2 - When all data is correct, and I click Save, I want to display my dialog box.
Now I can not. Can you help me? I use version 4 primefaces.
<h:form>
<p:panel id="panel" header="Create" style="margin-bottom:10px;border-color:blueviolet" >
<p:messages id="messages" />
<h:panelGrid columns="3">
<h:outputLabel for="date" value="Date : *" />
<p:calendar locale="fr" id="date" value="#{newBusinessCtrl.exercice.debut}" required="true" label="date" showButtonPanel="true"/>
<p:message for="date" />
<h:outputLabel for="zone" value="Zone Monétaire: *" />
<p:selectOneMenu id="zone" value="#{newBusinessCtrl.exercice.zoneChoice}" >
<f:selectItem itemLabel="Choice " itemValue="" />
<f:selectItems value="#{newBusinessCtrl.exercice.zones}" var="azone"
itemLabel="#{azone}" itemValue="#{azone}" >
</f:selectItems>
<p:message for="zone" />
</p:selectOneMenu>
<p:message for="zone" />
</h:panelGrid>
</p:panel>
<p:commandButton update="panel" value="Save" icon="ui-icon-check" style="color:blueviolet" onclick="choice.show()"/>
<p:confirmDialog message="Would you like to create accounts automatically ?"
header="Account creation" severity="alert"
widgetVar="choice" appendTo="#(body)">
<p:button outcome="personalizeAccount" value="Personalize" icon="ui-icon-star" />
<p:button outcome="autoAccount" value="Continue" icon="ui-icon-star" />
</p:confirmDialog>
Just show the dialog in Backing Bean like this:
Page:
<p:commandButton update="panel" value="Save"
icon="ui-icon-check"
style="color:blueviolet"
action="#{newBusinessCtrl.showDlg('choice')}"/>
Backing Bean:
public void showDlg(String dlgName){
RequestContext.getCurrentInstance().execute(dlgName+".show()");
}
Once the validation failed, the action won't execute and thus the dialog will not show.
If validation hasn't failed. PrimeFaces puts a global args object in the JavaScript scope which in turn has a boolean validationFailed property. You can check it before showing the dialog So you can use it this way:
<p:commandButton value="save" oncomplete="if (args && !args.validationFailed) saveDialog.show()"/>

PrimeFaces second dialog window not opening from first dialog

I have a issue trying to open a second dialog from the first dialog. The first dialog opens fine but the second dialog does not seem to open at all. I have tried with the form tag inside and outside of the dialog but get neither seems to open the dialog. On clicking the OPen dialog button from the first nothing seems to happen. I am using PrimeFaces 3.5.
Code for dialog is as below
<p:dialog id="dialog" header="New Submission" widgetVar="dlg" resizable="false" modal="true" closable="true">
<h:form id="createDialogForm">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="projectDropDown" value="Project:" />
<h:selectOneMenu id="projectDropDown" value="#{newSubmissionBean.submission.project}" required="true">
<f:selectItem itemLabel="Choose project" noSelectionOption="true" />
<f:selectItems value="#{newSubmissionBean.projectEntities}" var="project" itemLabel="#{project.name}" itemValue="#{project}" />
</h:selectOneMenu>
<f:facet name="footer">
<p:commandButton id="createButton" value="Create" update=":newSubmissionForm :createDialogForm"
actionListener="#{newSubmissionBean.createSubmission}"
oncomplete="handleRequest(xhr, status, args)"
/>
<p:commandButton id="chooseBatchButton" value="OPen dialog" update=":batchChooserForm"
actionListener="#{newSubmissionBean.fetchAvailability}" />
</f:facet>
</h:panelGrid>
</h:form>
</p:dialog>
<p:dialog id="batchDialog" header="Batch Chooser" widgetVar="bdlg" resizable="false" modal="true" closable="true">
<h:form id="batchChooserForm">
<p:fieldset legend="#{messages['label.legend.sample.available']}">
<p:dataTable id="availableSamples" var="sample" value="#{newSubmissionBean.availableSamples}">
<p:column style="width:20px">
<h:outputText id="dragIcon"
styleClass="ui-icon ui-icon-arrow-4" />
<p:draggable for="dragIcon" revert="true" />
</p:column>
<p:column headerText="#{messages['label.sample.batch']}">
<h:outputText value="#{sample.sampleId}" />
</p:column>
</p:dataTable>
</p:fieldset>
<p:fieldset id="selectedSamples" legend="#{messages['label.legend.sample.selected']}" style="margin-top:20px">
<p:outputPanel id="dropArea">
<h:outputText value="#{messages['label.drop.text']}"
rendered="#{empty newSubmissionBean.selectedSamples}"
style="font-size:24px;" />
<p:dataTable var="sample" value="#{newSubmissionBean.selectedSamples}"
rendered="#{not empty newSubmissionBean.selectedSamples}">
<p:column headerText="#{messages['label.sample.batch']}">
<h:outputText value="#{sample.sampleId}" />
</p:column>
<!-- p:column style="width:32px">
<p:commandButton update=":carForm:display"
oncomplete="carDialog.show()"
icon="ui-icon-search">
<f:setPropertyActionListener value="#{car}"
target="#{tableBean.selectedCar}" />
</p:commandButton>
</p:column-->
</p:dataTable>
</p:outputPanel>
</p:fieldset>
<p:commandButton id="confirmBatch" value="Confirm Selection" update=":newSubmissionForm :createDialogForm"
actionListener="#{newSubmissionBean.confirmSelection}"
oncomplete="handleRequest(xhr, status, args)"/>
<p:droppable for="selectedSamples" tolerance="touch" activeStyleClass="ui-state-highlight" datasource="availableSamples" onDrop="handleDrop">
<p:ajax listener="#{newSubmissionBean.onSampleDrop}" update="dropArea availableSamples" />
</p:droppable>
</h:form>
</p:dialog>
the javascript function for on complete is
<script type="text/javascript">
function handleRequest(xhr, status, args) {
if(args.validationFailed) {
dlg.show();
}
else {
dlg.hide();
}
}
</script>
And the code in the action listener where I try to open the second dialog. This method does get called as I have break pointed on it.
public void fetchAvailability(ActionEvent actionEvent) {
RequestContext.getCurrentInstance().execute("batchDialog.show()");
}
Can anyone advise what I have done wrong? Thanks in advance
You're using the id of the dialog in your javascript, you need to use the widgetVar as such:
public void fetchAvailability(ActionEvent actionEvent) {
RequestContext.getCurrentInstance().execute("bdlg.show()");
}
For future debuggning, try executing the javascript in your web browser console. In this case it should say "batchDialog is not defined" or something similar, giving you a hint.
Ok figured out what the issue was just in case anybody has the same thing. The Primefaces showcase example code has not defined the handledrop javascript function thus object undefined error is thrown. So I added the following to my code and now my pop up shows up.
function handleDrop(event, ui) {
var selectedSample = ui.draggable;
selectedSample.fadeOut('fast');
}
Thanks

Primefaces dialog doesn't show up

I want a dialog to show up after I click a commandButton, but it doesn't show up at all.
I think the button is submitting the form instead of showing up a dialog. What's more I've tried to make a 'Cancel' commandButton and it is also not working as it should - it works only if I click it first (if I click commandButton which is suppoused to open a dialog first, the cancel button won't work anymore).
Here's my .xhtml:
<ui:define name="content">
<p:dialog id="dlg" header="#{messages.chooseSkillLevel}" widgetVar="dlg" modal="true" dynamic="true">
<h:form>
<h:dataTable value="#{editSkills.skillsAndLevels}" var="skillslevel">
<h:column>
#{skillslevel.skill.umiejetnosc}
</h:column>
<h:column>
<p:selectOneMenu value="#{skillslevel.level}" >
<f:selectItems value="#{editSkills.levels}" var="level" itemLabel="#{level.stopien}" itemValue="#{level.id}" />
</p:selectOneMenu>
</h:column>
</h:dataTable>
<p:commandButton value="#{messages.confirm}" action="#{editSkills.showSkillsAndLevels}" oncomplete="dlg.hide();" />
<p:commandButton value="#{messages.cancel}" onclick="dlg.hide()"/>
</h:form>
</p:dialog>
<h:form>
<p:messages/>
<p:pickList value="#{editSkills.skills}" var="skill" effect="none" converter="#{picklistConverter}"
itemValue="#{skill.id}" itemLabel="#{skill.umiejetnosc}"
showSourceFilter="true" showTargetFilter="true" filterMatchMode="contains"
addLabel="#{messages.add}" removeLabel="#{messages.remove}" removeAllLabel="#{messages.removeAll}" >
<f:facet name="sourceCaption">#{messages.skillsList}</f:facet>
<f:facet name="targetCaption">#{messages.yourSkills}</f:facet>
<p:ajax event="transfer" listener="#{editSkills.onTransfer}" />
<p:column style="width:100%;">
#{skill.umiejetnosc}
</p:column>
</p:pickList>
<p:commandButton value="#{messages.confirm}" actionListener="#{editSkills.afterSubmit}" update=":dlg" oncomplete="dlg.show();" /> THIS IS THE MENTIONED BUTTON
<p:commandButton value="#{messages.cancel}" action="profile" immediate="true"/> THIS IS THE CANCEL BUTTON
</h:form>
</ui:define>
What should I do to make it working well?
Your code seems fine to me :). However, 1 thing you need to note is that the id and widgetVar attributes of the <p:dialog> must not have the same value. Try something like the following:
<p:dialog id="levelDlg" widgetVar="levelDialog">

How to skip the validation for component which is being hidden?

I have a scenario like the below..
<h:selectOneRadio id="someId" value="#{myBean.type}" required="true">
<f:ajax event="valueChange" execute="#form" render="myPanel">
<f:selectItem itemLabel="Existing Type" itemValue="Existing Type" />
<f:selectItem itemLabel="New Type" itemValue="New Type" />
<h:selectOneRadio>
<h:panelGroup id="myPanel" rendered="#{myBean.checkforNewType()}">
<h:inputText id="txtval" value="#{mybean.val}" required = "true" requiredMessage="Some message">
<h:message for="txtval" styleClass="error"/>
<h:panelGroup>
Basically the panel containing the textbox should be hidden if the value of the property type is "Existing Type".
But the issue I am facing is if user leave the box blank the panel is not hidden as it fails the validation.
Is there anyway to avoid the validation when the panel containing the textbox is being hidden?
Better check the request parameter value instead. The model value is namely not updated when the validation has failed in general and thus your rendered condition will fail when being bound to a request scoped bean.
<h:selectOneRadio id="someId" value="#{myBean.type}" required="true">
<f:ajax event="valueChange" execute="#form" render="myPanel">
<f:selectItem itemLabel="Existing Type" itemValue="Existing Type" />
<f:selectItem itemLabel="New Type" itemValue="New Type" />
<h:selectOneRadio>
<h:panelGroup id="myPanel" rendered="#{param['formId:someId'] == 'New Type'}">
<h:inputText id="txtval" value="#{mybean.val}" required="true" requiredMessage="Some message">
<h:message for="txtval" styleClass="error"/>
<h:panelGroup>
Here, I assume that the parent <h:form> has an id="formId".

Resources