p:ajax not updating p:inputText - jsf

I am unable to update a <p:inputText> based on the value entered in another <p:inputText> using <p:ajax>. I am using JSF 2 with PrimeFaces 5. The second <p:inputText> is not updating, the listener associated with <p:ajax> is being called and i am getting the correct values in the listener but its not updated on the view.
the view code is:
<p:dialog id="newStdDlg" header="Add new Student" widgetVar="newStdDlg" modal="true">
<h:panelGrid id="newStdDlgPanel" columns="2" cellpadding="5" style="width:100%;">
<p:outputLabel value="First Name *" />
<p:inputText id="studentfname" value="#{addStudentBean.student.firstName}">
<p:ajax event="change" update="studentUsrname" listener="#{addStudentBean.firstNameChange}" />
</p:inputText>
<p:outputLabel value="Last Name *" />
<p:inputText value="#{addStudentBean.student.lastName}"/>
<p:outputLabel value="Father's Name *" />
<p:inputText value="#{addStudentBean.student.fatherName}"/>
<p:outputLabel id="uLbl" value="Username (System Generated) *" />
<p:inputText id="studentUsrname" value="#{addStudentBean.student.user.username}" />
<p:outputLabel value="This temporary password would be mailed to user: " />
<p:outputLabel id="stdpassword" value="#{addStudentBean.student.user.password}"/>
</h:panelGrid>
<p:commandButton value="Create Student"
actionListener="#{addStudentBean.addNewStudentAction}"
style="margin-left:auto;margin-right:auto;display:block;"/>
</p:dialog>
and the listener of the session scoped managed bean is :
public void firstNameChange() {
System.out.println("In AddStudentBean().firstNameChange()..........");
System.out.println("The value of student.getFirstName: "+student.getFirstName());
System.out.println("updating system generated username as: "+student.getFirstName()+String.valueOf(new UserDAO().getUserCount()+1));
student.getUser().setUsername(student.getFirstName()+String.valueOf(new UserDAO().getUserCount()+1));
student.getUser().setPassword(KaaloUtils.getPassword());
}

Like Jaqen mentioned in comments the comments use h:form inside dialog.
If you want to update the component from ManagedBean you can do that by using org.primefaces.RequestContext's update method.
RequestContext.getCurrentInstance().update("COMPONENT_ID_TO_UPDATE")
If you feel like this method is too Cohesive, you can update from Facelet only, make sure remember to not place p:dialog in a h:from instead use h:form inside p:dialog .

Related

JSF Required Field only call message if i leave them

I have a problem with the JSF validation. I have the following form - only the first inputfield is required. So if I leave them empty and click on the primefaces calendar field - JSF render the whole form and of course I got a message that the field is required.
So I need a solutions that the field only call the blur event or required message when I leave the field not when I click another field etc.
<h:form>
<p:growl id="msg" showDetail="true" />
<b:panelGrid col-spans="4,8" columns="2" id="inputPanel">
<h:outputLabel value="ID*"></h:outputLabel>
<b:inputText value="#{managedBean.avsId}" required="true"
update="msg" onblur="ajax:managedBean.checkDublicates()"></b:inputText>
<h:outputLabel value="Legal Form"></h:outputLabel>
<b:switch animate="true" on-text="natural" offColor="danger"
onColor="success" off-text="forensic"
value="#{managedBean.legalform}">
</b:switch>
<h:outputLabel value="Date"></h:outputLabel>
<p:calendar value="#{managedBean.date}" pattern="dd.MM.yyyy">
<f:converter converterId="timestampConverter" />
</p:calendar>
<h:outputLabel value="Note" style="margin-top:5%;"></h:outputLabel>
<b:inputTextarea style="margin-top:5%;"
value="#{managedBean.note}"></b:inputTextarea>
</b:panelGrid>
<b:commandButton value="apply" look="success"
style="width:100%;" action="#{managedBean.create()}"
update="#form" />
</h:form>

Why does a primefaces view keep a value when I´m setting it as new? [duplicate]

