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

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));

Related

Null value in the first itemUnselect event on primefaces autoComplete

I am facing a strange situation when using primefaces p:autoComplete. I put this piece of code in a xhtml file, inside a h:form tag:
<p:autoComplete id="to"
multiple="true"
value="#{editEmailComponent.receiversEntitiesToDummy}"
completeMethod="#{editEmailComponent.completeQuery}"
emptyMessage="#{text['list.empty']}"
var="ent"
itemLabel="#{ent.class.simpleName eq 'EntityGroupHeader'? ent.design : (ent.class.simpleName eq 'EntityContactList'? ent.email : ent.abstractEntityEmail)}"
itemValue="#{ent}"
forceSelection="true"
cache="false"
styleClass="full-width"
autocomplete="none">
<o:converter converterId="omnifaces.ListConverter"
list="#{editEmailComponent.receiversAllConverter}" />
<p:column>
<h:outputText rendered="#{(ent.class.simpleName ne 'EntityGroupHeader') and (ent.class.simpleName ne 'EntityContactList')}" value="\# #{ent.number}" />
<h:outputText rendered="#{ent.class.simpleName eq 'EntityGroupHeader'}" value="\# #{ent.design}" />
<h:outputText rendered="#{ent.class.simpleName eq 'EntityContactList'}" value="#{ent.nif}" />
</p:column>
<p:column>
<h:outputText rendered="#{(ent.class.simpleName ne 'EntityGroupHeader') and (ent.class.simpleName ne 'EntityContactList')}" value="#{ent.abstractEntityDesignation}" />
<h:outputText rendered="#{ent.class.simpleName eq 'EntityContactList'}" value="#{ent.designation}" />
</p:column>
<p:column>
<h:outputText rendered="#{(ent.class.simpleName ne 'EntityGroupHeader') and (ent.class.simpleName ne 'EntityContactList')}" value="#{ent.abstractEntityEmail}" />
<h:outputText rendered="#{ent.class.simpleName eq 'EntityContactList'}" value="#{ent.email}" />
</p:column>
<p:ajax event="query" process="#this"/>
<p:ajax event="itemSelect" process="#form" listener="#{editEmailComponent.onItemSelectTo}" update="to" />
<p:ajax event="itemUnselect" process="#form" listener="#{editEmailComponent.onItemUnselectTo}" update="to" />
</p:autoComplete>
The action associated to this itemUnselect event is:
public void onItemUnselectTo(UnselectEvent event) {
onItemUnselect(receiversEntitiesToDummy, event);
BaseObject obj2 = (BaseObject) event.getObject();
//Instancia da entidade e converter para receiver
if(obj2 instanceof EntityContactList){
EntityContactList aux = (EntityContactList) obj2;
for(Receiver rec : receiversTo)
if(rec.getEntity().equals(aux.getEntity()))
receiversTo.remove(rec);
}
private static void onItemUnselect(List<BaseObject> list, UnselectEvent event) {
BaseObject obj = (BaseObject) event.getObject();
list.remove(obj);
}
I initialize the list of this autocomplete like this:
private List<BaseObject> receiversEntitiesToDummy = new ArrayList<>();
...
EntityContactList result = entityManager.getEntityContactList(receiver.getEntity(),null);
receiversEntitiesToDummy.add(result);
So, when I remove this first element the "obj2" is null but when I search and select some object the "obj2" is properly filled. Anyone knows why this happens?
Note: I am using primefaces 5.2.
I solved my problem changing the way I populate the list with the first element.
Instead of this:
private List<BaseObject> receiversEntitiesToDummy = new ArrayList<>();
...
EntityContactList result = entityManager.getEntityContactList(receiver.getEntity(),null);
receiversEntitiesToDummy.add(result);
I put the first element using the query function and it works.
EntityContactList result = entityManager.getEntityContactList(receiver.getEntity(),null);
List<BaseObject> aux = new ArrayList<>();
if(receiver.getEntity().getAbstractEntityEmail() != null)
aux = completeQuery(receiver.getEntity().getAbstractEntityEmail());
if(aux.contains(result)){
int num = aux.indexOf(result);
EntityContactList another = (EntityContactList) aux.get(num);
receiversEntitiesToDummy.add(another);
}

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);
}

How to set null value selectone menu jsf

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=?,

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.

primefaces treetable

i'm very new to primefaces. i create a treetable, all item get from database. my problem is if i select a child item, the actual selected is parent item, so then i cannot make operation on child item. here is my treetable code
<p:treeTable id="treeTable" value="#{aZoningController.root}" var="zonning" >
<p:column style="text-align: left; width: 93%">
<f:facet name="header">
#{lbl.aZoning_pokok}
</f:facet>
<h:outputText value="#{zonning.nama}" />
</p:column>
<p:column style="text-align: center; width: 5%">
<f:facet name="header">
#{lbl.aZoning_kod}
</f:facet>
<h:outputText value="#{zonning.kod}" />
</p:column>
<p:column style="vertical-align: text-top">
<p:menuButton value="" styleClass="mb">
<p:menuitem value="Update" oncomplete="confirmation.show()" process="#this" update=":actionForm:actionDialog" icon="ui-icon-document-b">
<f:setPropertyActionListener value="#{zonning}" target="#{aZoningController.selectedNode}" />
</p:menuitem>
<p:menuitem value="Delete" oncomplete="confirmation.show()" process="#this" update=":myform:confirmDialog" icon="ui-icon-trash">
<f:setPropertyActionListener value="#{zonning}" target="#{aZoningController.selectedNode}" />
</p:menuitem>
</p:menuButton>
</p:column>
</p:treeTable>
and i'm populate the tretable using this
public TreeNode getRoot() {
root = new DefaultTreeNode("Root", null);
List<aZoning> zon = ejbFacade.getRoot();
for (aZoning z : zon) {
TreeNode zonning = new DefaultTreeNode(z, root);
createNode(z.getId(), zonning);
}
return root;
}
private TreeNode createNode (String idParent, TreeNode parent) {
TreeNode node = null;
List<aZoning> zonning = ejbFacade.getZonning(idParent);
for (aZoning z : zonning) {
node = new DefaultTreeNode(z, parent);
createNode(z.getId(), node);
}
return node;
}
Please advice me
<f:setPropertyActionListener value="#{zonning}" target="#{aZoningController.selectedNode}" />
This sets the value of zonning to the selectedNode property of your aZoningController class. Instead of zonning, try setting the value that you need when the menuItem is selected. zonning is the value of the parent node, which is causing the issue.