How to set null value selectone menu jsf - primefaces

I am using PrimeFaces 5.1 , I have a field Cumulative indicator which is a select drop down wit Y/N/select, when I update the value to Y/N the edit/update is happening fine, but when I chose select as the drop down value it does not update it to null. I am able to set the value to null from the backend. When I chose select as the drop down value it should update to null instead it shows the previous value(Y/N) that is saved in the database. The below is my code xhtml, java bean and the update query. Please advice why its not updating the value to null value.
I tried putting the drop down value itemValue="#{null}" but that didn't work as mentioned in this post How to save Null value with selectone dropdown
Below is my xhtml:
<p:column headerText="Cumulative Indicator" width="60">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#
{AcctRefRecord.cumIndicator}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{AcctRefRecord.cumIndicator}"
label="Cumulative Indicator">
<f:selectItem
itemLabel="--Select--" itemValue="" />
<f:selectItem
itemValue="Y" />
<f:selectItem
itemValue="N" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:dataTable id="dtable" var="AcctRefRecord"value="#
{AcctRefMBean.
AcctRefRecords}" editable="true"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink}
{PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}
{RowsPerPageDropdown}" >
<p:ajax event="rowEdit" listener="#
{AcctRefMBean.onRowEdit}" update=":dtableform:msgs" resetValues="true"/>
<p:ajax event="rowEditCancel" listener="#
{AcctRefMBean.onRowCancel}" update=":dtableform:msgs"/>
Below is my javaBean:
//retrive the record/row of type
AcctRefTo on which edit even occurred
AcctRefTo to = (AcctRefTo)
event.getObject();
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
facesContext.getExternalContext().getSession(false);
String userId = (String)
session.getAttribute(WebAppConstants.CURRENT_USER_ID);
if (userId == null) {
userId = WebAppConstants.DEFAULT_CURRENT_USER_ID;
}
to.setUpdatedByUserID(userId);
updateRecord(to);
FacesMessage msg = new FacesMessage("Reference Data Updated for Account#"
+ to.getAcctNbr());
FacesContext.getCurrentInstance
().addMessage("null", msg);
}
/**
* #param to
* updates the given to in DB accordingly
*/
public void updateRecord(AcctRefTo to) {
jetSessionFacadebean.updateAccntRef(to);
}
Below is my updateQuery:
<key><value>updateAcctgRef</value></key>
<value>
update acct_ref set
cd_val=?,
dt_eff_end=?,
ind_bal=?,
ind_bal_acct_type=?,
ind_cum=?,
ind_net=?,
ind_net__bal_type=?,
ind__rcn=?,
ind_b=?,
nbr_gl_acct_yeb_offst=?,
nbr_gl_acct_net_unam_bal=?,
cd_fee_cat_type=?,
id_lst_updt=?,

Related

How to use "sortBy" in a p:dataTable with HashSet collection

