I am doing a product insert form in PrimeFaces dialog. My bean's scope is session. I can insert a product, but when I try to insert another product, the form has previous product's information. I want to reset form. I tried UIInput but it doesnt work. How can I clear the form?
Just create a new product after saving it and make sure that you're ajax-updating the form after save.
E.g.
<h:form>
<h:inputText value="#{productController.product.name}" />
<h:inputTextarea value="#{productController.product.description}" />
<h:selectOneMenu value="#{productController.product.category}">
<f:selectItems value="#{applicationData.categories}" />
</h:selectOneMenu>
<p:commandButton value="Save" action="#{productController.save}" update="#form" />
</h:form>
with
public void save() {
productService.save(product);
product = new Product();
}
By the way, that kind of bean really doesn't belong in the session scope. Put it in the view scope.
Related
In my JSF view I have a p:selectCheckboxMenu and CLEAR button. The aim of that CLEAR button is that when a user clicks the button, all selected checkbox values are removed and enable the checkbox again.Am writing the logic in JAVA side to update the changes by using requestcontext update method.But for my logic its not working.
JAVA :
public void clearResource{
getRemove_resource_SelectionList().clear();
enDis_resourceSelection(false);
RequestContext.getCurrentInstance().update("ResourceSelection");
}
<p:outputLabel id="ResourceSelection">Resource</p:outputLabel>
<p:selectCheckboxMenu id="selectUnselectresource" filter="true"
filterMatchMode="contains" multiple="true"
value="#{Bean.remove_resource_SelectionList}"
disabled="#{Bean.enDis_resourceSelection}">
<f:selectItems value="#{Bean.resource_List}" var="resource"
itemLabel="#{resource.attribute}" itemValue="#{resource.attr_value}"/>
<p:ajax event="change" update="#this"
onstart="PF('PM_progress').block();" oncomplete="PF('PM_progress').unblock();" />
<p:ajax event="toggleSelect" update="#this"
onstart="PF('PM_progress').block();" oncomplete="PF('PM_progress').unblock();" />
</p:selectCheckboxMenu>
<p:commandButton value="Clear" style="margin-top:10px;margin-right:5px;
id="ClearButton"
actionListener="#{Bean.clear_Resource()}" immediate="true"
onstart="PF('PM_progress').block();"
oncomplete="PF('PM_progress').unblock();"/>
I got a very funny issues: When I tried to access selectOneMenu selected value by using valueChangeListener's valueChangeEvent. I got itemLabel instead of itemValue.
jsf snappet:
<p:selectOneMenu id="position" value="#{employmentBean.currentEmployment.positionId}" required="true" effect="fold" editable="true"
requiredMessage="Please select an available option." hideNoSelectionOption="true" immediate="true" valueChangeListener="#{employmentControlBean.handlepositionIdSelected}">
<p:ajax update="#form" />
<f:selectItem itemLabel="Select Position to Create Employment." itemValue="" />
<f:selectItems value="#{positionBean.vacantPositionMap.entrySet()}" var="entry" itemLabel="#{entry.value}" itemValue="#{entry.key}"/>
</p:selectOneMenu>
my vacantPositionMap is a
Map<String,String>
style key/value pair, key is position Id, value is position Name.
my backing bean:
#Named(value = "employmentControlBean")
#SessionScoped
public class EmploymentControlBean(){
public void handlepositionIdSelected(ValueChangeEvent event){
........
String positionId = (String) event.getNewValue();
positionBean.setCurrentPosition((Position) positionBean.getPositionCache().get(positionId));
employmentBean.getCurrentEmployment().setPositionId(positionId);
}
}
from above snappet you can see. I am trying to fetch selectOneMenu selected value on valueChangeEvent.
Backing bean method by using ValueChangeEvent, I suppose JSF's itemValue will be passed to backing bean by using ValueChangeEvent.
This is what I found in my html by using firebug:
From above image you can see, primeFaces rendering html correctly, but when I tried to access selected value I get "President". It is not I expected, I expect will get "POSTN20161215xxxxxx".
My question is: Why ValueChangeEvent pass itemLabel instead of itemValue? How I can get the correct value?
Please advise!!
I am using Primefaces 4.0 and JSF 2.2. When I make a DataTable with row Edit and I set a valdiationFailed() on the rowEdit event, the roweditor is closing, which I want to prevent.
I added an oncomplete js function like:
<p:ajax event="rowEdit" listener="#{customerUI.onInvoiceRowEdit}"
oncomplete="if(!args.validationFailed) {updateTable();}" update=":messages" />
My remote command is as follows:
<p:remoteCommand name="updateTable" update=":form:addressTabs:customerTable" />
So this keeps the editor when the validation fails, but now the editors accept and cancel buttons doesn't work, so does editing other things on the side until i do a manual refresh.
I just want the editor to stay when the validation fails and to correct the input, if the validation went good, the editor can be closed.
Anyone any solution to this?
So I had a tangentially related problem and this question helped me figure out a solution so I thought I should share it here in case someone else lands on this question with a similar issue and needs help.
So I had a dataTable and a rowEdit ajax call to a function when a cell within the row is edited, I also used a remoteCommand to update the dataTable after I make some changes in the DB. Problem was if the validation for the cell edit value failed the remoteCommand would refresh the form and the error messages would disappear before they could be read. I wanted the ajax call on rowEdit to only go through if there were no validation errors, otherwise I wanted to display the error message with the row editor still open. So I used the args.validationFailed parameter as shown in the question to prevent the remoteCommand from being executed in case the custom validator fails. The following is a basic example of what I did.
JSF page:-
<h:form id="form_name">
<p:remoteCommand name="refreshForm" update="#form" />
<p:dataTable id="table_id" var="varTableData"
value="#{bean.tablerows}"
editable="true">
<p:ajax event="rowEdit"
listener="#{bean.onRowEdit}"
oncomplete="if(!args.validationFailed) refreshForm()" />
<p:column>
<f:facet name="header">
<h:outputText value="Column Title" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{varTableData.someValue}" />
</f:facet>
<f:facet name="input">
<p:inputText id="cellId"
value="#{varTableData.someValue}"
label="Some Label" required="true" style="width:100%"
validator="#{bean.validationMethod}">
</p:inputText>
<p:message id="someMsg" for="cellId" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</h:form>
Custom Validation Method :-
public void validationMethod(FacesContext context, UIComponent comp, Object value) {
int someCellValue = (int) value;
if (someCellValue < 6) {
((UIInput) comp).setValid(false);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Some error message",
"some error message");
context.addMessage(comp.getClientId(context), message);
}
}
Primefaces 3.5, Mojarra 2.1.14. This is my PF datatable, it contains one non-editable boolean column named 'automatic', and editable 'label' column:
<p:dataTable value="#{bean.contents}" paginator="true" var="row"
editable="true" editMode="cell" rows="25" rowsPerPageTemplate="10,25,50" id="list">
<p:column>
<f:facet name="header"><h:outputText value="header1" /></f:facet>
<p:selectBooleanCheckbox value="#{row.automatic}" disabled="true" id="isAutomatic"></p:selectBooleanCheckbox>
</p:column>
<p:column>
<f:facet name="header"><h:outputText value="header2" /></f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{row.label}"></h:outputText>
</f:facet>
<f:facet name="input">
<p:inputText value="#{row.label}"></p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<p:ajax event="cellEdit" process="#this" listener="#{myBean.onEditLabel}" update="isAutomatic"/>
</p:dataTable>
Cell edit event listener:
public void onEditLabel(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
DataTable s = (DataTable) event.getSource();
MyEntity d = (MyEntity) s.getRowData();
try {
d.setAutomatic(false);
myDAO.save(d);
addMessage("Change saved!");
} catch (Exception ex) {
addErrorMessage("Label could not be saved!");
getFacesContext().validationFailed();
}
}
}
The cell editor works, sends data to listener, and it is correctly persisted to the database. The 'automatic' flag is also cleared by cell edit event listener, and gets correctly persisted to the database. The problem is that 'automatic' checkbox is not updated on the client.
I also tried
<p:ajax event="cellEdit" process="#this" listener="#{myBean.onEditLabel}" update="list"/>
which correctly updated the checkbox, but also causes focus to be lost, and wastes bandwidth.
How can I update just a specific cell after cellEdit event is fired?
You p:ajax tag is inside p:dataTable no in some specific row or column, so you cent so easy update some relative component id. You can with help of RequestContext update specific component in cell. So, remove update from p:ajax and add this to your onEditLabel method:
RequestContext.getCurrentInstance().update(
s.getClientId(FacesContext.getCurrentInstance()) +
":" + event.getRowIndex() +
":isAutomatic"
);
As you can see, id of component inside cell has row number before id you assigned.
I believe you can solve this without having to know the details of the ID of the component you wish to update. You can pass it as a parameter to the bean.
First, bind the component you wish to update. You don't actual need a bean to which this component is bound to. You just need to define some value which you can use to identify this component later in your JSF. So in your case, you would do something like:
<p:selectBooleanCheckbox binding="#{isAutomaticComponent}" value="#{row.automatic}" disabled="true" id="isAutomatic"></p:selectBooleanCheckbox>
Now access the component when you do your update. ie:
<p:ajax event="cellEdit" process="#this" listener="#{myBean.onEditLabel(isAutomaticComponent.clientId)}" />
Now you can update the component from your cellEdit event method without knowing the contents of the ID. ie:
public void onEditLabel(CellEditEvent event, String idOfComponentToUpdate) {
...
RequestContext.getCurrentInstance().update(idOfComponentToUpdate);
...
I have a Dialog to input details. At the first time , InputText are empty.
But from the second input, InputText maintain the previous value.
This is my code :
<p:commandButton id="showDialogButton1" type="button" value="add" onclick="dlg1.show()" update="firstname1"/>
<p:dialog id="dialogAjout" header="add department" widgetVar="dlg1" resizable="false">
<h:panelGrid columns="2" style="margin-bottom:10px">
<h:outputLabel for="firstname1" value="Libellé :" />
<p:inputText id="firstname1" value="#{departementBean.departement.libelleDepartement}" />
</h:panelGrid>
<p:commandButton id="submitButton1" value="Valider" oncomplete="dlg1.hide();" action="#{departementBean.addDept()}" update="tabView"/>
</p:dialog>
How can I resolve this, please !!
You can use this primefaces component:
http://www.primefaces.org/showcase/ui/misc/resetInput.xhtml
Regarding dialogs in general: don't put them inside forms.
Have this instead: <p:dialog><h:form>...
Regarding update="" values, if your appendToBody is true, put a colon in front of the id (that means it`s in another form).
You should use the following code:
<h:commandButton value="Reset" style="margin-right:20px;">
<p:ajax update="registrationForm" resetValues="true" />
</h:commandButton>
Add resetValues="true" to your commandButton
<p:commandButton resetValues="true" action="#{departementBean.prepareDialog}" id="showDialogButton1" type="button" value="add" oncomplete="dlg1.show()" update=":dialogAjout"/>
modify you open button like this : open dialog in oncomplete and before that update it by adding its id to update attribute and add action method to do the server side logic to actually init the dialog fields (populate / reset)
<p:commandButton action="#{departementBean.prepareDialog}" id="showDialogButton1" type="button" value="add" oncomplete="dlg1.show()" update=":dialogAjout"/>
b.t.w it looks like your dialog located inside your form together with your opening button , this is a "bad practice" move your dialog away from that form and place a new form inside the dialog , e.g <p:dialog><h:form> ...
I solved this question thus
<p:dialog header="myDialog" widgetVar="dlg1" minHeight="40">
<h:outputLabel for="fild1" value="Fill the field" />
<p:password id="fild1" value="#{myBean.attribute}" required="false" label="Field" redisplay="false" /><br />
<p:commandButton action="#{myBean.method()}" value="Send" oncomplete="dlg1.hide()" update="field1" />
</p:dialog>
When I used the attribute update="field1" of p:commandButton.
The value of field p:password will empty after submitting the form.
I tried do the suggestion of Dani but my attribute going empty when I submitted my form and not stayed empty after submit