This question already has an answer here:
Dialog not updating after populating model in action method
(1 answer)
Closed 6 years ago.
I´m just trying to get some object when I do double click over a data table row and show it on a modal dialog. I should be missing something because it does it correctly only one time. After the bean object is setted, it keeps the value no matter what I do.
Here is the code:
*.xhtml:
<!-- Modal dialog -->
<p:dialog widgetVar="addNotDlg" id="idAddNotDlb" minHeight="40" modal="true"
resizable="false" draggable="false" style="heigth:500">
<p:panel id="panel">
<p:messages id="messages" />
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="resultado" value="Resultado:" />
<p:inputText id="resultado"
value="#{acuerdoBean.notificacion.resultado}" label="resultado" />
<p:message for="resultado" />
<p:outputLabel for="motivo" value="Motivo:" />
<p:inputText id="motivo"
value="#{acuerdoBean.notificacion.motivo}" label="motivo" />
<p:message for="motivo" />
</h:panelGrid>
<p:commandButton value="Guardar" id="addNewNotButton" actionListener="#{acuerdoBean.addNotificacion()}"
update=":formNotificacion:notificacionesTable"
oncomplete="handleLoginRequest(xhr, status, args)" />
<p:commandButton value="Cerrar" id="closeNewNotButton" onclick="PF('addNotDlg').hide();" />
<h:outputText value="" />
</p:panel>
</p:dialog>
*Bean.java code:
public void generateNewNotificacion() {
this.tiposNotificaciones = pservice.getTiposNotificaciones();
this.tipoNotificacion = new Rstiponotifica();
this.direccionPorDefecto = (Rsdireccion) pservice.findDireccionPorDefecto();
this.notificacion = new Rsnotificacion();
this.notificacion.setRsacuerdo(acuerdo);
this.notificacion.setRstiponotifica(tipoNotificacion);
this.notificacion.setRsdireccion(direccionPorDefecto);
}
The above function is executed in other .xhtml file event. I would expect that my "this.notificacion" object should appear as new in the modal, but it doesn´t. The "this.notification" object was setted previously and it remains in memory.
<p:commandLink onclick="PF('addNotDlg').show();" actionListener="#{acuerdoBean.generateNewNotificacion()}">
<h:outputText value="Añadir nueva notificacion" />
</p:commandLink>
Thanks in advance.
Updating your panel inside the dialog when you click the command link should fix your problem. The commandLink have an update attribute that you can use.
You can see a working example on primefaces website : http://www.primefaces.org/showcase/ui/data/schedule.xhtml

How can I get my commandButton by Id?

I want to change my ActionListener of commandButton depending on the icon selected in advance:
<p:dialog id="dialog" header="Add Memo" widgetVar="dialogMemo" resizable="false" >
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="commentInput" value="Comment:" />
<p:inputTextarea id="commentInput" value="#{dashboardBean.getCurrentComment()}" rows="6" cols="25" label="commentInput"/>
<p:watermark for="commentInput" value="Enter your memo..."/>
<h:outputLabel for="selectShare" value="Share Memo: " />
<p:selectBooleanCheckbox id="selectShare" />
<h:outputLabel for="choosePriority" value="Priority:" />
<p:selectOneMenu id="choosePriority" value="#{dashboardBean.currentPriority}" label="choosePriority">
<f:selectItem itemLabel="Low Priority" itemValue="1" />
<f:selectItem itemLabel="Medium Priority" itemValue="2" />
<f:selectItem itemLabel="High Priority" itemValue="3" />
</p:selectOneMenu>
<p:commandButton id="submitDialog" icon="ui-icon-check" value="Confirm" ajax='false' type="submit" action="#{dashboardBean.getLastMemo()}"/>
<p:commandButton icon="ui-icon-close" onclick="dialogMemo.hide();" value="Cancel"/>
</h:panelGrid>
</h:form>
</p:dialog>
<p:layout fullPage="true">
<p:layoutUnit id="leftPanel" position="west" size="250" header="My Memos" resizable="false" closable="false" collapsible="false">
<h:form id="form">
<p:commandButton id="addMemo" icon="ui-icon-plus" onclick="dialogMemo.show();" type="submit" action="#{dashboardBean.getEditControl}"/>
<p:dashboard id="dashboardId" model="#{dashboardBean.model}" binding="#{dashboardBean.dashboard}">
</p:dashboard>
</h:form>
</p:layoutUnit>
</h:body>
When i click to command button (id="addMemo"), i want to change actionListener to commandButton(id="submitDialog").
I try that with:
public void getEditControl()
{
UIViewRoot view = _context.getViewRoot();
CommandButton button = (CommandButton) view.findComponent("submitDialog");
System.out.println("I am ID ==== [ " + button.getId() +" ]");
}
But 'button.getId()' does't work.
But 'button.getId()' does't work.
I gather that this is because the button is actually null and therefore the attempt to invoke the getId() method threw a NullPointerException? It's surprising that you stated the problem like that, "button.getId() doesn't work" instead of like "view.findComponent() returned null" (which has in turn the pretty obvious consequence that any attempt to access it would throw NullPointerException). If you had indeed no clue why it threw NullPointerException, then I strongly recommend to take a JSF pause and learn basic Java first.
Coming back to the concrete problem, the findComponent will return null when the client ID submitDialog doesn't exist in the component tree. Indeed, you have it inside a <h:form> which is a NamingContainer component. The button's client ID is more likely formId:submitDialog where formId is the ID of the button's parent form which you have to assign yet. An easy way to find out it is checking the ID of the generated HTML representation of the button.
See also this related question: How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar" Just substitute "ajax" in the answer with findComponent.
I am not sure that the way you do this is the right way.
If you want to get component instance better way to do this will be not get it by id but add
<p:commandButton id="submitDialog" icon="ui-icon-check"
value="Confirm" ajax='false' type="submit"
action="#{dashboardBean.getLastMemo()}" binding="#{dashboardBean.component}" />
and that way the property in the bean will always have the component instance that you need.
Note that the scope of bean where you put component binding should be view to avoid side affects.

