Basically, I'm trying to fire an action from a <p:commandLink> to update a <p:datatable> and a <p:growl>.
The <p:growl> is updated instantly, but the <p:datatable> is updated only after a second click.
Here is the XHTML code :
<h:body>
<h:form id="form1" >
<p:layout id="layout">
<p:layoutUnit id="north" position="north">
<p:growl id="msg" showDetail="true" />
<h:column>
<p:commandButton id="searchdate"
value="Rechercher"
actionListener="#{dyna.search}"
update=":form1:tabexam,:form1:msg"/>
</h:column>
</p:layoutUnit>
<p:layoutUnit position="center"
resizable="true"
collapsible="true"
effect="drop"
size="300"
styleClass="heighter">
<p:dataTable id="tabexam"
paginatorPosition="bottom"
var="exam"
value="#{dyna.listexam}"
widgetVar="examTable"
emptyMessage="aucun résultat."
filteredValue="#{dyna.filteredexams}"
paginator="true"
rows="20"
rowsPerPageTemplate="10,20,40,80"
binding="#{dyna.table}">
<f:facet name="header" >
<h:outputText value="Rechercher: "/>
<p:inputText id="globalFilter"
onkeyup="examTable.filter();"
style="width:200px" />
</f:facet>
</p:dataTable>
</p:layoutUnit>
<p:layoutUnit position="west" resizable="false" header="Liste Perso.">
<ui:repeat var="list" value="#{userBean.userLists}">
<center>
<p:commandLink id="listerlink"
title="Afficher la liste"
action ="#{dyna.refreshChildren(list.id.tbCode)}"
update=":form1:tabexam,:form1:msg">
<p:graphicImage id="imglist" value="/images/Liste_Cold.png"/><br></br>
<p:outputLabel value="#{list.id.tbCode}" /><br></br>
</p:commandLink>
</center>
</ui:repeat>
</p:layoutUnit>
</h:form>
</h:body>
Here is some code from my ManagedBean.
#ManagedBean(name = "dyna", eager = true)
#SessionScoped
public class DynamicDatatable implements java.io.Serializable {
#PostConstruct
public void init() {
listexam = DAO_Examen.getAllExamens();
selectedExamen = new Cotation();
etatExamOptions = createFilterOptions();
payExamOptions = createFilterOptions2();
salleOptions = DAO_Salle.getAllSalle(UserBean.user.getUserId());
refreshChildren("default");
}
public void refreshChildren(String listid) {
try {
//config
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
ExpressionFactory ef = application.getExpressionFactory();
ELContext elc = fc.getELContext();
//Table
table = (DataTable) application.createComponent(DataTable.COMPONENT_TYPE);
//columns spec.
ArrayList<ColumnModel> columnmodel = DAO_UserLists.createUserColumnSpec(UserBean.user.getUserId(), "SITE1", listid);
if (columnmodel != null) {
for (int i = 0; i < columnmodel.size(); i++) {
if ((columnmodel.get(i) != null) && (columnmodel.get(i).getDbname() != null)) {
Column column = (Column) application.createComponent(Column.COMPONENT_TYPE);
column.setHeaderText(columnmodel.get(i).getUserListname());
column.setWidth("10");
column.setId("Col_" + columnmodel.get(i).getHeadername());
column.setStyleClass("dispo");
column.setSortBy(columnmodel.get(i).getDbname());
column.setRendered(columnmodel.get(i).isVisible());
table.getChildren().add(column);
}
}
FacesMessage msg = new FacesMessage("Terminé avec succes", "la liste " + listid + " est bien chargée");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
API's Version:
JSF 2.2
primefaces 4.0
Related
I want to add item into Primefaces table when I create new item. I managed to create this code:
<h:form id="new_item_button">
<p:commandButton id="ajax" value="New Sensor" styleClass="ui-priority-primary" onclick="PF('dlg').show();" type="button"/>
</h:form>
<h:form id="new_sensor">
<p:dialog header="New Sensor" widgetVar="dlg" focus="name" modal="true" showEffect="fade">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="name" value="Name" />
<p:inputText id="name" label="name" value="#{newSensor.sensor.name}" />
.............................
</h:panelGrid>
<f:facet name="footer">
<p:commandButton id="ajax" value="Create Sensor" actionListener="#{newSensor.saveRecord()}" update=":new_sensor"/>
</f:facet>
</p:dialog>
</h:form>
<h:form id="form">
<p:dataTable id="tbl" var="sensor" value="#{sensors.systemSensors}"
.......
paginator="true" rows="12"
rowKey="#{sensor.model}">
<p:column headerText="Name" sortBy="#{sensor.name}" style="text-align: center">
<h:outputText value="#{sensor.name}" />
</p:column>
...................
</p:column>
</p:dataTable>
Beans:
#Named
#RequestScoped
public class Sensors implements Serializable
{
private List<SensorObj> sensors;
#PostConstruct
public void init()
{
sensors = generateSensors();
}
public List<SensorObj> getSystemSensors()
{
return sensors;
}
private List<SensorObj> generateSensors()
{
List list = new ArrayList();
SensorObj obj1 = new SensorObj("Sensor 1", "SBS0212", "Online", true, null);
list.add(obj1);
return list;
}
}
#Named
#RequestScoped
public class NewSensor implements Serializable
{
private SensorObj sensor = new SensorObj();
public SensorObj getSensor()
{
return sensor;
}
public void setSensor(SensorObj sensor)
{
this.sensor = sensor;
}
public void saveRecord(){
.....
}
}
When I submit the dialog with the new sensor I want to update the table. How I can implement this?
Should I use one managed bean for listing the content and adding new items or as it is it's better to use two?
I'm trying to create a filtering datatable with PrimeFaces framework.
My issue is that the datatable is displayed but filtering option doesn't work , help please !!
My page.xhtml looks like :
<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">
<ui:composition>
<h5>
<h:form>
<p:dataTable var="student" value="#{studentWizard.students}" widgetVar="studentTable" emptyMessage="Aucun élève trouvé" id="tableStudent" filteredValue="#{studentWizard.filteredStudents}" >
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Chercher tous les champs:" />
<p:inputText id="globalFilter" onkeyup="studentTable.filter()" style="width:150px" placeholder="Entrer le mot-clé"/>
</p:outputPanel>
</f:facet>
<p:column filterBy="#{student.studentCode}" headerText="Code de l'élève" filterMatchMode="contains">
<h:outputText value="#{student.studentCode}"/>
</p:column>
<p:column filterBy="#{student.firstName}" headerText="Prénom" filterMatchMode="contains">
<h:outputText value="#{student.firstName}"/>
</p:column>
<p:column filterBy="#{student.lastName}" headerText="Nom" filterMatchMode="contains">
<h:outputText value="#{student.lastName}"/>
</p:column>
<p:column headerText="Modifier" >
<p:commandButton value="Modifier" type="submit" ajax="false" icon="ui-icon-update"/>
</p:column>
</p:dataTable>
</h:form>
</h5>
</ui:composition>
</html>
and My Java Bean :
#ManagedBean(name="studentWizard")
#Component
#ViewScoped
public class StudentWizard implements Serializable {
public StudentWizard() {}
private static final long serialVersionUID = 1L;
private Student student;
private List<Student> students;
private List<Student> filteredStudents;
#PostConstruct
public void init() {
students = getAllStudent();
}
public List<Student> getFilteredStudents() {
return filteredStudents;
}
public void setFilteredStudents(List<Student> filteredStudents) {
this.filteredStudents = filteredStudents;
}
#Autowired
private StudentManager studentManager;
public void setStudentManager(StudentManager studentManager) {
this.studentManager = studentManager;
}
public Student getstudent() {
return student;
}
public StudentManager getStudentManager() {
return studentManager;
}
public void setstudent(Student student) {
this.student = student;
}
public void save() {
studentManager.saveStudent(student);
student = new Student();
}
public List<Student> getAllStudent() {
return studentManager.getAllStudent();
}
public Student getStudentById(int id) {
return studentManager.getStudentById(id);
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
This is my home web page
<h:body>
<p:layout style="min-width:400px;min-height:100px;">
<p:layoutUnit position="center" size="400" >
</p:layoutUnit>
</p:layout>
<p:layout style="min-width:400px;min-height:500px;">
<p:layoutUnit position="west" size="244" >
<h5>
<h:form>
<p:menu toggleable="true">
<p:submenu label="Eleves">
<p:menuitem value="Nouvel élève" action="#{menuView.setSelectedItem(1)}" update=":globalPanel" />
<p:menuitem value="Consultation" action="#{menuView.setSelectedItem(2)}" update=":globalPanel" />
</p:submenu>
<p:submenu label="Personnels">
</p:submenu>
<p:submenu label="Notes">
</p:submenu>
<p:submenu label="Caisses">
</p:submenu>
<p:submenu label="Salaires">
</p:submenu>
<p:submenu label="Référentiel">
</p:submenu>
</p:menu>
</h:form>
</h5>
</p:layoutUnit>
<p:layoutUnit position="center">
<h:panelGroup id ="globalPanel" >
<h:panelGroup id="inscriptionPanel" rendered="#{menuView.selectedItem == 1}" header="Inscription" style="margin-bottom:20px">
<ui:include src="/inscription.xhtml" />
</h:panelGroup>
<h:panelGroup id="testerPanel" rendered="#{menuView.selectedItem == 2}" header="Consultation" style="margin-bottom:20px" >
<ui:include src="/consul.xhtml" />
</h:panelGroup>
</h:panelGroup>
</p:layoutUnit>
</p:layout>
</h:body>
Good day!
I'm using JSF 2.1 Primefaces 4.0 Glassfish 3.2.1
In my Form.xhtml, I have this code.
<h:form id="modDlgFormc">
<p:dialog id="modIDc" header="Criteria Info"
showEffect="fade" hideEffect="fade" modal="true"
resizable="false" widgetVar="modDlgc" closable="false"
position="center" visible ="#{Fame.modVisiblec}">
<p:messages id="pmsgCrit" closable="true"/>
<h:panelGrid id="criteriapGrid" columns="1">
<h:panelGrid id="critLabelId" columns="2">
<p:selectOneMenu id="fieldNameId" value="#
{Fame.fieldName}" var="fieldSelect">
<f:selectItem itemLabel="Select Field Name"
itemValue="" />
<f:selectItems value="#{Fame.fieldNameMap}" />
<p:ajax event="change" update="fieldNameId
operandId" listener="#{Fame.fieldNameChange}"/>
</p:selectOneMenu>
<p:selectOneMenu id="operandId" value="#{Fame.operator}" >
<f:selectItem itemLabel="Select Operand" itemValue="" />
<f:selectItems value="#{Fame.operandMap}" />
<p:ajax event="change" update="operandId valueId"
listener="#{Fame.operandChange}" />
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid id="valueId" columns="2">
<c:if test="#{Fame.showValue == 'txt'}">
<h:outputLabel for="inputVal" value="Value : " style="font-weight: bolder"/>
<p:inputText id="inputVal" size="30" value="#{Fame.value}"/>
<c:if test="#{Fame.operator == 'Is Between'}">
<h:outputText value=""/>
<p:inputText size="30" value="#{Fame.value2}"/>
</c:if>
</c:if>
<c:if test="#{Fame.showValue == 'cal'}">
<h:outputLabel for="fromDateId" value="From : " style="font-weight: bolder"/>
<p:calendar id="fromDateId" value="#{Fame.date}" showButtonPanel="true" maxdate="#{Fame.maxDate}"/>
<c:if test="#{Fame.operator == 'Is Between'}">
<h:outputLabel for="toDateId" value="To : " style="font-weight: bolder"/>
<p:calendar id="toDateId" value="#{Fame.date2}" showButtonPanel="true" maxdate="#{Fame.maxDate}"/>
</c:if>
</c:if>
<c:if test="#{Fame.showValue == 'upload'}">
<h:outputText value=""/>
<p:commandButton value="UPLOAD" onclick="uconfirmation.show()" type="button" />
</c:if>
</h:panelGrid>
<h:panelGrid id="critBtnId" columns="4">
<p:commandButton id="addBtn" value="ADD" actionListener="#{Fame.saveCriteria}" update=":modDlgFormc:modIDc" rendered="#{empty Fame.editMode}" />
<p:commandButton value="SAVE" actionListener="#{Fame.updateCriteria}" update=":modDlgFormc:modIDc" rendered="#{not empty Fame.editMode}"/>
<p:commandButton value="CANCEL" actionListener="#{Fame.cancelCriteria}" update=":modDlgFormc" rendered="#{not empty Fame.editMode}"/>
<p:commandButton id="mCancelButtonc" value="CLOSE" update=":modDlgFormc:modIDc :wbookForm" actionListener="#{Fame.closealldialogsopen}"/>
</h:panelGrid>
<br/>
</h:panelGrid>
<center>
<h:panelGrid id="critDTable" columns="1">
<p:dataTable id="criteriaTbl" var="criteria" value="#{Fame.createdCriteria}" paginator="true" rows="5" rowIndexVar="rowIndex" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
currentPageReportTemplate="{totalRecords} record(s) in {totalPages} page(s)">
<p:column headerText="WORKSHEET NAME">
#{criteria.wsheetName}
</p:column>
<p:column headerText="FIELD NAME">
#{criteria.fieldName}
</p:column>
<p:column headerText="OPERATOR">
#{criteria.operator}
</p:column>
<p:column headerText="VALUE">
#{criteria.value}
</p:column>
<p:column headerText="UPDATE">
<p:panelGrid>
<p:row>
<p:column style="vertical-align: top;border: none">
<p:commandButton actionListener="#{Fame.editCri(rowIndex)}" style="width:30px;text-align:center;border:none;background-color:transparent;" icon="ui-icon-pencil" update=":modDlgFormc" />
<p:commandButton actionListener="#{Fame.deleteCri(rowIndex)}" style="width:30px;text-align:center;border:none;background-color:transparent;" icon="ui-icon-close" update=":modDlgFormc" />
</p:column>
</p:row>
</p:panelGrid>
</p:column>
</p:dataTable>
</h:panelGrid>
</center>
</p:dialog>
</h:form>
My Main code
#ManagedBean(name = "Fame")
#SessionScoped
private FameCriteriaDAOImpl fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
private ArrayList<FameCriteriaBean> createdCriteria = new ArrayList();
public void saveCriteria() {
fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
try {
if (this.validate() == true) {
//String wsheetId = fameManagementDP.getWsheetId(group_Id, workbookName);
FameCriteriaBean bean = new FameCriteriaBean();
bean.setWsheetId(this.worksheetId);
bean.setFieldName(this.fieldName);
bean.setOperator(this.operator);
bean.setValue(this.value);
String actionStr = "inserted";
fameCriteriaDAOImpl.save(bean);
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
error(converter.getConvertedError(sqlEx.getMessage()));
} finally {
this.initialize();
this.initializeCreatedCriteria();
this.resetCriteria();
}
}
My Bean code.
public class FameCriteriaBean {
private String wsheetName = "";
private String wsheetId = "";
private String fieldName = "";
private String operator = "";
private String value = "";
public FameCriteriaBean(){
}
/**
* #return the fieldName
*/
public String getFieldName() {
return fieldName;
}
/**
* #param fieldName the fieldName to set
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* #return the operator
*/
public String getOperator() {
return operator;
}
/**
* #param operator the operator to set
*/
public void setOperator(String operator) {
this.operator = operator;
}
/**
* #return the value
*/
public String getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
/**
* #return the wsheetId
*/
public String getWsheetId() {
return wsheetId;
}
/**
* #param wsheetId the wsheetId to set
*/
public void setWsheetId(String wsheetId) {
this.wsheetId = wsheetId;
}
/**
* #return the wsheetName
*/
public String getWsheetName() {
return wsheetName;
}
/**
* #param wsheetName the wsheetName to set
*/
public void setWsheetName(String wsheetName) {
this.wsheetName = wsheetName;
}
}
Below is the scenario.
I choose a fieldName then the lists of operand was loaded. This is correct.
I click the button ADD, then a p:message appear that there is no operand selected. This is correct.
I had noticed that the fieldname value that I was selected when error appears was gone.
My question is how not to refresh the value of fieldNameId so that I can use it after an error is displayed in p:message.
I'm using SessionScoped for my java class because I'm using p:wizard in Form.xhtml.
Please help me to solve this.
Thank you and More Power! :)
What I did is this.
Please see updated Main class
#ManagedBean(name = "Fame")
#SessionScoped
private FameCriteriaDAOImpl fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
private ArrayList<FameCriteriaBean> createdCriteria = new ArrayList();
public void saveCriteria() {
fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
if (!this.validate()) {
return;
}
try {
FameCriteriaBean bean = new FameCriteriaBean();
bean.setWsheetId(this.worksheetId);
bean.setFieldName(this.fieldName);
bean.setOperator(this.operator);
bean.setValue(this.value);
String actionStr = "inserted";
fameCriteriaDAOImpl.save(bean);
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
error(converter.getConvertedError(sqlEx.getMessage()));
} finally {
this.initialize();
this.initializeCreatedCriteria();
this.resetCriteria();
}
}
I try to update my PanelGrid from my CommandButton with update attribute, but it doesn't work:
<h:body>
<p:dialog id="dialog" header="Add Memo" widgetVar="dialogMemo" resizable="false" >
<h:form id="formDialog">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="commentInput" value="Comment:" />
<p:inputTextarea id="commentInput" value="#{dashboardBean.currentComment}" rows="6" cols="25" label="commentInput" required="true"/>
<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" update=":formPanel:myPanelGrid" oncomplete="dialogMemo.hide();" type="submit">
</p:commandButton>
<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="formPanel">
<p:commandButton id="addMemo" icon="ui-icon-plus" onclick="dialogMemo.show();" type="submit" actionListener="#{dashboardBean.getEditControl}"/>
<h:panelGrid id="myPanelGrid" columns="1" width="100%" >
</h:panelGrid>
</h:form>
</p:layoutUnit>
</h:body>
I set the actionListener of my commandButton("submitDialog") dynamically, when i click to commandButton("addMemo").
The method is properly called, but the panelGrid("myPanelgrid") is not updated.
When i reload the page all components are properly displayed. But for me the update attribute of "submitDialog" is correctly set.
My methods to add panels dynamically,the first is called in postConstruct method(component is displayed correctly) and the second is called in commandButton("SubmitDialog") actionListener(Panelgrid is not Updated):
public void createMemoList()
{
if (panelGridUI != null && _countMemos > 0)
{
for (int i = 0; _countMemos > i; i++)
{
int u = _memosId.get(i);
Panel panel = (Panel)_application.createComponent(FacesContext.getCurrentInstance(), "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
MethodExpression editExpression = _ef.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{panelListener.handleEdit}", Void.class, new Class[]{ActionEvent.class});
MethodExpression me = _ef.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{panelListener.handleClose}", null, new Class[]{AjaxBehaviorEvent.class});
AjaxBehavior ajaxBehavior = new AjaxBehavior();
Draggable draggable = new Draggable();
panel.setId("mymemo_" + String.valueOf(u));
panel.setHeader(_userNames.get(i));
panel.setClosable(true);
panel.setToggleable(true);
HtmlOutputText memo = new HtmlOutputText();
memo.setValue(_userMemos.get(i));
memo.setId("text_" + String.valueOf(u));
panel.getChildren().add(memo);
HtmlPanelGroup panelGroup = new HtmlPanelGroup();
panelGroup.setId("group_" + u);
CommandButton button = new CommandButton();
button.setIcon("ui-icon-pencil");
button.addActionListener(new MethodExpressionActionListener(editExpression));
button.setOnclick("dialogMemo.show()");
button.setStyle("width:20px;height:20px;margin-right:5px;");
HtmlOutputText header = new HtmlOutputText();
header.setValue(_userNames.get(i));
header.setStyle("font-size:15px;");
panelGroup.getChildren().add(button);
panelGroup.getChildren().add(header);
panel.getFacets().put("header", panelGroup);
ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(me, me));
panel.addClientBehavior("close", ajaxBehavior);
draggable.setFor("mymemo_" + String.valueOf(u));
draggable.setRevert(true);
draggable.setHandle(".ui-panel-titlebar");
draggable.setStack(".ui-panel");
getPanelGrid().getChildren().add(panel);
getPanelGrid().getChildren().add(draggable);
}
}
}
public void createLastMemo()
{
if (panelGridUI != null && _countMemos > 0)
{
int u = _memosId.get(_countMemos - 1);
Panel panel = (Panel)_application.createComponent(FacesContext.getCurrentInstance(), "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
MethodExpression editExpression = _ef.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{panelListener.handleEdit}", Void.class, new Class[]{ActionEvent.class});
MethodExpression me = _ef.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{panelListener.handleClose}", null, new Class[]{AjaxBehaviorEvent.class});
AjaxBehavior ajaxBehavior = new AjaxBehavior();
Draggable draggable = new Draggable();
panel.setId("mymemo_" + String.valueOf(u));
panel.setHeader(_userNames.get(_countMemos - 1));
panel.setClosable(true);
panel.setToggleable(true);
HtmlOutputText memo = new HtmlOutputText();
memo.setValue(_userMemos.get(_countMemos - 1));
memo.setId("text_" + String.valueOf(u));
panel.getChildren().add(memo);
HtmlPanelGroup panelGroup = new HtmlPanelGroup();
panelGroup.setId("group_" + String.valueOf(u));
CommandButton button = new CommandButton();
button.setIcon("ui-icon-pencil");
button.addActionListener(new MethodExpressionActionListener(editExpression));
button.setOnclick("dialogMemo.show()");
button.setStyle("width:20px;height:20px;margin-right:5px;");
HtmlOutputText header = new HtmlOutputText();
header.setValue(_userNames.get(_countMemos - 1));
header.setStyle("font-size:15px;");
panelGroup.getChildren().add(button);
panelGroup.getChildren().add(header);
panel.getFacets().put("header", panelGroup);
ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(me, me));
panel.addClientBehavior("close", ajaxBehavior);
draggable.setFor("mymemo_" + String.valueOf(u));
draggable.setRevert(true);
draggable.setHandle(".ui-panel-titlebar");
draggable.setStack(".ui-panel");
getPanelGrid().getChildren().add(panel);
getPanelGrid().getChildren().add(draggable);
}
}
And this method is where i set the actionListener to my commandButton("addMemo")
:
public void getEditControl()
{
System.out.println("I am in getEditContol!!!");
UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot();
CommandButton button = (CommandButton) view.findComponent("formDialog:submitDialog");
for(ActionListener act : button.getActionListeners()) {
button.removeActionListener(act);
}
MethodExpression getLastmemo = _ef.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{dashboardBean.getLastMemo}", Void.class, new Class[]{ActionEvent.class});
button.addActionListener(new MethodExpressionActionListener(getLastmemo));
}
My MethodExpression("getLastMemo") call my method createLastmemo. ActionListener is correctly called, but the view is not updated. I am in ViewScoped.
I have a form with some inputs which has a ViewScoped *ManagedBean* behind. At the bottom of the form I have a CommandButton for saving the data. There is a datatable on the form which new items could be added by entering data to an input and clicking another CommandButton. When user filled all the inputs and added any items to the datatable he/she can click the save button. But I have some problems in controling the add button and updating the datamodel. When I set the immadiate of the button to true the value of the input won't update and when I set it to false validation error will happen for the rest of the inputs on the form!!!
Code if it helps:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./templates/master.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns="http://www.w3.org/1999/xhtml">
<ui:define name="windowTitle">
#{lbls.registerWaggon}
</ui:define>
<ui:define name="sectionTitle">
<h:panelGroup layout="block" styleClass="sectionTitle">
<h:graphicImage library="img" name="railways.png"/>
</h:panelGroup>
</ui:define>
<ui:define name="right">
<ui:include src="templates/railwaysright.xhtml"/>
</ui:define>
<ui:define name="extraCSS">
<h:outputStylesheet library="css" name="persiancalendar.css"/>
<h:outputStylesheet library="css" name="grid.css"/>
</ui:define>
<ui:define name="extraJS">
<h:outputScript library="js" name="lib/persiancalendar.js"/>
</ui:define>
<ui:define name="content">
<h:panelGroup rendered="#{!current.hasLoggedIn()}">
<h:panelGroup layout="block" styleClass="warningBox">
<h:outputText value="#{app.youHaveNotLoggedIn}"/>
<br/>
<h:link value="#{lbls.login}" outcome="login"/>
</h:panelGroup>
</h:panelGroup>
<p:panel rendered="#{current.hasLoggedIn() and requestWaggon.isViewable()}">
<f:facet name="header">
<h:outputText value="#{lbls.registerWaggonLong}" />
</f:facet>
<h:form id="frmRequest">
<h:panelGrid columns="3" footerClass="buttons">
<h:outputText value="#{lbls.number}:"/>
<h:inputText id="number" label="#{lbls.number}" styleClass="ltr" value="#{requestWaggon.request.number}" readonly="true" />
<h:message for="number" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.requestDate}:"/>
<h:inputText styleClass="ltr" id="date" label="#{lbls.requestDate}" value="#{requestWaggon.request.date}" required="true" readonly="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
<h:message for="date" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.nameOfMaterialOwner}:"/>
<h:inputText id="ownerName" label="#{lbls.nameOfMaterialOwner}" value="#{requestWaggon.request.fullName}" required="true" readonly="true"/>
<h:message for="ownerName" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.companyName}:"/>
<h:inputText id="companyName" label="#{lbls.companyName}" value="#{requestWaggon.request.companyName}" required="true" readonly="true"/>
<h:message for="companyName" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.nameOfMaterial}:"/>
<h:inputText id="nameOfMaterial" label="#{lbls.nameOfMaterial}" value="#{requestWaggon.request.materialName}" required="true" readonly="true"/>
<h:message for="nameOfMaterial" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.materialWeight}:"/>
<h:panelGroup>
<h:inputText id="materialWeight" styleClass="ltr" label="#{lbls.materialWeight}" value="#{requestWaggon.request.materialWeight}" required="true" style="min-width: 0px; width: 60px" readonly="true"/>
<h:outputText value=" #{requestWaggon.request.weightUnit}"/>
</h:panelGroup>
<h:message for="materialWeight" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.senderAddress}:"/>
<h:inputText id="senderAddress" label="#{lbls.senderAddress}" value="#{requestWaggon.request.address}" required="true" style="width: 350px;" readonly="true"/>
<h:message for="senderAddress" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.receiverAddress} (#{lbls.country}):"/>
<h:outputText value="#{requestWaggon.request.country}"/>
<h:message for="country" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.station}:"/>
<h:inputText id="station" label="#{lbls.station}" value="#{requestWaggon.request.station}" required="true" readonly="true"/>
<h:message for="station" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.loadingDate}:"/>
<h:panelGroup>
<h:inputText styleClass="ltr" id="loadingDate" label="#{lbls.loadingDate}" value="#{requestWaggon.request.loadingDate}" required="true" readonly="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
</h:panelGroup>
<h:message for="loadingDate" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.boundryStation}:"/>
<h:outputText value="#{requestWaggon.request.bountryStation}"/>
<h:message for="boundryStation" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value=""/>
<h:outputText value=""/>
<h:outputText value=""/>
<h:outputText value="#{lbls.confirmDate}:"/>
<h:panelGroup>
<h:inputText styleClass="date ltr" id="confirmDate" label="#{lbls.confirmDate}" value="#{requestWaggon.request.confirmDate}" required="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
<input type="button" value="..." onclick="displayDatePicker('frmRequest:confirmDate', this);" class="datePicker"/>
</h:panelGroup>
<h:message for="confirmDate" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.confirm}:" styleClass="b"/>
<h:selectOneMenu value="#{requestWaggon.request.confirm}">
<f:selectItem/>
<f:selectItems value="#{searchRequest.allConfirms}" var="confirm" itemLabel="#{searchRequest.confirmCaption(confirm)}" itemValue="#{confirm}"/>
</h:selectOneMenu>
<h:message for="confirm" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.description}:"/>
<h:inputText id="description" label="#{lbls.description}" value="#{requestWaggon.request.confirmDescription}" required="false" style="width: 350px;"/>
<h:message for="description" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.waggonType}:"/>
<h:selectOneMenu id="waggonType" label="#{lbls.waggonType}" value="#{requestWaggon.request.waggonType}" required="true">
<f:selectItem/>
<f:selectItems value="#{requestWaggon.waggonTypes}"/>
<f:converter converterId="ir.khorasancustoms.CatalogValueFixedConverter"/>
</h:selectOneMenu>
<h:message for="waggonType" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
**<h:outputText value="#{lbls.specialWaggonNumber}:"/>
<h:panelGroup>
<h:inputText id="specialWaggonNumber" label="#{lbls.specialWaggonNumber}" binding="#{requestWaggon.waggonNumberComponent}" />
<h:commandButton value="#{lbls.add}" action="#{requestWaggon.addWaggon}" immediate="true"/>
</h:panelGroup>
<h:message for="specialWaggonNumber" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>**
<h:outputText value="#{lbls.waggons}:"/>
<h:dataTable value="#{requestWaggon.waggonsDataModel}" var="waggon" columnClasses="index,,action" styleClass="grid" headerClass="title" rowClasses="two,three,one">
<h:column>
<f:facet name="header">#{lbls.index}</f:facet>
<h:outputText value="#{searchRequest.datamodel.rowIndex + 1}"/>
</h:column>
<h:column>
<f:facet name="header">#{lbls.number}</f:facet>
<h:outputText value="#{waggon.number}"/>
</h:column>
<h:column>
<f:facet name="header">#{lbls.action}</f:facet>
<h:commandLink action="delete">
<h:graphicImage styleClass="nb" alt="#{lbls.delete}" title="#{lbls.delete}" library="img" name="delete.png"/>
<f:param name="id" value="#{waggon.id}"/>
</h:commandLink>
</h:column>
</h:dataTable>
<f:facet name="footer">
<h:button outcome="searchrequest" value="#{lbls.cancel}" rendered="#{requestWaggon.id ne null}"/>
<h:commandButton action="#{requestWaggon.doNew}" value="#{lbls.new}" rendered="#{requestWaggon.request.id ne null}"/>
<h:commandButton action="#{requestWaggon.save}" value="#{lbls.ok}"/>
</f:facet>
</h:panelGrid>
<h:outputScript>
focusElement('frmRequest:confirmDate');
</h:outputScript>
</h:form>
<f:facet name="footer">
<h:messages styleClass="boxMessages" layout="table" infoClass="infoBox" warnClass="warningBox" errorClass="errorBox" fatalClass="errorBox" globalOnly="true"/>
<h:link outcome="searchrequest" value="#{lbls.searchRequestWaggon}"/>
</f:facet>
</p:panel>
<p:panel rendered="#{current.hasLoggedIn() and !requestWaggon.isViewable()}">
<h:panelGroup layout="block" styleClass="warningBox">
<h:outputText value="#{app.accessDenied}" />
</h:panelGroup>
</p:panel>
</ui:define>
</ui:composition>
bean
#ManagedBean(name = "requestWaggon")
#ViewScoped
public class RequestWaggonBean {
//<editor-fold defaultstate="collapsed" desc="FIELDS">
private Logger logger;
#ManagedProperty(value = "#{current}")
private CurrentSessionBean current;
private RequestWaggon request;
private Set<CatalogValue> weightUnits;
private Set<CatalogValue> countries;
private Set<CatalogValue> boundryStations;
private Set<CatalogValue> waggonTypes;
private Integer id;
#ManagedProperty(value = "#{searchRequest}")
private SearchRequestBean searchRequest;
private Integer newWaggonNumber;
private HtmlInputText waggonNumberComponent;
private DataModel<Waggon> waggonsDataModel;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="CONSTRUCTORS">
public RequestWaggonBean() {
logger = LogUtil.getLogger(RequestWaggonBean.class);
request = new RequestWaggon();
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest httpRequest = (HttpServletRequest) exContext.getRequest();
String strId = httpRequest.getParameter("id");
try {
id = Integer.parseInt(strId);
} catch (Exception ex) {
logger.fatal(ex);
}
}
#PostConstruct
public void init() {
request.setDate(current.getDate());
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
//session.beginTransaction();
if (id != null) {
request = (RequestWaggon) session.get(RequestWaggon.class, id);
}
Query query = session.createQuery("from CatalogGroup as catalogGroup where catalogGroup.englishTitle = :englishTitle");
query.setParameter("englishTitle", "WeightUnit");
CatalogGroup weightUnit = (CatalogGroup) query.uniqueResult();
weightUnits = weightUnit.getValues();
query.setParameter("englishTitle", "Country");
CatalogGroup country = (CatalogGroup) query.uniqueResult();
countries = country.getValues();
query.setParameter("englishTitle", "BoundryStation");
CatalogGroup boundryStation = (CatalogGroup) query.uniqueResult();
boundryStations = boundryStation.getValues();
query.setParameter("englishTitle", "WaggonType");
CatalogGroup waggonType = (CatalogGroup) query.uniqueResult();
waggonTypes = waggonType.getValues();
//session.getTransaction().commit();
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
Waggon[] arrayWaggons = new Waggon[request.getWaggons().size()];
arrayWaggons = request.getWaggons().toArray(arrayWaggons);
waggonsDataModel = new ArrayDataModel<Waggon>(arrayWaggons);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="METHODS">
public void save() {
boolean canSave = false;
String cantSaveMessage = "";
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
session.beginTransaction();
int number = 0;
if (request.getNumber() == null) {
number = RequestWaggon.nextNumber();
}
if (request.getNumber() != null || number > 0) {
if (request.getNumber() == null) {
request.setNumber(number);
canSave = isInsertable();
cantSaveMessage = app.getString("insertDenied");
} else {
canSave = isEditable();
cantSaveMessage = app.getString("editDenied");
}
if (canSave) {
session.saveOrUpdate(request);
RequestWaggonHistory history = new RequestWaggonHistory(request, current.getUser(), number > 0 ? 'I' : 'U', current.getIP());
session.save(history);
session.getTransaction().commit();
String message = app.getString("savedSuccessfully");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, cantSaveMessage, cantSaveMessage));
}
} else {
logger.fatal("Getting next number failed!");
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
}
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
}
public void addWaggon(ValueChangeEvent event) {
ResourceBundle app = ResourceBundle.getBundle("application");
String strNewWaggonNumber = event.getNewValue().toString();
Integer newWaggonNumber = Integer.parseInt(strNewWaggonNumber);
if (newWaggonNumber == null || newWaggonNumber <= 0) {
String message = app.getString("EnterWaggonNumber");
FacesContext.getCurrentInstance().addMessage("frmRequest:specialWaggonNumber", new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
} else {
Waggon newWaggon = new Waggon();
newWaggon.setNumber(newWaggonNumber);
request.getWaggons().add(newWaggon);
Waggon[] arrayWaggons = new Waggon[request.getWaggons().size()];
arrayWaggons = request.getWaggons().toArray(arrayWaggons);
waggonsDataModel = new ArrayDataModel<Waggon>(arrayWaggons);
}
}
public boolean isViewable() {
return current.isViewable();
}
public boolean isDeletable() {
return current.isDeletable() && request.getWaggons().isEmpty();
}
public boolean isInsertable() {
return current.isInsertable();
}
public boolean isEditable() {
return current.isEditable() && request.getConfirm() == null;
}
public void doNew() {
request = new RequestWaggon();
request.setDate(current.getDate());
}
public String delete() {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
session.beginTransaction();
session.delete(request);
RequestWaggonHistory history = new RequestWaggonHistory(request, current.getUser(), 'D', current.getIP());
session.save(history);
session.getTransaction().commit();
searchRequest.search();
String message = app.getString("deletedSuccessfully");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
} catch (ConstraintViolationException ex) {
String message = app.getString("constraintViolation");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, message, message));
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
return "searchrequest";
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="PROPERTIES">
public RequestWaggon getRequest() {
return request;
}
public void setRequest(RequestWaggon requestWaggon) {
this.request = requestWaggon;
}
public CurrentSessionBean getCurrent() {
return current;
}
public void setCurrent(CurrentSessionBean current) {
this.current = current;
}
public Set<CatalogValue> getWeightUnits() {
return weightUnits;
}
public void setWeightUnits(Set<CatalogValue> weightUnits) {
this.weightUnits = weightUnits;
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public Set<CatalogValue> getCountries() {
return countries;
}
public void setCountries(Set<CatalogValue> countries) {
this.countries = countries;
}
public Set<CatalogValue> getBoundryStations() {
return boundryStations;
}
public void setBoundryStations(Set<CatalogValue> boundryStations) {
this.boundryStations = boundryStations;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public SearchRequestBean getSearchRequest() {
return searchRequest;
}
public void setSearchRequest(SearchRequestBean searchRequest) {
this.searchRequest = searchRequest;
}
public Set<CatalogValue> getWaggonTypes() {
return waggonTypes;
}
public void setWaggonTypes(Set<CatalogValue> waggonTypes) {
this.waggonTypes = waggonTypes;
}
public Integer getNewWaggonNumber() {
return newWaggonNumber;
}
public void setNewWaggonNumber(Integer newWaggonNumber) {
this.newWaggonNumber = newWaggonNumber;
}
public DataModel<Waggon> getWaggonsDataModel() {
return waggonsDataModel;
}
public void setWaggonsDataModel(DataModel<Waggon> waggonsDataModel) {
this.waggonsDataModel = waggonsDataModel;
}
public HtmlInputText getWaggonNumberComponent() {
return waggonNumberComponent;
}
public void setWaggonNumberComponent(HtmlInputText waggonNumberComponent) {
this.waggonNumberComponent = waggonNumberComponent;
}
//</editor-fold>
}
The h:commandButton submits the whole form and all elements will be validated. You can use ajax to do a partial submit. Try the following:
Give your datatable an id value. So you can reference it from your commandButton:
<h:panelGroup id="tableWrapper">
<h:datatable id="mytable" value="#{requestWaggon.waggonsDataModel}" ..>
...
</h:datatable>
</h:panelGroup>
Then put an <f:ajax> inside your commandButton. The render and execute attributes must contain the id of your datatable; immediate=true is not needed:
<h:commandButton value="#{lbls.add}" action="#{requestWaggon.addWaggon}">
<f:ajax render="tableWrapper" execute="mytable"/>
</h:commandButton>