I'm using prime faces 3.4.2 and I'm trying to update an entity that contains a list of another object, using a row editing datatable. My problem is that when I validate the change , the simple attributes of the entity are updated in the database , but the list is not. I don't know how to save the whole object in the data base.
here you find the editing page :
`
<p:panel style="width:1000px; ;font: lighter 70.5% Arial, Helvetica, sans-serif ; " header="Informations Générales">
<p:growl id="growl" showDetail="true" sticky="true" style="font-size: small;" />
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel value="Société" />
<p:inputText id="custSoc" value="#{CustomerCtrl.selectedCust.company}"/>
<h:outputLabel value="Secteur d'activité" />
<p:inputText id="custActivite" value="#{CustomerCtrl.selectedCust.secteurActivite}" />
<h:outputLabel value="Nom du propriétaire" />
<p:inputText id="custprop" value="#{CustomerCtrl.selectedCust.proprietaire}" />
</h:panelGrid>
<p:tabView id="tabView">
<p:tab title="Coordonnées">
<p:growl id="messages" showDetail="true"/>
<p:dataTable var="cu" value="#{CustomerCtrl.selectedCust.coordonnee}" id="carList" editable="true">
<f:facet name="header">
Coordonnées
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column colspan="5" headerText="Adresses" />
<p:column colspan="5" headerText="Contacts" />
</p:row>
<p:row>
<p:column headerText="Num" style="width:2cm"/>
<p:column headerText="Rue/Avenue" style="width:3cm"/>
<p:column headerText="Code postal" style="width:2cm" />
<p:column headerText="Ville" style="width:2.5cm" />
<p:column headerText="Pays" style="width:2.5cm" />
<p:column headerText="Fixe" style="width:2cm"/>
<p:column headerText="Mobile" style="width:2cm"/>
<p:column headerText="Fax" style="width:2cm"/>
<p:column headerText="E-mail" style="width:3.7cm"/>
<p:column headerText=" " />
</p:row>
</p:columnGroup>
<p:ajax event="rowEdit" listener="#{CustomerCtrl.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="#{CustomerCtrl.onCancel}" update=":form:messages" />
<p:column headerText="Num">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.number}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.number}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Rue/Avenue">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.street}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.street}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Code postal">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.zipcode}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.zipcode}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Ville">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.city.text}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{cu.city.text}" style="width:100%">
<f:selectItems value="#{CustomerCtrl.cityList}" style="width:100%"
var="city"
itemLabel="#{city}"
itemValue="#{city}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Pays" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.country.text}" style="width:100%" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{cu.country.text}" style="width:100%">
<f:selectItems value="#{CustomerCtrl.countryList}" style="width:100%"
var="color"
itemLabel="#{color}"
itemValue="#{color}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fixe">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.phone}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.phone}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Mobile" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.mobile}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.mobile}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fax" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.fax}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.fax}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="E-mail" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.email}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.email}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
</p:column>
</p:dataTable>
</p:tab>
<p:tab title="Compte">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel value="Login" />
<p:inputText id="userLogin" value="#{CustomerCtrl.selectedCust.login}" />
<h:outputLabel value="Mot de passe" />
<p:password id="userpass" value="#{CustomerCtrl.selectedCust.password}" />
</h:panelGrid>
</p:tab>
<p:tab title="Applications">
<h:panelGrid columns="2" cellpadding="5">
</h:panelGrid>
</p:tab>
<p:tab title="Interventions">
<h:panelGrid columns="2" cellpadding="5">
</h:panelGrid>
</p:tab>
</p:tabView>
</p:panel>
<br/>
`
and here is my managedbean :`#ManagedBean(name = "CustomerCtrl")
#ViewScoped
public class CustomerController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idSelected;
private Customer selectedCust ;
private Coordonnee selectedCoord = new Coordonnee();
private Coordonnee filteredCoord = new Coordonnee();
private List<Customer> filteredCusts;
private int cityId;
private int countryId;
private List<SelectItem> cityList = new ArrayList<SelectItem>();
private List<SelectItem> countryList = new ArrayList<SelectItem>();
private List<Customer> custmrs = new ArrayList<Customer>();
private List<Coordonnee> coordonnees = new ArrayList<Coordonnee>();
private Coordonnee selectedCustomerCoordonne;
#EJB
private SettingsBean settingBean;
public CustomerController() {
if (selectedCust != null) {
coordonnees = (List<Coordonnee>) settingBean.FindCoordonneeByCustomer(selectedCust.getId());
}
}
public void createCustomer() {
System.out.println("hello createCustomer");
System.out.println("selectedcust :"+selectedCust.getCompany());
System.out.println("selectedcustCoordonnee 1 :"+selectedCustomerCoordonne);
if(selectedCust==null){
System.out.println("entré");
selectedCust= new Customer();
System.out.println("nouvelle instance créé");
settingBean.createCustomer(selectedCust);
settingBean.createCoordonnee(selectedCustomerCoordonne);
System.out.println("Nouveau client " + selectedCust.getCompany() + " ajoutée");
}
else{
System.out.println("editer");
selectedCust.setCoordonnee(coordonnees);
settingBean.editCustomer(selectedCust);
System.out.println("client " + selectedCust.getCompany() + " édité");
}
}
public List<Customer> getCustmrs() {
custmrs = settingBean.findAllCustomers();
return custmrs;
}
public void setCustmrs(List<Customer> custmrs) {
this.custmrs = custmrs;
}
public void preRenderView() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(true);
}
public Customer getSelectedCust() {
if (selectedCust == null) {
selectedCust = (Customer) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("selectedCust");
System.out.println("Par session");
if (selectedCust == null) {
selectedCust = new Customer();
selectedCust.setCoordonnee(new ArrayList<Coordonnee>());
} else
selectedCust.setCoordonnee(settingBean
.FindCoordonneeByCustomer(selectedCust.getId()));
}
return selectedCust;
}
public void setSelectedCust(Customer selectedCust) {
this.selectedCust = selectedCust;
}
public List<Customer> getFilteredCusts() {
return filteredCusts;
}
public void setFilteredCusts(List<Customer> filteredCusts) {
this.filteredCusts = filteredCusts;
}
public List<Coordonnee> getCoordonnees() {
if (selectedCust != null) {
coordonnees = (List<Coordonnee>) settingBean.FindCoordonneeByCustomer(selectedCust.getId());
}
return coordonnees;
}
public void setCoordonnees(List<Coordonnee> coordonnees) {
this.coordonnees = coordonnees;
}
public void setCustomerToEdit(Customer customerToEdit) {
}
public String removeCustomer() {
if (selectedCust != null) {
System.out.println("in delete");
String selected = selectedCust.getCompany();
System.out.println("supprimer " + selected + "");
custmrs.remove(selectedCust);
settingBean.removeCustomer(selectedCust);
System.out.println("client supprimé");
}
return "";
}
public String removeCustomercoordonnee() {
if (selectedCustomerCoordonne != null) {
System.out.println("coordonne in delete");
String selected = selectedCustomerCoordonne.getEmail();
System.out.println("supprimer " + selected + "");
settingBean.removeCustomerCoordonnee(selectedCustomerCoordonne);
System.out.println("coordonne supprimé");
}
return "";
}
public String editCustomer() {
if (selectedCust != null) {
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("selectedCust", selectedCust);
System.out.println("selected "
+ FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().get("selectedCust"));
}
return "customeradd.xhtml?faces-redirect=true";
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public List<SelectItem> getCityList() {
cityList = new ArrayList<SelectItem>();
List<City> Listcity = settingBean.findAllCity();
for (City c : Listcity) {
cityList.add(new SelectItem(c.getId(), c.getText()));
}
return cityList;
}
public void setCityList(List<SelectItem> cityList) {
this.cityList = cityList;
}
public List<SelectItem> getCountryList() {
cityList = new ArrayList<SelectItem>();
List<Country> Listcountry = settingBean.findAllCountry();
for (Country c : Listcountry) {
countryList.add(new SelectItem(c.getId(), c.getText()));
}
return countryList;
}
public void setCountryList(List<SelectItem> countryList) {
this.countryList = countryList;
}
public int getIdSelected() {
return idSelected;
}
public void setIdSelected(int idSelected) {
this.idSelected = idSelected;
}
public Coordonnee getSelectedCustomerCoordonne() {
return selectedCustomerCoordonne;
}
public void setSelectedCustomerCoordonne(
Coordonnee selectedCustomerCoordonne) {
this.selectedCustomerCoordonne = selectedCustomerCoordonne;
}
public Coordonnee getSelectedCoord() {
return selectedCoord;
}
public void setSelectedCoord(Coordonnee selectedCoord) {
this.selectedCoord = selectedCoord;
}
public Coordonnee getFilteredCoord() {
return filteredCoord;
}
public void setFilteredCoord(Coordonnee filteredCoord) {
this.filteredCoord = filteredCoord;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Cliquer sur enregistrer pour valider la modification", ((Coordonnee) event.getObject()).getCustomer().getCompany());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Modification annulée", ((Coordonnee) event.getObject()).getCustomer().getCompany());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}`
Pleaaase help me to save the both objects.
Related
I didn't found a good answer so this problem. Maybe I just need to understand how to handle it. I implemented via contextMenu a menuItem to delete selected rows. That doesn't work anymore. Furthermore the editing does not working anymore. I have implemented a row editor. When I click on it, it gets activated and i can start editing but when I press okay or abort nothing happens.
No method is getting called. Not for deleting, not for editing, not even for selecting. It has obviously something to do with the lazyDataModel but how can I change it.
My Controller:
#Scope(value = "session")
#Component(value = "telefonbuchList")
#ELBeanName(value = "telefonbuchList")
#Join(path = "/", to = "/eintraege-liste.jsf")
public class TelefonbuchListController extends LazyDataModel<Telefonbuch> {
private static final long serialVersionUID = 1L;
#Autowired
private TelefonbuchRepository telefonbuchRepository;
private List<Telefonbuch> selectedEntries;
private LazyDataModel<Telefonbuch> lazyModel;
private int pageSize = 5;
public void deleteEntry() {
telefonbuchRepository.deleteAll(selectedEntries);
lazyModel.getWrappedData().removeAll(selectedEntries);
selectedEntries.clear();
}
public LazyDataModel<Telefonbuch> getLazyModel() {
return lazyModel;
}
#Override
public int getPageSize() {
return pageSize;
}
#Override
public Telefonbuch getRowData(String rowKey) {
List<Telefonbuch> list = getWrappedData();
for (Telefonbuch telefonbuch : list) {
if (telefonbuch.getId().toString().equals(rowKey)) {
return telefonbuch;
}
}
return null;
}
#Override
public Object getRowKey(Telefonbuch telefonbuch) {
return telefonbuch != null ? telefonbuch.getId() : null;
}
public List<Telefonbuch> getSelectedEntries() {
return selectedEntries;
}
#Deferred
#RequestAction
#IgnorePostback
public void loadData() {
lazyModel = new LazyDataModel<Telefonbuch>() {
private static final long serialVersionUID = 1L;
#Override
public List<Telefonbuch> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List<Telefonbuch> result = new ArrayList<Telefonbuch>();
if (first == 0) {
if (sortField != null && !sortField.isEmpty()) {
if (sortOrder.name().equalsIgnoreCase("ascending")) {
result = telefonbuchRepository
.findAll(PageRequest.of(first, pageSize, Sort.by(sortField).ascending()))
.getContent();
} else if (sortOrder.name().equalsIgnoreCase("descending")) {
result = telefonbuchRepository
.findAll(PageRequest.of(first, pageSize, Sort.by(sortField).descending()))
.getContent();
}
} else {
result = telefonbuchRepository.findAll(PageRequest.of(first, pageSize)).getContent();
}
} else {
first = first / pageSize;
if (sortField != null && !sortField.isEmpty()) {
if (sortOrder.name().equalsIgnoreCase("ascending")) {
result = telefonbuchRepository
.findAll(PageRequest.of(first, pageSize, Sort.by(sortField).ascending()))
.getContent();
} else if (sortOrder.name().equalsIgnoreCase("descending")) {
result = telefonbuchRepository
.findAll(PageRequest.of(first, pageSize, Sort.by(sortField).descending()))
.getContent();
}
} else {
result = telefonbuchRepository.findAll(PageRequest.of(first, pageSize)).getContent();
}
}
return result;
}
};
lazyModel.setRowCount((int) telefonbuchRepository.count());
lazyModel.setPageSize(pageSize);
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
telefonbuchRepository.save((Telefonbuch) newValue);
}
public void onRowCancel(RowEditEvent event) {
}
public void onRowEdit(RowEditEvent event) {
Object oldValue = event.getObject();
telefonbuchRepository.save((Telefonbuch) oldValue);
FacesMessage msg = new FacesMessage("Eintrag geändert",
((Telefonbuch) event.getObject()).getVorname() + " " + ((Telefonbuch) event.getObject()).getNachname());
FacesContext.getCurrentInstance().addMessage("eintraege-list", msg);
}
#Override
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setSelectedEntries(List<Telefonbuch> selectedEntries) {
this.selectedEntries = selectedEntries;
}
The .xhtml:
<h:form id="eintraegeList">
<p:panel header="Liste aller Einträge">
<p:dataTable id="table" var="telefonbuch" lazy="true" widgetVar="tableWv" value="#{telefonbuchList.lazyModel}" stickyHeader="true" editable="true" resizableColumns="true" liveResize="true" style="margin-bottom:20px" paginator="true" rows="#{telefonbuchList.pageSize}" dynamic="true" emptyMessage="Keine Telefonbucheinträge vorhanden" selection="#{telefonbuchList.selectedEntries}" selectionMode="multiple" rowKey="#{telefonbuch.id}"
currentPageReportTemplate="{startRecord}-{endRecord} von {totalRecords}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink} {Exporters}"
rowsPerPageTemplate="5,8,10">
<f:facet name="header">
<p:commandButton id="toggler" type="button" value="Anzeige" style="float:right" icon="pi pi-align-justify" />
<p:columnToggler datasource="table" trigger="toggler" />
</f:facet>
<p:ajax event="rowEdit" listener="#{telefonbuchList.onRowEdit}" update="table" />
<p:ajax event="rowEditCancel" listener="#{telefonbuchList.onRowCancel}" update="table" />
<p:ajax event="cellEdit" listener="#{telefonbuchList.onCellEdit}" update="table" />
<p:separator />
<p:column headerText="ID" sortBy="#{telefonbuch.id}">
<h:outputText value="#{telefonbuch.id}" />
</p:column>
<p:column headerText="Vorname" sortBy="#{telefonbuch.vorname}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.vorname}" /></f:facet>
<f:facet name="input"><p:inputText id="vornameInput" value="#{telefonbuch.vorname}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Nachname" sortBy="#{telefonbuch.nachname}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.nachname}" /></f:facet>
<f:facet name="input"><p:inputText id="nachnameInput" value="#{telefonbuch.nachname}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Telefonnummer" sortBy="#{telefonbuch.telefonnummer}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.telefonnummer}" /></f:facet>
<f:facet name="input"><p:inputText id="telefonnummerInput" value="#{telefonbuch.telefonnummer}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Handynummer" sortBy="#{telefonbuch.handynummer}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.handynummer}" /></f:facet>
<f:facet name="input"><p:inputText id="handynummerInput" value="#{telefonbuch.handynummer}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Geschäftsstelle" sortBy="#{telefonbuch.geschaeftsstelle}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.geschaeftsstelle}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu value="#{telefonbuch.geschaeftsstelle}" style="width:100%">
<f:selectItems value="#{telefonbuchController.geschaeftsstellen}" var="c" itemLabel="#{geschaeftsstelle}" itemValue="#{geschaeftsstelle}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Geschlecht" sortBy="#{telefonbuch.gender.shortGender}">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{telefonbuch.gender.shortGender}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu id="gender" value="#{telefonbuch.gender}" style="width:100%">
<f:selectItem itemLabel="Keine Angabe" itemValue="" />
<f:selectItems value="#{telefonbuch.genders}" var="gender" itemLabel="#{gender.shortGender}" itemValue="#{gender}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:20px;text-align:center;">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:growl id="growl" showDetail="true" for="eintraege-list">
<p:autoUpdate />
</p:growl>
<p:separator />
<p:contextMenu for="table">
<h:outputStylesheet library="webjars" name="font-awesome/5.7.1/css/fontawesome.min-jsf.css" />
<p:menuitem value="Löschen" update="table" icon="fas fa-eraser" action="#{telefonbuchList.deleteEntry}"/>
<p:menuitem value="Edit Cell" icon="pi pi-search" onclick="PF('tableWv').showCellEditor();return false;"/>
</p:contextMenu>
<h3>Exportieren der Daten</h3>
<h:commandLink>
<p:graphicImage value="/img/icon-pdf.png" />
<p:dataExporter type="pdf" target="table" fileName="Telefonbuch" />
</h:commandLink>
</p:panel>
</h:form>
Model (Telefonbuch):
public enum Gender {
MALE("Männlich"), FEMALE("Weiblich");
private String shortGender;
private Gender(String shortGender) {
this.shortGender = shortGender;
}
public String getShortGender() {
return shortGender;
}
}
#Column
#Enumerated(EnumType.STRING)
private Gender gender;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String vorname;
#Column
private String nachname;
#Column
private String telefonnummer;
#Column
private String handynummer;
#Column
private String geschaeftsstelle;
PrimeFaces Version 6.2
JSF MyFaces Version 2.2.12
Java 1.8
Spring Boot 2.1.2
I have developed an approval screen(for user creation). There I have included two states which were approval and disapproval. Currently it takes the reading only as approval and it doesn't check disapproval. approval process is working fine for me. but I want to have disapproval part as well.
I want to improve my code to take separate readings for above mentioned two different states.
How can I get the approval and disapproval objects to two separate List??? Cant find example for two selection ways in primeface.
I want to know how do i get a column selection as approve and disapprove.
I have the following screen
I have the following datatable
<p:dataTable id="userApprovals" var="user" value="#{userApprovalBean.userApprovals}"
selection="#{userApprovalBean.selectedUser}"
widgetVar="usersTable"
rowKey="#{user.username}"
reflow="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
paginator="true" rows="10" style="margin-bottom:20px">
<f:facet name="header">
<h:commandLink style="float:right;">
<p:graphicImage name="/images/excel.png" width="24" />
<p:dataExporter type="xls" target="userApprovals" fileName="cars" />
</h:commandLink>
User Approval
<h:commandLink style="float:right;">
<p:graphicImage name="/images/pdf.png" width="24" />
<p:dataExporter type="pdf" target="userApprovals" fileName="cars" />
</h:commandLink>
<p:commandButton id="toggler" type="button" value="Columns"
style="width:100px;float:left;" icon="ui-icon-calculator" />
<p:columnToggler datasource="userApprovals" trigger="toggler" />
</f:facet>
<p:column sortBy="#{user.username}">
<f:facet name="header">
<h:outputText value="Username" />
</f:facet>
<h:outputText value="#{user.username}" />
</p:column>
<p:column sortBy="#{user.firstName}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.firstName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Geneder" />
</f:facet>
<h:outputText value="#{user.gender}" />
</p:column>
<p:column style="width:160px;">
<f:facet name="header">
<h:outputText value="Address" />
</f:facet>
<h:outputText value="#{user.addressLine1}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="User Role" />
</f:facet>
<h:outputText value="#{user.userRole.userRoleDescription}" />
</p:column>
<p:column sortBy="#{user.entUser}">
<f:facet name="header">
<h:outputText value="Created User" />
</f:facet>
<h:outputText value="#{user.entUser}" />
</p:column>
<p:column styleClass="myTable">
<f:facet name="header">
<h:outputText value="Created Date" />
</f:facet>
<h:outputText value="#{user.entDate}" />
</p:column>
<p:column style="width:60px;float:center;" >
<f:facet name="header">
<h:outputText value="View" />
</f:facet>
<p:commandLink update=":form:documentPanel" oncomplete="PF('documentDialog').show()" title="View Detail" styleClass="ui-icon ui-icon-search">
<f:setPropertyActionListener value="#{user}" target="#{userApprovalBean.gridUser}" />
</p:commandLink>
</p:column>
<p:column selectionMode="multiple" style="width:55px;text-align:center">
</p:column>
<p:column selectionMode="multiple" style="width:55px;text-align:center">
</p:column>
<f:facet name="footer">
<p:commandButton process="userApprovals" update=":form:multiCarDetail"
icon="ui-icon-search" value="Selected Records" style="width:200px;height:22px"
oncomplete="PF('multiCarDialog').show()" />
</f:facet>
</p:dataTable>
I have the following Bean
public class UserApprovalBean {
private List<UserDetail> userApprovals;
private String recordStatus;
private List<UserDetail> selectedUser;
private UserDetail gridUser;;
private FacesContext context;
private UserDetail loggedUserDetail;
#PostConstruct
public void init(){
try {
context = FacesContext.getCurrentInstance();
userApprovals = UserApprovalDao.getInstance().findAllUserApproval();
//selectedUser.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void submitData(){
context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
RequestContext context1 = RequestContext.getCurrentInstance();
boolean dataFill = true;
if (selectedUser.isEmpty()) {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Validation Error", "You need to select something....!");
FacesContext.getCurrentInstance().addMessage(null, message);
context1.addCallbackParam("loggedIn", dataFill);
}
else{
try{
for(UserDetail ud: selectedUser){
ud.setRecordStatus("ACTIVE");
ud.setApprovedUser(loggedUserDetail.getUsername());
ud.setApprovedDate(new Timestamp(System.currentTimeMillis()));
UserApprovalDao.getInstance().update(ud);
}
context.getApplication().getNavigationHandler()
.handleNavigation(context, null,
"/approveUserForm.xhtml?faces-redirect=true");
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void refresh() {
HttpServletRequest req = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
context = FacesContext.getCurrentInstance();
if (req.getMethod().equalsIgnoreCase("GET")) {
try {
reload();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void reload() {
clear();
loadData();
}
private void clear() {
userApprovals.clear();
}
private void loadData() {
try {
userApprovals = UserApprovalDao.getInstance().findAllUserApproval();
loggedUserDetail = (UserDetail) context.getExternalContext()
.getSessionMap().get("user");
} catch (Exception e) {
e.printStackTrace();
}
}
public List<UserDetail> getUserApprovals() {
return userApprovals;
}
public void setUserApprovals(List<UserDetail> userApprovals) {
this.userApprovals = userApprovals;
}
public String getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(String recordStatus) {
this.recordStatus = recordStatus;
}
public List<UserDetail> getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(List<UserDetail> selectedUser) {
this.selectedUser = selectedUser;
}
public UserDetail getGridUser() {
return gridUser;
}
public void setGridUser(UserDetail gridUser) {
this.gridUser = gridUser;
}
public UserDetail getLoggedUserDetail() {
return loggedUserDetail;
}
public void setLoggedUserDetail(UserDetail loggedUserDetail) {
this.loggedUserDetail = loggedUserDetail;
}
}
You can use p:selectBooleanCheckbox in approval and disapproval column with unique value objects and can easily get the approval and disapproval selection list using If condition
i got an error on my datatable "Target Unreachable, 'null' returned null", it caused by one column with join with another table, normally i initiate everything in my beans, this is my code, someone can enlighten me please ?
#ManagedBean
#ViewScoped
public class locationBean extends LazyDataModel<Location> {
private Location selectedLocation;
private List<Location> locations;
private List<SelectItem> selectoneitemclient;
#PostConstruct
public void init() {
this.locations = new ArrayList<Location>();
this.selectoneitemclient = new ArrayList<SelectItem>();
this.selectedLocation = new Location();
}
public List<SelectItem> getSelectoneitemclient() {
ClientDao clientdao = new ClientDaoImpl();
List<Client> clients = clientdao.selectItems();
for (Client cl : clients) {
SelectItem selectitem = new SelectItem(cl.getCodecl(), cl.getNom());
this.selectoneitemclient.add(selectitem);
}
return selectoneitemclient;
}
public List<Location> getLocations() {
LocationDao locationdao = new LocationDaoImpl();
this.locations = locationdao.findAll();
return locations;
}
location.xhtml
<h:form id="formDataTable">
<p:dataTable var="location" value="#{locationBean.locations}" rowKey="#{location.codeloc}" paginatorPosition="bottom" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{locationBean.selectedLocation}" id="tableLocation">
<p:ajax event="rowSelect" listener="#{locationBean.onRowSelect}" update=":formDisplay" oncomplete="PF('dialogLocationDisplay').show()" />
<f:facet name="header">
Listes des réservations
</f:facet>
<p:column headerText="Type client" filterBy="#{location.client.typecl}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.typecl}" />
</p:column>
<p:column headerText="Nom" filterBy="#{location.client.nom}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.nom}" />
</p:column>
<p:column headerText="Tel" filterBy="#{location.client.tel}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.tel}" />
</p:column>
<p:column headerText="Email" filterBy="#{location.client.email}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.email}" />
</p:column>
<p:column headerText="Date Debut" filterBy="#{location.datedebut}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.datedebut}" />
</p:column>
<p:column headerText="Date Fin" filterBy="#{location.datefin}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.datefin}" />
</p:column>
<p:column headerText="Gestion">
<p:commandButton id="btnUpdate" update=":formUpdate" oncomplete="PF('dialogLocationUpdate').show()" icon="ui-icon-pencil" title="modifier">
<f:setPropertyActionListener value="#{location}" target="#{locationBean.selectedLocation}"/>
</p:commandButton>
<p:commandButton id="btnDelete" update=":formDelete" oncomplete="PF('dialogLocationDelete').show()" icon="ui-icon-trash" title="supprimer">
<f:setPropertyActionListener value="#{location}" target="#{locationBean.selectedLocation}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form id="formUpdate">
<p:dialog header="modifier une reservation" widgetVar="dialogLocationUpdate" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="detailLocationUpdate" style="text-align:center;">
<p:panelGrid columns="2" columnClasses="label,value">
<h:outputText value="Client: " />
<p:selectOneMenu value="#{locationBean.selectedLocation.client.codecl}">
<f:selectItem itemLabel="- Selectionner un client -" itemValue = "" />
<f:selectItems value="#{locationBean.selectoneitemclient}" />
</p:selectOneMenu>
<h:outputText value="Titre: " />
<p:inputText value="#{locationBean.selectedLocation.titre}" />
LocationDaoImpl.java
#Override
public List<Location> findAll() {
List<Location> listloc = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String sql = "FROM Location l inner join fetch l.client";
try {
session.beginTransaction();
listloc = session.createQuery(sql).list();
session.beginTransaction().commit();
} catch (Exception e) {
if (session != null) {
session.close();
}
e.printStackTrace();
}
return listloc;
}
#Override
public boolean update(Location loc) {
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
Location locdb = (Location) session.load(Location.class, loc.getCodeloc());
locdb.setCodeloc(loc.getCodeloc());
locdb.setTitre(loc.getTitre());
locdb.setClient(loc.getClient());
locdb.setDatedebut(loc.getDatedebut());
locdb.setDatefin(loc.getDatefin());
locdb.setTotalttc(loc.getTotalttc());
session.update(locdb);
session.getTransaction().commit();
flag = true;
} catch (Exception e) {
flag = false;
if (session != null) {
session.close();
}
e.printStackTrace();
}
return flag;
}
I have two primefaces dataTables. The first show the instances of a MainEntity.
The second one show a list of Words (just strings) associated with the selected MainEntity on the first datatable.
The printscreen illustrates what I mean.
My problem is, when I edit a string on the Word List, my listener method won't receive the new value. In fact, when I call the event.getNewValue() method, I get old value.
What am I missing?
I'm using JavaServer Faces 2.2, Primefaces 5.0 and Spring Framework 4.0.3.
Thanks in advance for any help.
The code for the xhtml, the managed bean and the MainEntity are as follows:
mainEntity.xhtml:
<h:body>
<h:form id="mainEntityForm">
<p:panelGrid columns="1" fullPage="true" id="dashboard">
<f:facet name="header">
<h2>MainEntity Table</h2>
</f:facet>
<p:panel>
<f:facet name="header">
MainEntity List
<p:commandButton value="New MainEntity"
actionListener="#{mainEntityController.createMainEntityDialog}"
styleClass="header-button">
<p:ajax event="dialogReturn" update=":mainEntityForm:mainEntityTable" />
</p:commandButton>
</f:facet>
<p:dataTable id="mainEntityTable" var="mainEntity" value="#{mainEntityController.mainEntities}"
editable="true" editMode="cell" widgetVar="cellMainEntity"
selectionMode="single" selection="#{mainEntityController.selectedMainEntity}"
rowKey="#{mainEntity.id}" tableStyle="width:auto">
<p:ajax event="rowSelect" update=":mainEntityForm:stringGrid :mainEntityForm:entityAGrid :mainEntityForm:entityBGrid" />
<p:ajax event="cellEdit" listener="#{mainEntityController.onEditMainEntity}" update=":mainEntityForm:mainEntityTable" />
<p:column headerText="ID">
<h:outputText value="#{mainEntity.id}" />
</p:column>
<p:column headerText="Name">
<p:cellEditor>
<f:facet name="output">
<h:outputText id="nameOutput" value="#{mainEntity.name}" />
</f:facet>
<f:facet name="input">
<h:inputText id="atyInput" value="#{mainEntity.qty}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Commands">
<p:commandButton title="Remove MainEntity" icon="ui-icon-trash"
actionListener="#{mainEntityController.deleteMainEntity(mainEntity)}"
update=":mainEntityForm:mainEntityTable" />
</p:column>
</p:dataTable>
</p:panel>
<p:panelGrid fullPage="true" id="mainEntityDetail">
<f:facet name="header">
<p:row>
<p:column colspan="4">
<h2>MainEntity Detail</h2>
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<p:panel>
<f:facet name="header">
Word List
<p:commandButton value="New Word"
actionListener="#{mainEntityController.addNewWord()}"
styleClass="header-button"
update=":mainEntityForm:wordGrid">
</p:commandButton>
</f:facet>
<p:dataTable id="wordGrid" var="word"
value="#{mainEntityController.selectedMainEntity.wordList}"
tableStyle="width:auto" editable="true" editMode="cell" widgetVar="cellWord">
<p:ajax event="cellEdit" listener="#{mainEntityController.onEditWord}" />
<p:column headerText="Word">
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<h:inputText id="wordInput" value="#{word}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Commands">
<p:commandButton title="Remove Word"
icon="ui-icon-trash"
actionListener="#{mainEntityController.removeWord(word)}"
update=":mainEntityForm:wordGrid" />
</p:column>
</p:dataTable>
</p:panel>
</p:column>
</p:row>
</p:panelGrid>
</p:panelGrid>
</h:form>
</h:body>
MainEntityController.java (managed bean):
#ManagedBean
#SessionScoped
public class MainEntityController {
//...
private MainEntity selectedMainEntity;
public List<MainEntity> mainEntities;
//...
public MainEntity getSelectedMainEntity(){
return selectedMainEntity;
}
public void setSelectedMainEntity(MainEntity mainEntity){
this.selectedMainEntity = mainEntity;
}
//...
public void onEditWord(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
// THE PROBLEM IS HERE
// I NEVER ACTUALLY REACH THIS CODE
// newValue is always equal to oldValue!
FacesContext context = FacesContext.getCurrentInstance();
String word = context.getApplication().evaluateExpressionGet(context, "#{word}", String.class);
System.out.println(newValue);
System.out.println(word);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Word Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
MainEntity.java:
#Entity
public class MainEntity {
#Id
private String id;
#ElementCollection(fetch=FetchType.EAGER)
#CollectionTable(
name="MainEntity_Word",
joinColumns = #JoinColumn(name = "id", referencedColumnName="id")
)
#Column(name = "word")
private Set<String> wordList;
//...
public void addWord(String word) {
this.wordList.add(word);
}
public void removeWord(String word) {
this.wordList.remove(word);
}
public Set<String> getWordList() {
return wordList;
}
public void setWordList(Set<String> wordList) {
this.wordList = wordList;
}
}
Change
<h:inputText id="wordInput" value="#{word}" />
to
<p:inputText id="wordInput" value="#{word}" />
or
<h:inputText id="wordInput" value="#{word}" >
<p:ajax event="change" process="#this"/>
</h:inputText>
You need to ajaxify the input component, and at last update the outputText component.
Edited:
change this column :
<p:column headerText="Word" >
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<h:inputText id="wordInput" value="#{word}" />
</f:facet>
</p:cellEditor>
</p:column>
to
<p:column headerText="Word" >
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<p:inputText id="wordInput" value="#{word}" >
<p:ajax event="change" update="wordOutput" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
Edit 2 :
From Chapter 24 Introduction to the Java Persistence API
If an entity instance be passed by value as a detached object, such as
through a session bean’s remote business interface, the class must
implement the Serializable interface.
I finally got it working.
I suspected of the String immutable nature and what I did was to encapsulate the 'word' in a class like the following:
public class Word {
private String word;
Word (String word) {
this.setWord(word);
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
}
After that, I also had to create a set inside the managed bean (controller) to hold the set of words, like 'private Set managedWordList;'.
I also changed the getter for the list, inside the managed bean, to convert from the String set to a Word set like:
public Set<Word> getWordList() {
if (this.selectedMainEntity != null){
this.wordList = new HashSet<Word>();
for (String word : this.selectedMainEntity.getWordList()) {
this.wordList.add(new Word(word));
}
}
return this.wordList;
}
Finally, I changed the dataTable to reference the new set. From:
<p:dataTable ... value="#{mainEntityController.selectedMainEntity.wordList}"... />
To:
<p:dataTable ... value="#{mainEntityController.wordList}"... />
And only then I got it to work as I expected.
I have I datatable. I want to disable the commandlinks when I go to rowedit mode by pressing on the edit link:
JSF:
<p:growl id="messages" showDetail="true" />
<p:dataTable value="#{employeeBean.employees}"
var="employee" id="employeeDTable"
editable="true">
<p:ajax event="rowEdit" listener="#{employeeBean.edit}" update=":employeeForm:messages" />
<p:ajax event="rowEditCancel" listener="#{employeeBean.undoEdit}" update=":employeeForm:messages" />
<p:column id="id" headerText="Id">
<h:outputText value="#{employee.id}"/>
</p:column>
<p:column id="firstname" headerText="Voornaam">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{employee.firstName}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{employee.firstName}" label="firstname"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column id="editButtonsId" headerText="">
<p:rowEditor />
</p:column>
<p:column id="cashbook" headerText="">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" /> <!-- DISABLE THIS IN EDITMODE -->
</h:panelGroup>
</div>
</p:column>
</p:dataTable>
CODE:
#Component("employeeBean")
#Scope("session")
public class EmployeeBean {
List<EmployeeModel> employees;
private EmployeeModel employeeModel;
#Autowired
private EmployeeService employeeService;
public EmployeeBean() {
if(employeeService == null){
employeeService = ServiceRepository.getInstance().getEmployeeService();
}
employeeModel = new EmployeeModel();
if(employees == null){
this.employees = this.employeeService.getEmployees();
}
}
public void edit(RowEditEvent event) {
EmployeeModel employee = ((EmployeeModel) event.getObject());
EmployeeModel updatedEmployee = this.employeeService.updateEmployee(employee);
if(updatedEmployee != null){
FacesMessage msg = new FacesMessage("Employee Edited", employee.getFirstName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
public void undoEdit(RowEditEvent event) {
}
public EmployeeModel getEmployeeModel() {
return employeeModel;
}
public void setEmployeeModel(EmployeeModel employeeModel) {
this.employeeModel = employeeModel;
}
public List<EmployeeModel> getEmployees() {
return employees;
}
public void setEmployees(List<EmployeeModel> employees) {
this.employees = employees;
}
}
Put your link and disabled link inside a <p:cellEditor/>
<p:column id="cashbook" headerText="">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" />
</h:panelGroup>
</div>
</f:facet>
<f:facet name="input">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink disabled="true" title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" />
</h:panelGroup>
</div>
</f:facet>
</p:cellEditor>
</p:column>