How to set JSF input field value before submit

I a have a JSF page with PrimeFaces with some input fields. Before a submit is done, I would like to use the value of a field as input for a method which does some calculations and updates another field with the result but without submitting the form.
This is the field that will be used as input for my method:
<h:outputLabel for="hiredate" value="#{msgs['addUser.hireDate']}" />
<p:calendar id="hiredate" value="#{userWizardMB.user.hireDate}" required="true" immediate="true"/>
<p:message for="hiredate" />
The calculation is done by clicking a <p:commandButton>:
<p:commandButton value="Calculate days" icon="ui-icon-circle-check" action="#{userWizardMB.calculateVacationDays}" update="vacationDays" process="#this" immediate="true"/>
And this is the method called:
public void calculateVacationDays() {
user.setVacationDays((int) vacationDaysCalculator
.calculateWithHireDate(user.getHireDate()));
}
When debugging, though, I see that this field is NULL even if I set value in the form.
How can I force the setting of this field - user.hireDate because I really need this value for my calculation?
Thank you
Edit: I removed all of the other fields in the form and the immediate attribute:
<h:form id="addUserForm">
<p:wizard widgetVar="wizard" flowListener="#{userWizardMB.onFlowProcess}">
<!-- TAB FOR PERSONAL DATA -->
<p:tab id="personal" title="#{msgs['addUser.personalTab']}">
<p:panel header="#{msgs['addUser.personalInformation']}">
<p:message for="vacationDays" showDetail="true" autoUpdate="true" closable="true"/>
<h:panelGrid columns="3" columnClasses="label, value" styleClass="grid">
<h:outputLabel for="hiredate" value="#{msgs['addUser.hireDate']}" />
<p:calendar id="hiredate" value="#{userWizardMB.user.hireDate}" required="true" />
<p:message for="hiredate" />
<h:outputLabel for="vacationDays" value="#{msgs['addUser.vacationDays']}"/>
<p:inputText id="vacationDays" value="#{userWizardMB.user.vacationDays}"/>
<p:commandButton value="Calculate days" icon="ui-icon-circle-check" action="#{userWizardMB.calculateVacationDays}" process="#this hiredate" update="vacationDays"/>
</h:panelGrid>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
And the backing bean method is still not called.
Remove immediate="true" from the input and the command component. Do not use immediate unless you really understand what it should be used for. Further you also need to include the input component which you'd like to process in the update attribute of the command component. Note that this should represent the client ID, not the property name as mentioned in one of your comments.
<p:calendar id="hiredate" value="#{userWizardMB.user.hireDate}" required="true" />
...
<p:commandButton value="Calculate days" icon="ui-icon-circle-check"
action="#{userWizardMB.calculateVacationDays}"
process="#this hiredate" update="vacationDays" />
See also:
Why was "immediate" attribute added to the EditableValueHolders?
Use process="#form" (or process="[the id of the calendar component]" in the commandButton
process="#this" means that only the part of the model related to the commandButton (usually none) gets updated.
Old question, but did you add partialSubmit="true" in the commandButton tag? At least in PrimeFaces 3.5, false is the default value of this attribute (see the PrimeFaces PDF documentation).

primefaces dialog with inputtext as parameter

I would like to give the content of an inputText as a parameter to a function in a backing bean, I know that I could send the content in the backing bean, but it doesn't make much sense in my object model. I know that in the datatable, you can provide a function with the name of the "var", I thought I could use the same mechanism by passing the ID of the inputText, but it always sends null. Is there a way to do it ?
<p:dialog id="dialog" header="Reason for obsolescence" modal="true" widgetVar="dlg">
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="reason" value="Reason for obsolescence :" />
<p:inputText value="default" id="reason" required="true" label="reason" />
<p:commandButton id="provideReason" value="Ok" update=":form:tabView:table-metadata"
action="#{tableMetadataController.setSelectedObsolete(reason)}"
oncomplete="dlg.hide()"/>
</h:panelGrid>
</h:form>
</p:dialog>
Thanks

Resources