UPDATED
I have the following dataTable:
<p:dataTable id="shipOwnerCompanyHistoriesTable" widgetVar="shipOwnerCompanyHistoriesTable" var="entry" value="#{shipRegisterView.ship.shipOwnerCompanyHistories}" rowKey="#{entry}" selectionMode="single" selection="#{shipRegisterView.selectedShipOwnerCompanyHistory}"
styleClass="margin-bottom-10" paginator="true" rows="5"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10" emptyMessage="Δεν βρέθηκαν εγγραφές.">
<p:ajax event="rowSelect" update="#form" listener="#{shipRegisterView.selectShipOwnerCompanyHistory}" />
<p:ajax event="rowUnselect" update="#form" listener="#{shipRegisterView.unselectShipOwnerCompanyHistory}" />
<p:column headerText="Πλοιοκτησία">
<h:outputText value="#{entry.company.brandNameGreek} / #{entry.company.brandNameLatin}"/>
</p:column>
<p:column headerText="Από" sortBy="#{entry.fromDate}">
<h:outputText value="#{entry.fromDate}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column headerText="Έως" sortBy="#{entry.toDate}">
<h:outputText value="#{entry.toDate}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column headerText="Ποσοστό" sortBy="#{entry.percentage}">
<h:outputText value="#{entry.percentage}%"/>
</p:column>
<p:column headerText="Σημειώσεις">
<h:outputText value="#{entry.comments}" rendered="#{entry.comments != null and not empty entry.comments}"/>
<h:outputText value="-" rendered="#{entry.comments == null or empty entry.comments}"/>
</p:column>
</p:dataTable>
With the value being taken from the follwoing view class like so:
public ShipRegisterView() {
newFlagHistory = new ShipFlagHistory();
lossState = "";
growlId = "shipMessages";
ship = new Ship();
ship.setLossState("Normal");
shipList = new ArrayList<Ship>();
newEncumbrance = new ShipEncumbrance();
newFek = new ShipFek();
newShipEngine = new ShipEngine();
newShipRenameHistory = new ShipRenameHistory();
newTransferHistory = new ShipTransferHistory();
newShipOwnerCompanyHistory = new ShipOwnerCompanyHistory();
newShipOwnerNaturalPersonHistory = new ShipOwnerNaturalPersonHistory();
newShipAdminCompanyHistory = new ShipAdminCompanyHistory();
newShipUtilizationCompanyHistory = new ShipUtilizationCompanyHistory();
newShipOwnerCompanyHistory.setCompany(new Company());
newShipOwnerNaturalPersonHistory.setNaturalPerson(new NaturalPerson());
newShipAdminCompanyHistory.setCompany(new Company());
newShipUtilizationCompanyHistory.setCompany(new Company());
newConditionHistory = new ShipConditionHistory();
newRecreationalLicense = new RecreationalLicense();
newRecreationalLicense.setAdminClassAct(new AdminClassAct());
newRecreationalLicense.setAdminDeclassAct(new AdminDeclassAct());
searchInspectionsList = new ArrayList<Inspection>();
searchCertificatesList = new ArrayList<Certificate>();
searchRosCertificatesList = new ArrayList<Certificate>();
searchAffirmationsList = new ArrayList<Affirmation>();
newNaturalPerson = new NaturalPerson();
newNaturalPerson.setAddress(new Address());
searchNaturalPerson = new NaturalPerson();
harboursForShipsForDNPUser = new ArrayList<Harbour>();
fines = new ArrayList<Fine>();
complaints = new ArrayList<Complaint>();
completedRoutes = new ArrayList<CompletedRoute>();
searchOwnerCompany = new SearchCompany();
searchOwnerNaturalPerson = new SearchNaturalPerson();
searchAdminCompany = new SearchCompany();
searchUtilizationCompany = new SearchCompany();
ship.setShipEngines(new HashSet<ShipEngine>());
ship.setShipAdminCompanyHistories(new HashSet<ShipAdminCompanyHistory>());
ship.setShipOwnerCompanyHistories(new HashSet<ShipOwnerCompanyHistory>());
ship.setShipOwnerNaturalPersonHistories(new HashSet<ShipOwnerNaturalPersonHistory>());
ship.setShipUtilizationCompanyHistories(new HashSet<ShipUtilizationCompanyHistory>());
ship.setShipEncumbrances(new HashSet<ShipEncumbrance>());
ship.setShipConditionHistories(new ArrayList<ShipConditionHistory>());
ship.setShipFeks(new HashSet<ShipFek>());
ship.setDocuments(new HashSet<AccompanyingFile>());
ship.setShipPhotos(new HashSet<ShipPhoto>());
ship.setShipFlagHistories(new HashSet<ShipFlagHistory>());
ship.setRecreationalLicenses(new HashSet<RecreationalLicense>());
ship.setShipTransferHistories(new HashSet<ShipTransferHistory>());
ship.setLossTheftDecisions(new HashSet<LossTheftDecision>());
ship.setShipRenameHistories(new HashSet<ShipRenameHistory>());
List<ShipOwnerCompanyHistory> list = new ArrayList<>(shipOwnerCompanyHistories);
};
The thing i am trying to do is to sort the columns of the table using the sortBy attribute of primefaces. When i press the column, i get the following error on the webpage:
And on my tomcat:
ERROR (com.liferay.faces.bridge.context.internal.ExceptionHandlerAjaxImpl.java:71).handle - Data type should be java.util.List or javax.faces.model.ListDataModel instance to be sortable.
Now, i understand that it has to be a list in order to work, but is there a way where i can sort the table? Hibernate mapping is a set too:
<set name="shipOwnerCompanyHistories" inverse="true" cascade="all-delete-orphan" lazy="false" >
<key column="shipId" on-delete="cascade"/>
<one-to-many class="gr.yptp.hcg.sr.Model.ShipOwnerCompanyHistory"/>
</set>
Let me know. I really appreciate your help.
Instead of
ship.setShipOwnerCompanyHistories(new HashSet<ShipOwnerCompanyHistory>());
and further on
List<ShipOwnerCompanyHistory> list = new ArrayList<>(shipOwnerCompanyHistories);
(where the list variable is nowhere used anymore, doesn't it have a yellow squirreled lin under it in your IDE?)
Do
ship.setShipOwnerCompanyHistories(new ArrayList<>(new HashSet<ShipOwnerCompanyHistory>()));
or just
ship.setShipOwnerCompanyHistories(new ArrayList<ShipOwnerCompanyHistory>());
or you you retrieved the shipOwnerCompanyHistories variable (assuming it is a HashSet from the database, do
ship.setShipOwnerCompanyHistories(new ArrayList<>(shipOwnerCompanyHistories));

How to Persist Rows after Reordering p:dataTable rows in backing bean

I am using Primefaces Datatable to show the data, i have used draggablerows and trying to save/persist the reordering of the rows in the backing bean
with
I can get the from and to indexes from the event. But, I was not able to persist the row reordering:
<p:dataTable value="#{EmployeeHandler.model.employees}" var="employee" draggableRows="true">
<p:ajax event="rowReorder" listener="#{EmployeeHandler.onRowReorder}"/>
<p:column>
<h:outputText value="#{employee.id}"/
</p:column>
<p:column>
<h:outputText value="#{employee.firstName}"/
</p:column>
<p:column>
<h:outputText value="#{employee.lastName}"/
</p:column>
</p:dataTable>
I tried
public void onRowReorder(ReorderEvent event) {
List<Employee> employees = model.getEmployees (new order in the employees list);
fromIndex = event.getFromIndex();
toIndex = event.getToIndex();
// swapping indexes
Collections.swap(employees, fromIndex, toIndex);
}

PrimeFaces <p:cellEditor> not changing value of variable

I've done some research and haven't been able to find anything that directly addresses the problem I've been having.
I have a DataTable column that is editable (by cell) and I have the ability to click on the cell, enter a new number in the cell editor box, but when I hit the cell editor closes but does not save the new value (same thing happens if you just click off and don't hit enter).
Here is the Code Snippet
<h:form>
<c:forEach items="#{extensionsBean.getPhases()}" var="phase">
<p:fieldset legend="#{phase.getPhaseName()}">
<p:dataTable value="#{extensionsBean.getActivities(phase)}" var="activity" editable="true" editMode="cell">
<p:column>
<f:facet name="header">
<h:outputText value="Actual Hours"/>
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{activity.getEstimateDetail().actualHours}"/>
</f:facet>
<f:facet name="input">
<h:inputText value="#{activity.getEstimateDetail().actualHours}" />
</f:facet>
</p:cellEditor>
//the rest of the closing tags are present
Any suggestions would be great! For the record, I have basically the exact same setup in a different xhtml page and I'm able to edit each of the cells without a problem. Not sure what's causing this one to bug out on me.
Add Ajax event cellEdit and store the values
Add ajax event celledit and where do you want save the value you can save it.
Code is below in my project
Xhtml page(Primefaces):
<p:dataTable var="my" value="#{java.custom_info}" editMode="cell" editable="true" style="font-size: 12px">
<p:ajax event="cellEdit" listener="#{java.custom_detail}"/>
<p:column style="background: white">
<h:outputText value="First Name"/>
</p:column>
<p:column style="background: white">
<p:cellEditor>
<f:facet name="output"> <h:outputText value="#{my.first}"/> </f:facet>
<f:facet name="input"><p:inputText value="#{my.first}" placeholder="Enter First Name" style="width:93%"/></f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
Java Class
public void custom_detail(CellEditEvent event){
String old_str = (String) event.getOldValue();
String first_name = (String) event.getNewValue();
System.out.println("update method reached..."+first_name);
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Query db = new Query();
Customer bean = new Customer();
if(session!=null){
if(((String)session.getAttribute("login"))!=null){
Calendar currentDate=Calendar.getInstance();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datenow=format.format(currentDate.getTime());
session.setAttribute("firstname", first_name);
session.setAttribute("modified_date",datenow);
bean.setFirst(first_name);
bean.setUsrid((String)session.getAttribute("user"));
bean.setUsr_modified(datenow);
db.update_personalinfo(bean);
}
}
}

Save checkbox state After ReLoadThe Page in JSF Primefaces

Im using a "DataTable - Selection",(http://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml) in primefaces 5 to check the selected rows, but when I reload the page, the checkboxes are unchecked, How can i keep the state of the checkboxes in session?
**
*********DataTable****************
**
<p:dataTable var="var" value="#{vistaBean.listaFichero}" rowKey="#{var.nombre}" paginator="true" rows="10"
selection="#{vistaBean.selectFichero}">
<f:facet name="header">
Votar ProductBox
</f:facet>
<p:column headerText="Votar" selectionMode="multiple"/>
<p:column headerText="Nombre del Fichero">
<h:outputText value="#{var.nombre}" />
</p:column>
<p:column headerText="Ver/Descargar">
<h:commandLink id="pdf" action="#{vistaBean.downLoad}">
<f:setPropertyActionListener target="#{vistaBean.ruta}" value="#{var.ruta}" />
<h:graphicImage library="images" name="pdf.png" />
</h:commandLink>
</p:column>
</p:dataTable>
<p:commandButton value="Guardar Votos" action="#{vistaBean.addVoto()}" update="msgs"/>
<p:commandButton value="Ver Votos" update="display" oncomplete="PF('dlg').show()" icon="ui-icon-check" inmediate="true"/>
<p:dialog header="Product Box Seleccionados" modal="true" showEffect="clip" widgetVar="dlg" resizable="false">
<p:outputPanel id="display">
<p:dataList value="#{vistaBean.selectFichero}" var="v">
#{v.nombre}
</p:dataList>
</p:outputPanel>
</p:dialog>
I solve the issue by installing a newer version of Primefaces, 5.2, i had the 5.1 and it had that bug.
This is how you set a session variable:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("foo", "bar");
This is how you can get session variables:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements())
{
String attr = (String)e.nextElement();
System.err.println(" attr = "+ attr);
Object value = session.getValue(attr);
System.err.println(" value = "+ value);
}
Your only task is to save the state of your checkboxes into the session and then load it.

How to use jsf to edit some data in a database

i have an app that displays some data entered in a databse, this should allow a user to delete or edit this information, so far i have managed to get it to delete, but i am wondering, what is the best method for editting the data, what i would like if possible is to click on an edit button on a page already populated with the data and this to take the user to a webpage that has only that selected records pre populating textboxs and then allow the user to edit these, how would i do this ?
this is how i am deleting a row from the database
<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
User ID
</f:facet>
#{u.userID}
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
#{u.name}
</p:column>
<p:column>
<f:facet name="header">
Email
</f:facet>
#{u.email}
</p:column>
<p:column>
<f:facet name="header">
Address
</f:facet>
#{u.address}
</p:column>
<p:column>
<f:facet name="header">
Created Date
</f:facet>
#{u.created_date}
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
</p:column>
<p:column>
<f:facet name="header">
Edit
</f:facet>
<h:commandButton value="Edit" action="{user.delete(u.userID)}" />
</p:column>
</p:dataTable>
and this is the backing bean allowing me to delete
public void delete(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "DELETE FROM user1 WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row deleted successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks
EDIT
i have figured out how to update the data, my question is now simply, how do i get the data from a row and populate a new page with input boxes with the selected data Or even better would be to edit the data live in the table, is this possilbe
instead of taking the user to a second page to edit the data, you can make use of primfaces DataTable - Row Editing see this
http://www.primefaces.org/showcase/ui/datatableRowEditing.jsf
send user object only with editdata method
<h:commandButton value="Edit" action="{user.editData(u)}" />
then you can use prepared statement with update like shown below
String sql = "UPDATE user1 set name = '"+name+"', email = '"+ email +"', address = '"+address+"' WHERE userId=" + userID;
I will suggest try hibernate.