Clearing forms and components in JSF 2.2 [duplicate] - forms

This question already has answers here:
Clear JSF form input values after submitting
(5 answers)
Closed 5 years ago.
After you have made a registration, it clears the form normally, but when I turn the page and come back to the registration page, the fields are filled with the values ​​I have registered before. The scoped I'm using is #ViewScoped.
Registration page..
Realizar Emprestimos
<h:form id="form" prependId="false">
<p:messages id="msgs"/>
<p:toolbar>
<f:facet name="left">
<p:toolbarGroup>
<p:commandButton value="Confirmar" action="#{empMB.inserir}" process="#this"
update="form:list_publicacao" ajax="false">
<f:ajax render="form:list_publicacao" resetValues="true"/>
</p:commandButton>
</p:toolbarGroup>
</f:facet>
<f:facet name="right">
<p:toolbarGroup>
<p:commandButton value="Cancelar" action="#{empMB.limparCampos()}"
immediate="true">
<f:ajax render="#form" resetValues="true"/>
</p:commandButton>
</p:toolbarGroup>
</f:facet>
</p:toolbar>
<f:ajax event="blur">
<h:panelGrid id="p1" columns="4" layout="grid">
<p:outputLabel value="Usuário: " for="usuario" />
<p:selectOneMenu id="usuario" effect="fade" filter="true"
filterMatchMode="contains"
value="#{empMB.emprestimo.usuario.idUsuario}" required="true"
requiredMessage="Selecione um usuário">
<f:selectItem itemLabel="selecione um usuario"
noSelectionOption="true" />
<f:selectItems value="#{usuarioMB.todosUsuarios}" var="usu"
itemValue="#{usu.idUsuario}" itemLabel="#{usu.nomeUsuario}" />
</p:selectOneMenu>
<p:outputLabel value="Data Emprestimo: " for="dataEmprestimo" />
<p:calendar id="dataEmprestimo"
value="#{empMB.emprestimo.dataEmprestimo}" effect="fold"
navigator="true" required="true"
requiredMessage="Inserir uma data do emprestimo"
pattern="dd/MM/yyyy" title="Data do Emprestimo">
<f:convertDateTime pattern="dd/MM/yyyy" locale="pt_BR"
timeZone="America/Sao_Paulo" />
</p:calendar>
</h:panelGrid>
<h:panelGrid id="p2" columns="2" layout="grid">
<p:outputLabel value="Publicacao: " for="publicacao" />
<p:selectOneMenu label="Publicação:" id="publicacao" effect="fade"
filter="true" filterMatchMode="contains"
value="#{empMB.emprestimo.publicacao.publicacaoId}">
<f:selectItem itemLabel="Selecione uma publicação"
noSelectionOption="true" />
<f:selectItems value="#{pubMB.publicacoesDisponiveis}" var="pub"
itemValue="#{pub.publicacaoId}" itemLabel="#{pub.titulo}" />
<f:ajax listener="#{empMB.setlistPublicacao()}"
render="list_publicacao msgs publicacao" />
</p:selectOneMenu>
</h:panelGrid>
<h2 style="font-size: 1.9em; margin-top: 3%;">Publicações
selecionadas</h2>
<p:dataTable reflow="true" id="list_publicacao"
value="#{empMB.listPublicacaoDesejada}" var="pub"
emptyMessage="Suas publicações aparecerão aqui.">
<ui:include src="/colunasPublicacoes.xhtml" />
</p:dataTable>
</f:ajax>
</h:form>
</ui:define>
Method..
public Emprestimo inserir() {
System.out.println(getListPublicacaoDesejada().size());
try {
for (int i = 0; i < getListPublicacaoDesejada().size(); i++) {
Calendar dataPrevista = Calendar.getInstance();
dataPrevista.setTime(emprestimo.getDataEmprestimo());
dataPrevista.add(Calendar.DAY_OF_MONTH,
Integer.parseInt(JSFHelper.getExternalContext().getInitParameter("previsaoDevolucao")));
emprestimo.setFuncionarioEmprestimo("usuarioteste08");
emprestimo.setDataPrevistaDevolucao(dataPrevista.getTime());
emprestimo.getPublicacao().setPublicacaoId(emprestimo.getListPublicacao().get(i).getPublicacaoId());
emprestimoFacade.inserir(emprestimo);
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Emprestimo(s)", "realizado(s) com sucesso!");
RequestContext.getCurrentInstance().showMessageInDialog(message);
emprestimo = new Emprestimo();
return emprestimo;
} catch (DAOException e) {
e.printStackTrace();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Atenção", "Erro ao realizada emprestimo");
RequestContext.getCurrentInstance().showMessageInDialog(message);
return null;
}
}
Thank you very much in advance.

Solved, I added the PostConstruct method at the beginning of MB.
#PostConstruct
public void init() {
emprestimo = new Emprestimo();
}

Related

commandLink not work primefaces mobile

primefaces mobile commandLink action does not work, it's not loading the page with id="station1". f:setPropertyActionListener is work and call setSelectedStation() method .
<pm:page id="fastStationPage">
<pm:header title="Fast Charging Station" swatch="b" ></pm:header>
<pm:content>
<h:form id="stationsDetailsForm">
<p:growl id="messages" showDetail="true" />
<p:dataList value="#{navigationViewImpl.fastStationList}" var="station" type="ordered">
<p:commandLink value="#{station.name}" action="pm:station1?transition=slide" update=":station1:stationDetail">
<f:setPropertyActionListener value="#{station}" target="#{navigationViewImpl.selectedStation}" />
</p:commandLink>
</p:dataList>
</h:form>
</pm:content>
</pm:page>
<pm:page id="station1">
<pm:content>
<h:outputText id="stationDetail" value="#{navigationViewImpl.selectedStation.name}" escape="false"/>
</pm:content>
</pm:page>
public void setSelectedStation(StationDTO selectedStation) {
this.selectedStation = selectedStation;
}
I got answer. I not configure face-config.xml file. I am not add navigation-handler
<application>
<navigation-handler>
org.primefaces.mobile.application.MobileNavigationHandler
</navigation-handler>
</application>

Close Rich:modalPanel after save correctly

I have a form with a button that opens a Rich:modalPanel with another form inside and two buttons at bottom; Close and Save.
Close: executes onclick="#{rich:component('mp')}.hide() and hides the modalPanel.
Save: validates the fields of the forms shows an error if is not complete, if the form is correct saves in db. reset the form but not close the Rich:modalPanel.
I want to close the Rich:modalPanel only if the form is ok and saves but i cant do it. I tried with:
Inserting Javascript:
<a4j:commandButton value="${msg.guardar}" styleClass="boton" reRender="personaForm" action="#{persona.guardarAuxiliar}" onclick="#{rich:component('mp')}.hide()"/><br />
and
<a4j:commandButton value="${msg.guardar}" styleClass="boton" reRender="personaForm" action="#{persona.guardarAuxiliar}" oncomplete="#{rich:component('mp')}.hide()"/><br />
Using only RichFaces:
<a4j:commandButton value="${msg.guardar}" styleClass="boton" reRender="personaForm" action="#{persona.guardarAuxiliar}">
<rich:componentControl for="mp" operation="hide" event="onclick" />
</a4j:commandButton><br />
and
<a4j:commandButton value="${msg.guardar}" styleClass="boton" reRender="personaForm" action="#{persona.guardarAuxiliar}">
<rich:componentControl for="mp" operation="hide" event="oncomplete" />
</a4j:commandButton><br />
But this codes always closes (or hide) the modalPanel, not only if the save is complete. Is it another way to close this modalPanel only if the save is ok?.
The Error popup is:
<a4j:outputPanel ajaxRendered="true">
<h:messages id="error" styleClass="error"></h:messages>
</a4j:outputPanel>
<rich:modalPanel id="panel2" width="350" height="100" zindex="4000" showWhenRendered="${persona.hayErrores || persona.exito}">
<f:facet name="header">
<h:panelGroup>
<h:outputText value="${msg.error}" rendered="#{persona.hayErrores}"></h:outputText>
<h:outputText value="${msg.info}" rendered="#{persona.exito}"></h:outputText>
</h:panelGroup>
</f:facet>
<f:facet name="controls">
<h:panelGroup>
<h:graphicImage value="/estilos/general/img/iconos/close.png" style="cursor:pointer" id="hidelink2"/>
<rich:componentControl for="panel2" attachTo="hidelink2" operation="hide" event="onclick"/>
</h:panelGroup>
</f:facet>
<a4j:outputPanel ajaxRendered="true">
<h:outputText value="#{persona.listaErrores}" rendered="#{persona.hayErrores}" styleClass="error"/>
<h:outputText value="#{msg.personaExito}" rendered="#{persona.exito}"/>
</a4j:outputPanel>
</rich:modalPanel>
Solved:
Just adding another rich:componentControl with conditions in popup message showing validation.
// If its wrong, only closes this popup
<rich:componentControl for="panel2" attachTo="hidelink2" operation="hide" event="onclick" rendered="#{persona.hayErrores}" />
// If its ok, closes this popup and 'mp' modalPanel
<rich:componentControl for="panel2,mp" attachTo="hidelink2" operation="hide" event="onclick" rendered="#{persona.exito}" />
You can use oncomplete attribute of a4j:commandButton, like
<a4j:commandButton action="#{persona.guardarAuxiliar}"
oncomplete="Richfaces.hideModalPanel('mp')"
value="#{msg.guardar}" reRender="personaForm" />
or with condition
oncomplete="if (#{!yourAction.hasErrors}) Richfaces.hideModalPanel('mp')"
Classical case with checking validation errors
oncomplete="if (#{facesContext.maximumSeverity == null}) {Richfaces.hideModalPanel('mp');}"

Orbeon + jsf -> submit in selectonemenu

I have a problem with xforms, how refresh only rich:panel when I choose value from h:selectOneMenu :
<!--<h:form> call bean but--> <form><!--open start page-->
<h:selectOneMenu id="add" onchange="submit()" <!-- can't find context , error orbeon/java--> >
<!-- is not working <a4j:support event="onchange" actionListener="#{bean.action}"/> -->
<s:selectItems value="#{bean.List()}" var="message" itemValue="#{message}" label="#{message}" />
</h:selectOneMenu>
</form>
more Code JSF :
<form>
<rich:panel styleClass="DocumentBody" id="documentPanel"
name="panell" style="margin-top:10px; height:90px;">
<f:facet styleClass="documentHeader" name="header"></f:facet>
<div id="documentTest" class="actionButtons">
<div style="clear: both; height: 15px; width: 60px" />
<s:button id="addButton" value="#{messages['operation.save.button']}"
action="#{actionBean.generateNewName()}" reRender="confirm"
onclick="#{actionBean.generateNewName()};#{rich:component('confirm')}.show();return false;">
</s:button>
<s:button id="loadButton" value="#{messages['operation.load.button']}"
action="#{actionBean.loadDraft()}" reRender="documentTests,documentPanel,loadButton" />
<s:button id="deleteButton" value="#{messages['operation.delete.button']}"
action="#{actionBean.deleteDraft()}" reRender="documentTests,documentPanel,deleteButton" />
</div>
</rich:panel>
</form>
<h:form style="margin: 0;">
<h:selectOneMenu id="messageTypeAdd"
style="margin-right:5px; margin-top:-30px;margin-left:90px;"
valueChangeListener="#{actionBean.documentTestChange}"
enableManualInput="false" selectFirstOnUpdate="true"
directInputSuggestions="true" onchange="submit()">
<!-- submit() rerender all page, but i try refresh only modalPanel id="confirm" -->
<s:selectItems value="#{actionBean.getdocumentTestList()}"
var="message" itemValue="#{message}" label="#{message}" />
<!--a4j and f:ajax is not work, i try update JSF 1.2 to 2.0 -->
</h:selectOneMenu>
</h:form>
<rich:modalPanel id="confirm" autosized="true" width="300">
<f:facet name="header"></f:facet>
<rich:messages style="color:red;" globalOnly="true" />
<a4j:outputPanel ajaxRendered="true">
<h:panelGrid>
<h:panelGrid columns="2">
<h:outputText value="#{messages['report.name.label']}" />
<h:inputText id="newDraftNameInput" value="#{actionBean.newDraftName}"
valueChangeListener="#{actionBean.newDraftNameChange}">
</h:inputText>
</h:panelGrid>
</h:panelGrid>
</a4j:outputPanel>
</rich:modalPanel>

jsf inputText disabled and readonly properties in form

This question is a follow on from a previous question "InputText value null when disabled is true" however I can not add comments to it.
I am using jsf 2.2 and the both the disabled and readonly properties when set true, for the inputText and inputTextarea controls when included in a form is deleting data from the associated field in the database when the object is merged because the fields are null when the object is returned from the jsf page.
The purpose for setting these properties on a form's field is to display the data in the field but not allow the user to change it and save changes to other fields in the form.
What other way can this be achieved other than placing the fields outside of the form and complicate the page layout.
Graham
I solved the problem, it was caused by using #RequestScoped instead of #SessionScoped for my page controller bean.
What I was doing was using a edit link from a datatable passing the current product object to the doEditProduct method.
<h:dataTable id="viewProductsTable" value="#{productController.products}" var="_product"
styleClass="data-table" headerClass="table-header" rowClasses="table-row">
<h:column>
<f:facet name ="header">
<h:outputText value="Product Name" />
</f:facet>
<h:outputText value="#{_product.productName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Goal"/>
</f:facet>
<h:outputText value="#{_product.goal}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Details"/>
</f:facet>
<h:outputText value="#{_product.description}"/>
</h:column>
<h:column>
<h:form>
<h:commandLink value="Edit" action="#{productController.doEditProduct(_product)}"/>
</h:form>
</h:column>
</h:dataTable>
the productController.doEditProduct method then opened the edit page
public String doEditProduct(Product product) {
this.product = product;
return "edit-product.xhtml";
the edit page contained a simple edit form
<h:form id="addProductForm">
<h:panelGrid columns="2" columnClasses="top-alignment, top-alignment">
<h:outputLabel for="product-name" value="Product Name"/>
<h:outputText value="#{productController.product.productName}" id="product-name" />
<h:outputLabel for="goal" value="Goal" />
<h:inputTextarea value="#{productController.product.goal}" id="goal" rows="10" cols="100" />
<h:outputLabel for="details" value="Details" />
<h:inputTextarea value="#{productController.product.description}" id="details" rows="20" cols="100"/>
<f:facet name="footer">
<h:panelGroup style="padding-top: 15px; display: inline-block; float: right; white-space: nowrap">
<h:commandButton id="submit" value="Save" action="#{productController.updateProduct()}" class="button" />
<h:button id="Cancel" outcome="index.xhtml" value="Cancel" class="button"/>
</h:panelGroup>
</f:facet>
</h:panelGrid>
</h:form>
At this point the product data was displayed on the page. However when the save button was clicked and ran the update method
public String updateProduct() {
try {
log.log(Level.INFO, "Updating: {0}", product.getGoal());
productFacade.edit(product);
} catch (Exception e) {
log.log(Level.WARNING, e.toString());
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "could not update product");
facesContext.addMessage(null, m);
return "";
}
return "index.xhtml";
Any field that had was disabled or readonly was set to null. In fact any non input field, anywhere on the page was set to null.
#RequestScope on the controller class meant that the class was being reinstantiated and thus the object stored in product was being assigned a new object in the PostConstruct method. The values in the editable fields were transferred to this new object and the non editable fields were set to null. Merging with the database meant that the data in the fields was deleted.
Using #SessionScoped means that the controller beans continues to exist across page requests. (I needed to remind myself about basic web page lifecycles)
Hope this helps anybody else that has this behaviour.
Graham

synchronization validation and display of dialog in a PrimeFaces JSF2.0 form

I have a form with jsf2 and primefaces that contains a submit button that managed two things:
First: form validation with the update attribute and second launching a confirmation dialog box when validation succeeded and all of this are managed by:
update="myfieldset display"
so my problem is that when I click into the button validation: if validation don't succeeded : validation messages are displayed in the form : ok
but if the validation succeeded I must click a second time to display dialog box
anyone know how to solve this problem there?
<!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://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<script type="text/javascript">
<!--
function effacer(formulaire){
for (var i=0; i<formulaire.length; i++){
if (formulaire.elements[i].type=="input" || formulaire.elements[i].type=="textarea" ) {formulaire.elements[i].value="";}
}
document.getElementById('contenu_input').value="";
}
//-->
</script>
<body>
<ui:composition template="./template_utilisateur.xhtml">
<ui:define name="content">
<h:form id="form" prependId="false" >
<p:fieldset id="myfieldset" legend="Nouveau message">
<p:messages id="msgs"/>
<h:panelGrid columns="3" style="margin-bottom:10px">
<h:outputLabel for="title" value="Titre : *"/>
<p:inputText id="title" style="width:340px;" value="#{messageController.titre}" required="true" requiredMessage="veuillez saisir un titre" label="Titre">
<f:validateLength minimum="10" />
</p:inputText>
<p:message for="title" display="icon"/>
<h:outputLabel for="city" value="Destinataire : *" />
<p:selectOneMenu id="city" value="#{messageController.destinataire}" label="Destinataire" required="true" requiredMessage="veuillez choisir au moins un destinataire" >
<f:selectItem itemLabel="Séléctionner déstinataire" itemValue="" />
<f:selectItems value="#{messageController.users}" />
</p:selectOneMenu>
<p:message for="city" id="msgSurname3" display="icon"/>
<h:outputLabel for="comm" value="Lié a La commande N° : " />
<p:selectOneMenu id="comm" label="Commande" value="#{messageController.idComm}" >
<f:selectItem itemLabel="Aucune commande" itemValue="" />
<f:selectItems value="#{messageController.id_c}" />
</p:selectOneMenu>
<p:message for="comm" id="msgSurnamse3" display="icon"/>
</h:panelGrid>
<h:outputLabel for="contenu" value="Contenu : *" />
<h:panelGrid columns="2">
<p:editor id="contenu" widgetVar="editer" value="#{messageController.message}" width="600" required="true" requiredMessage="Veuillez saisir le contenu du message" >
<f:validateLength minimum="10" />
</p:editor>
<p:message for="contenu" id="editorm" display="icon"/>
</h:panelGrid>
<h:panelGrid columns="3">
<p:commandButton id="submitButton" value="envoyer" update="myfieldset display" onclick="#{messageController.retournerDialog()}" icon="ui-icon-disk" />
<p:commandButton id="clearButton" type="reset" value="initialiser" onclick="editer.clear()"
icon="ui-icon-close" />
</h:panelGrid>
</p:fieldset>
<p:dialog header="Confirmation" widgetVar="dlg" showEffect="fade" hideEffect="fade" modal="true">
<h:panelGrid id="display" columns="1" cellpadding="4">
<h:outputText value="Titre : " />
<h:outputText value="#{messageController.titre}" id="model"/>
<h:outputText value="Déstinataire :" />
<h:outputText value="#{messageController.destinataire}" id="year"/>
<h:outputText value="Lié à la commande N° : " />
<h:outputText value="#{messageController.idComm}" id="manufacturer"/>
<h:outputText value="Contenu :" />
<h:outputText id="displxcay" value="#{messageController.message}" escape="false" />
</h:panelGrid>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
and here the method to launch the dialog
public String retournerDialog(){
String retour = "";
if( getDestinataire() != "" && getMessage()!= "" && getTitre()!="" && getMessage().length()>9 && getTitre().length()>9){
retour="dlg.show()";
}
return retour;
}
thank you in advance
Update: thank you BalusC for your detailed response, I tested both of your answers but they don't work
here is the code of the button :
<p:commandButton id="submitButton" value="envoyer" update="myfieldset, display" action="#{messageController.showDialog}" icon="ui-icon-disk" />
and the managedBean :
private boolean showDialog;
public void showDialog() {
showDialog = true;
}
public boolean isShowDialog() {
return showDialog;
}
and with this code above the dialog doesn't appear even if validation is succeeded
: I think because action must return outcome string not boolean
and when I make :
<p:commandButton id="submitButton" value="envoyer" update="myfieldset, display" onclick="dlg.show();" icon="ui-icon-disk" />
it appear even if the validation failed
and to remind you
when I put a method above like this :
<p:commandButton id="submitButton" value="envoyer" update="myfieldset, display" onclick="#{messageController.retournerDialog()}" icon="ui-icon-disk" />
I have to click twice (I think one for validation and one for displaying dialog)for the dialog is displayed
also in the official documentation : they use this dialog with onclick attribute
do you have any other idea