I have modules list with four checkbooks (View, Create,Edit and Delete). In that, if user click on Create check box or edit check box or delete check box want to checked view check box automatically and same, if uncheck view check box want to uncheck create.Edit and Delete automatically. Please help me to solve this issue as i'm new to JSF. thanks in advance
Regards
Mohan
<p:column headerText="Module ID:">
<h:outputText value="#{modules.moduleID}" />
</p:column>
<p:column headerText="Root Module ID:">
<h:outputText value="#{modules.rootID}" />
</p:column>
<p:column headerText="Module Description:">
<h:outputText value="#{modules.moduleDescription}" />
</p:column>
<p:column headerText="View" >
<h:selectBooleanCheckbox id="vi" value="#{roleModule.view[modules.moduleID]}"/>
</p:column>
<p:column headerText="Create" >
<h:selectBooleanCheckbox value="#{roleModule.create[modules.moduleID]}">
<p:ajax update="vi" listener="#{roleModule.permissionCheck}"/>
</h:selectBooleanCheckbox>
</p:column>
<p:column headerText="Edit" >
<h:selectBooleanCheckbox value="#{roleModule.edit[modules.moduleID]}">
<p:ajax update="vi" listener="#{roleModule.permissionCheck}"/>
</h:selectBooleanCheckbox>
</p:column>
<p:column headerText="Delete" >
<h:selectBooleanCheckbox value="#{roleModule.delete[modules.moduleID]}">
<p:ajax update="vi" listener="#{roleModule.permissionCheck}"/>
</h:selectBooleanCheckbox>
</p:column>
</p:dataTable>
I would do it in jQuery, for one reason, it's so basic move to take it into server-side level, after all the unchecking and checking is done on the view.
JS
$(PrimeFaces.escapeClientId('form:table'))
.on("change",
"input[type='checkbox'][name*='edit'], input[type='checkbox'][name*='create'], input[type='checkbox'][name*='delete']",
function() {
var tr = $(this).parent().parent();
var view = tr
.find("input[type='checkbox'][name*='view']");
var create = tr
.find("input[type='checkbox'][name*='create']");
var edit = tr
.find("input[type='checkbox'][name*='edit']");
var deleteBox = tr
.find("input[type='checkbox'][name*='delete']");
if ($(this).is(':checked')) {
view.prop("checked", true);
} else {
if (create.is(':checked') || edit.is(':checked')
|| deleteBox.is(':checked')) {
view.prop("checked", true);
} else
view.prop("checked", false);
}
});
$(PrimeFaces.escapeClientId('form:table')).on(
"change",
"input[type='checkbox'][name*='view']",
function() {
var tr = $(this).parent().parent();
var view = tr.find("input[type='checkbox'][name*='view']");
var create = tr.find("input[type='checkbox'][name*='create']");
var edit = tr.find("input[type='checkbox'][name*='edit']");
var deleteBox = tr
.find("input[type='checkbox'][name*='delete']");
if ($(this).is(':not(:checked)')) {
create.prop("checked", false);
edit.prop("checked", false);
deleteBox.prop("checked", false);
}
});
Please Note: if you update the table, you should rerun the script or you could replace the selector with the form id only. like this
$(PrimeFaces.escapeClientId('form')).on ....
of course you should include the code in the $( document ).ready().
EDIT:
BASED ON YOUR REQUEST.
I have created a small project on github, you can download the project and see how jQuery (JS in general) works with JSF, and here's a live demo.
Two main files are main.xhml and checkBoxesJQuery.js.
Hope it helps.
Try this, This may help you
JSF Code:
<h:selectBooleanCheckbox value="#{bean.viewChecked}" >
<a4j:support action="#{bean.viewCheckBoxAction}" event="onclick" reRender="panelId"/>
</h:selectBooleanCheckbox>
<h:outputText value="View" />
<h:selectBooleanCheckbox value="#{bean.createChecked}" >
<a4j:support action="#{bean.createCheckBoxAction}" event="onclick" reRender="panelId"/>
</h:selectBooleanCheckbox>
<h:outputText value="Create" />
<h:selectBooleanCheckbox value="#{bean.editChecked}" >
<a4j:support action="#{bean.editCheckBoxAction}" event="onclick" reRender="panelId"/>
</h:selectBooleanCheckbox>
<h:outputText value="Edit" />
<h:selectBooleanCheckbox value="#{bean.deleteChecked}" >
<a4j:support action="#{bean.deleteCheckBoxAction}" event="onclick" reRender="panelId"/>
</h:selectBooleanCheckbox>
<h:outputText value="Delete" />
Bean Code:
public String viewCheckBoxAction()
{
if(!viewChecked) // while view is unchecked then uncheck all the others
{
editChecked = false;
deleteChecked = false;
createChecked = false;
}
return null;
}
public String createCheckBoxAction()
{
viewCheckManage();
return null;
}
public String editCheckBoxAction()
{
viewCheckManage();
return null;
}
public String deleteCheckBoxAction()
{
viewCheckManage();
return null;
}
private void viewCheckManage()
{
if(createChecked || deleteChecked || editChecked) // while any one is checked then view also checked
{
viewChecked = true;
}
else
{
viewChecked = false;
}
}
You could use the onchange-attribute of the checkboxes and add JavaScript-Code like document.getElementByID('formID:tableID:lineID:boxID').checked=true
You may try something like this
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable value="#{roleModule.modulesList}" var="module" id="table">
<p:column headerText="Module ID:">
<h:outputText value="#{module.moduleID}" />
</p:column>
<p:column headerText="Root Module ID:">
<h:outputText value="#{module.rootID}" />
</p:column>
<p:column headerText="Module Description:">
<h:outputText value="#{module.moduleDescription}" />
</p:column>
<p:column headerText="View">
<h:selectBooleanCheckbox id="view" value="#{module.view}">
<p:ajax update=":form:table" listener="#{roleModule.permissionCheck}" />
</h:selectBooleanCheckbox>
</p:column>
<p:column headerText="Create">
<h:selectBooleanCheckbox id="create" value="#{module.create}">
<p:ajax update=":form:table" listener="#{roleModule.permissionCheck}" />
</h:selectBooleanCheckbox>
</p:column>
<p:column headerText="Edit">
<h:selectBooleanCheckbox id="edit" value="#{module.edit}">
<p:ajax update=":form:table" listener="#{roleModule.permissionCheck}" />
</h:selectBooleanCheckbox>
</p:column>
<p:column headerText="Delete">
<h:selectBooleanCheckbox id="delete" value="#{module.delete}">
<p:ajax update=":form:table" listener="#{roleModule.permissionCheck}" />
</h:selectBooleanCheckbox>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
and if your module is an entity bean, you may want to annotate your checkboxes attributes with #Transient
import java.io.Serializable;
public class Module implements Serializable {
private static final long serialVersionUID = 176253618089501709L;
private String moduleID,rootID,moduleDescription;
private boolean view,edit,delete,create;
public String getModuleID() {
return moduleID;
}
public void setModuleID(String moduleID) {
this.moduleID = moduleID;
}
public String getRootID() {
return rootID;
}
public void setRootID(String rootID) {
this.rootID = rootID;
}
public String getModuleDescription() {
return moduleDescription;
}
public void setModuleDescription(String moduleDescription) {
this.moduleDescription = moduleDescription;
}
public boolean isView() {
return view;
}
public void setView(boolean view) {
this.view = view;
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public boolean isDelete() {
return delete;
}
public void setDelete(boolean delete) {
this.delete = delete;
}
public boolean isCreate() {
return create;
}
public void setCreate(boolean create) {
this.create = create;
}
#Override
public String toString() {
return "Module [moduleID=" + moduleID + ", rootID=" + rootID + ", moduleDescription=" + moduleDescription + ", view=" + view + ", edit=" + edit + ", delete=" + delete + ", create=" + create + "]";
}
}
and finally
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean
#ViewScoped
public class RoleModule implements Serializable{
private static final long serialVersionUID = 1L;
private List<Module> modulesList;
#PostConstruct
public void init() {
modulesList = new ArrayList<Module>();
Module m1 = new Module();
m1.setModuleID("1");
m1.setRootID("root");
m1.setModuleDescription("desc1");
modulesList.add(m1);
Module m2 = new Module();
m2.setModuleID("2");
m2.setRootID("root");
m2.setModuleDescription("desc2");
modulesList.add(m2);
}
public void permissionCheck(AjaxBehaviorEvent event){
Boolean value = (Boolean) ((UIInput) event.getComponent()).getValue();
UIInput component = ((UIInput) event.getComponent());
FacesContext context = FacesContext.getCurrentInstance();
Module module = context.getApplication().evaluateExpressionGet(context, "#{module}", Module.class);
System.out.println(module+","+value+","+component.getId());
switch(component.getId()){
case "create":
case "delete":
case "edit":
if (value){
module.setView(true);
}
break;
case "view":
if (!value){
module.setCreate(false);
module.setDelete(false);
module.setEdit(false);
}
}
}
public List<Module> getModulesList() {
return modulesList;
}
public void setModulesList(List<Module> modulesList) {
this.modulesList = modulesList;
}
}
UPDATE: a little errata below
//try as non-string using equal
Path pathFilterNonString = getPath(filter.getKey(), site, siteType);
Class pathType = pathFilterNonString.getJavaType();
if (pathType.equals(Long.class)){
try{
filterCondition = cb.and(filterCondition, cb.equal(pathFilterNonString, Long.valueOf(filter.getValue())));
}catch(java.lang.NumberFormatException nfe){
//ignore
//java.lang.NumberFormatException: For input string: "a"
}
}else if (pathType.equals(Timestamp.class)){
try{
filterCondition = cb.and(filterCondition, cb.equal(pathFilterNonString, Timestamp.valueOf(filter.getValue())));
}catch(java.lang.IllegalArgumentException e){
//ignore
//java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
}
}
Related
Every time I select some of the elements of my p:datatable it always returns the first one, always.
I have this following piece of code that is used on my screen, in which the detailEntity is referenced in the table as a row of the same.
Tab Lots
<sgv:detailCrud
scrollable="true"
scrollHeight="350"
updateClass="lotChangeListener, .crudButtons"
controller="#{productLotsController}"
btnDetailDeleteLabel="#{productByLotsController.inNewMode or productLotsController.inNewMode ? productsBundle.deleteLabel : productsBundle.inactivateLabel}"
withDelete="#{productLotsController.showEntity and productLotsController.deletableEntity}"
disabled="#{not (productByLotsController.byLots and not productsController.inViewMode)}">
<p:column headerText="#{productsBundle.productLotsBarcode}">
<h:outputText
value="#{detailEntity.barcode}"
converter="barcodeConverter" />
</p:column>
<p:column headerText="#{productsBundle.productLotsNumber}">
<h:outputText value="#{detailEntity.number}" />
</p:column>
<p:column
headerText="#{productsBundle.productLotsExpiration}"
rendered="#{productByLotsController.perishable}">
<h:outputText value="#{detailEntity.expirationData.expiration}">
<f:convertDateTime
type="both"
locale="#{currentUserConfigController.locale}" />
</h:outputText>
</p:column>
<p:column
headerText="#{productsBundle.fieldLabelStockAvailable}"
rendered="#{productsController.hasStockByLocation()}">
<h:outputText value="#{productLotsController.getStockByLocation(detailEntity).totalizedStockData.availableAmount}" />
</p:column>
<p:column
headerText="#{productsBundle.fieldLabelStockReserved}"
rendered="#{productsController.hasStockByLocation()}">
<h:outputText value="#{productLotsController.getStockByLocation(detailEntity).totalizedStockData.reservedAmount}" />
</p:column>
//THIS BUTTON ONLY SELECT THE FIRST ROW OF MY TABLE, IT'S BROKEN.
<p:column
width="35"
rendered="#{productByLotsController.byLots}">
<p:commandButton
id="btnPrintPaperLot"
title="#{productsBundle.btnPrintBarCode}"
process="#this"
actionListener="#{printerSelectorController.onPrint()}"
icon="fa fa-print">
<f:setPropertyActionListener
value="PAPER"
target="#{printerSelectorController.type}" />
<f:setPropertyActionListener
value="#{productLotsController.getTypePrintedProductLot(detailEntity)}"
target="#{printerSelectorController.value}" />
</p:commandButton>
</p:column>
As you can see, I have a custom component that I created called sgv:detailCrud. He is responsible for owning the CRUD architecture of my services, being able to delete, create or view details of a line. (VIDEO DETAILS)
Details CRUD Component
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:composite="http://xmlns.jcp.org/jsf/composite"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
xmlns:of="http://omnifaces.org/functions">
<head>
<title>Details CRUD Component</title>
</head>
<body>
<composite:interface>
<composite:attribute name="style" />
<composite:attribute name="styleClass" />
<composite:attribute name="listStyle" />
<composite:attribute name="listStyleClass" />
<composite:attribute name="datailStyle" />
<composite:attribute name="datailStyleClass" />
<composite:attribute
name="controller"
required="true"
type="eprecise.sgv.server.core.CrudController" />
<composite:attribute
name="disabled"
default="false" />
<composite:attribute
name="withInsert"
default="true" />
<composite:attribute
name="scrollable"
default="false" />
<composite:attribute
name="scrollHeight"
default="400" />
<composite:attribute
name="withDelete"
default="true" />
<composite:attribute
name="withUpdate"
default="true" />
<composite:attribute
name="emptyMessage"
default="#{detailCrudBundle.emptyMessage}" />
<composite:attribute
name="btnNewLabel"
default="#{detailCrudBundle.btnNewLabel}" />
<composite:attribute
name="btnDetailDeleteLabel"
default="#{detailCrudBundle.detailBtnDelete}" />
<composite:attribute
name="btnDetailSaveLabel"
default="#{detailCrudBundle.detailBtnSave}" />
<!-- Parametro de classe Css listener de update -->
<composite:attribute
name="updateClass"
default="#{cc.id}ChangeListener" />
<composite:facet name="list" />
<composite:facet name="details" />
</composite:interface>
<composite:implementation>
<p:outputPanel
id="#{cc.id}"
styleClass="#{cc.id}ChangeListener">
<p:panel
styleClass="Wrapper"
rendered="#{not cc.attrs.controller.showEntity}">
<f:facet name="header">
<composite:renderFacet name="title" />
<p:commandLink
id="btnNew"
styleClass="Fright"
update="#(.#{cc.attrs.updateClass},.#{cc.id}ChangeListener)"
process="#this"
icon="fa fa-plus-circle"
disabled="#{cc.attrs.disabled}"
rendered="#{cc.attrs.withInsert}"
action="#{cc.attrs.controller.onBtnNovoClick()}">
<i class="fa fa-plus-circle Fs23 White"></i>
</p:commandLink>
<p:tooltip
for="btnNew"
showDelay="500"
value="#{cc.attrs.btnNewLabel}" />
<div class="clearfix"></div>
</f:facet>
<p:dataTable
id="list"
selectionMode="single"
scrollable="#{cc.attrs.scrollable}"
scrollHeight="#{cc.attrs.scrollHeight}"
selection="#{cc.attrs.controller.entity}"
emptyMessage="#{cc.attrs.emptyMessage}"
value="#{cc.attrs.controller.dataModel}"
reflow="true"
var="detailEntity"
rowKey="#{detailEntity.id}">
<f:attribute
name="styleClass"
value="#{cc.attrs.listStyleClass} #{cc.attrs.styleClass}" />
<p:ajax
event="rowSelect"
listener="#{cc.attrs.controller.onEntityClick()}"
process="#this"
update="#(.#{cc.attrs.updateClass}, .#{cc.id}ChangeListener, .formConfirmDialog)"
onstart="crudController.blockTable();"
onsuccess="crudController.unblockTable();" />
<composite:insertChildren />
</p:dataTable>
</p:panel>
<p:panel
id="detailCrudPanel"
styleClass="disableFluidForButtons detailForm"
rendered="#{cc.attrs.controller.showEntity}">
<f:attribute
name="styleClass"
value="#{cc.attrs.datailsStyleClass} #{cc.attrs.styleClass} detailForm" />
<f:facet name="header">
<p:commandButton
id="btnSaveDetail_#{cc.id}"
styleClass="saveBtn RaisedButton Fright WidAuto"
update="#(.#{cc.attrs.updateClass}, .#{cc.id}ChangeListener)"
process="#(.detailForm)"
value="#{cc.attrs.btnDetailSaveLabel}"
icon="fa fa-save"
rendered="#{cc.attrs.withUpdate and not cc.attrs.disabled}"
action="#{cc.attrs.controller.onBtnSalvarClick()}" />
<p:commandButton
action="#{cc.attrs.controller.onBtnDeleteClick()}"
icon="fa fa-trash-o"
styleClass="deleteBtn Fright WidAuto"
value="#{cc.attrs.btnDetailDeleteLabel}"
disabled="#{cc.attrs.disabled}"
process="#this"
rendered="#{cc.attrs.withDelete and (cc.attrs.controller.inEditMode or cc.attrs.controller.inViewMode)}"
update="#(.#{cc.attrs.updateClass}, .#{cc.id}ChangeListener)">
</p:commandButton>
<p:commandButton
update="#(.#{cc.attrs.updateClass}, .#{cc.id}ChangeListener)"
process="#this"
styleClass="cancelBtn Fright WidAuto"
icon="fa fa-ban"
value="#{detailCrudBundle.detailBtnCancel}"
rendered="#{not cc.attrs.disabled}"
action="#{cc.attrs.controller.onBtnCancelarClick()}" />
<p:commandButton
update="#(.#{cc.attrs.updateClass}, .#{cc.id}ChangeListener)"
process="#this"
styleClass="RedButton RaisedButton"
icon="fa fa-arrow-left WidAuto"
value="#{detailCrudBundle.detailBtnBack}"
rendered="#{cc.attrs.disabled}"
action="#{cc.attrs.controller.onBtnCancelarClick()}" />
<p:defaultCommand
target="btnSaveDetail_#{cc.id}"
scope="detailCrudPanel" />
</f:facet>
<composite:renderFacet name="details" />
</p:panel>
</p:outputPanel>
</composite:implementation>
</body>
</html>
Another detail is that I can do these crud operations on the rows of the table without any problem, that is, hitting the index. However, I have this problem of always selecting the first row when I click my button to print a lot variation, it's like it doesn't obey the crud architecture for some bizarre reason...
I believe this problem is only for the view, but for the sake of conscience I will post the code of the two controllers of this button here too, follow the thread.
Method that should take the selected entity in the table and assemble it from the String Builder
public String getTypePrintedProductLot(ProductLot selectedLot) {
if (selectedLot != null && selectedLot instanceof ProductLot) {
final Optional<ProductLabelSetting> optional = this.productLabelSettingsRepository.listActives().stream().findFirst();
if (optional.isPresent()) {
final StringBuilder builder = new StringBuilder();
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
final HashMap<String, Object> params = new HashMap<String, Object>();
final Logger log = LoggerFactory.getLogger(ProductLotsController.class);
log.warn("********** SELECTED LOT NUMBER IN TABLE **********\n");
log.warn(selectedLot.getNumber());
log.warn("********** SELECTED LOT NUMBER IN TABLE **********\n");
params.put("product", selectedLot);
final ProductLot lot = selectedLot;
params.put("lot", lot);
if (lot.getExpirationData() instanceof PerishableExpirationData) {
params.put("lotExpiration", sdf.format(lot.getExpirationData().getExpiration()));
} else {
params.put("lotExpiration", "Não Perecível");
}
params.put("login", this.currentUser.getLogin().toUpperCase());
params.put("enterprise", this.currentEnterprise.getName().toUpperCase());
builder.append(optional.get().parser(params));
return builder.toString();
}
}
return null;
}
Controller that receives the values from the String Builder and prints the variation according to this information
package eprecise.sgv.server.core.printers;
import java.io.Serializable;
import java.util.Optional;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import eprecise.sgv.server.products.ProductLotsController;
import org.apache.commons.lang3.StringUtils;
import eprecise.sgv.server.core.ViewController;
import eprecise.sgv.server.core.auth.Current;
import eprecise.sgv.server.core.util.FacesMessageUtil;
import eprecise.sgv.server.devicesHub.remoteHw.RemoteHwChannel;
import eprecise.sgv.server.devicesHub.remoteHw.printers.RemoteHwPrinter;
import eprecise.sgv.server.devicesHub.remoteHw.printers.RemoteHwPrintersRepository;
import eprecise.sgv.server.users.User;
import org.primefaces.PrimeFaces;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ViewController
public class PrinterSelectorController implements Serializable {
private enum PrintType {
COMMON,
PAPER,
COUPON
}
private static final long serialVersionUID = 1L;
private final RemoteHwPrintersRepository repository;
private final User user;
private final RemoteHwChannel remoteHwChannel;
private String id;
private String value;
private String type;
private #NotNull #Min(1) int amount = 1;
private Boolean withAmount = false;
private RemoteHwPrinter printer;
public PrinterSelectorController() {
this.repository = null;
this.user = null;
this.remoteHwChannel = null;
}
#Inject
public PrinterSelectorController(RemoteHwPrintersRepository repository, #Current User user, RemoteHwChannel remoteHwChannel) {
this.repository = repository;
this.user = user;
this.remoteHwChannel = remoteHwChannel;
}
public void onPrint() {
if (!this.withAmount) {
switch (PrintType.valueOf(this.type.toUpperCase())) {
case COMMON:
break;
case PAPER:
if (this.user.hasDefaultPrinterPaper()) {
if (this.print(this.user.getConfigurations().getDefaultPrinters().getPaper())) {
FacesMessageUtil.addInfoMessage("Etiqueta impressa com sucesso.");
break;
}
} else {
this.showDialog();
}
break;
case COUPON:
break;
default:
this.showDialog();
break;
}
} else {
this.showDialog();
}
}
public void onPrint(RemoteHwPrinter printer) {
if (printer != null) {
switch (PrintType.valueOf(this.type.toUpperCase())) {
case COMMON:
break;
case PAPER:
if (this.print(printer)) {
FacesMessageUtil.addInfoMessage("Etiqueta impressa com sucesso.");
}
break;
case COUPON:
break;
}
} else {
FacesMessageUtil.addErrorMessage("Nenhuma impressora selecionada.");
}
}
public void onPrintSelect() {
this.onPrint(this.printer);
}
private boolean print(DefaultPrinter defaultPrinter) {
final Optional<RemoteHwPrinter> optional = this.repository.findById(defaultPrinter.getId());
if (optional.isPresent()) {
return this.print(optional.get());
}
this.showDialog();
return false;
}
private boolean print(RemoteHwPrinter printer) {
if (StringUtils.isNotBlank(this.value)) {
final StringBuilder builder = new StringBuilder();
for (int i = 1; i <= this.amount; i++) {
builder.append(this.value);
}
this.remoteHwChannel.sendPrint(printer, builder.toString());
this.clearFields();
return true;
}
FacesMessageUtil.addErrorMessage("Modelo a ser impresso está vazio.");
return false;
}
private void clearFields() {
this.amount = 1;
this.printer = null;
this.id = null;
this.value = null;
this.type = null;
}
private void showDialog() {
final Logger log = LoggerFactory.getLogger(PrinterSelectorController.class);
log.warn("********* VALUE OF SELECTED LOT *********\n");
log.warn(this.value);
log.warn("********* VALUE OF SELECTED LOT *********\n");
PrimeFaces.current().executeScript(
new StringBuilder("PF('").append(this.id).append("_").append("listPrintersDialogJs").append("').show();").toString());
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public int getAmount() {
return this.amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public RemoteHwPrinter getPrinter() {
if (StringUtils.isEmpty(this.type)) {
return null;
}
switch (PrintType.valueOf(this.type.toUpperCase())) {
case COMMON:
break;
case PAPER:
if (this.user.hasDefaultPrinterPaper()) {
final Optional<RemoteHwPrinter> optional = this.repository
.findById(this.user.getConfigurations().getDefaultPrinters().getPaper().getId());
if (optional.isPresent()) {
this.printer = optional.get();
}
}
break;
case COUPON:
break;
}
return this.printer;
}
public void setPrinter(RemoteHwPrinter printer) {
this.printer = printer;
}
public Boolean getWithAmount() {
return this.withAmount;
}
public void setWithAmount(Boolean withAmount) {
this.withAmount = withAmount;
}
}
Details
I'm using Java 8 with primefaces in version 7
Some images
Video
https://youtu.be/kw_xhQxrV-M
i am pretty new to jsf and i'm having a bit trouble implementing a subTable in my dataTable. Der var atribute from my subtable doesn't seem to evaluate to the elements from the list. Also the #PostConstruct method from my backing bean isn't called either, when i execute my webapp and navigate to the xhtml site. No errors are shown in the console, so i have pretty much no idea what i did wrong.
Backing Bean
#Named(value = "selfEvalBean")
#ViewScoped
public class SelfEvaluationBean extends AbstractBean implements Serializable {
private static final long serialVersionUID = 310401011219411386L;
private static final Logger logger = Logger.getLogger(SelfEvaluationBean.class);
#Inject
private ISelfEvaluationManager manager;
private List<SelfEvaluation> selfEvaluations;
private SelfEvaluationTopic topic;
public List<SelfEvaluation> getSelfEvaluations() {
return selfEvaluations;
}
public void setSelfEvaluation(final List<SelfEvaluation> theSelfEvaluations) {
selfEvaluations = theSelfEvaluations;
}
#PostConstruct
public void init() {
if (!isLoggedIn()) {
return;
}
final User user = getSession().getUser();
List<SelfEvaluation> eval = user.getSelfEvaluations();
if (eval == null) {
eval = manager.createSelfEvaluation(user);
}
selfEvaluations = eval;
topic = new SelfEvaluationTopic();
}
//some methods
/**
* #return the topic
*/
public SelfEvaluationTopic getTopic() {
return topic;
}
/**
* #param theTopic
*/
public void setTopic(final SelfEvaluationTopic theTopic) {
topic = theTopic;
}
}
SelEvaluation Class
#Entity
public class SelfEvaluation extends JPAEntity implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToOne
private User user;
#Column
private String title;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<SelfEvaluationTopic> topics = new ArrayList<>();
public User getUser() {
return user;
}
public void setUser(final User theUser) {
user = theUser;
public List<SelfEvaluationTopic> getTopics() {
return topics;
}
public void setTopics(final List<SelfEvaluationTopic> theTopics) {
topics = theTopics;
}
public void addSelfEvalTopic(final SelfEvaluationTopic theTopic) {
topics.add(theTopic);
}
public void removeSelfEvalTopic(final SelfEvaluationTopic theTopic) {
topics.remove(theTopic);
}
#Override
public boolean equals(final Object theObject) {
if (!(theObject instanceof SelfEvaluation)) {
return false;
}
final SelfEvaluation other = (SelfEvaluation) theObject;
return getId().equals(other.getId());
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
#Override
public int hashCode() {
return getId().hashCode();
}
#Override
public String toString() {
return String.format("SelfEvaluation {id: %d, from: %s}", getId(),
user.getUsername());
}
}
SelfEvaluationTopic Class
#Entity
public class SelfEvaluationTopic extends JPAEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Column(nullable = false)
private String topic;
#Column
private boolean sad;
#Column
private boolean normal;
#Column
private boolean happy;
public String getTopic() {
return topic;
}
public void setTopic(final String theTopic) {
topic = assertNotNull(theTopic);
}
public boolean getSad() {
return sad;
}
public void setSad(final boolean evaluation) {
sad = evaluation;
}
public boolean getNormal() {
return normal;
}
public void setNormal(final boolean evaluation) {
normal = evaluation;
}
public boolean getHappy() {
return happy;
}
public void setHappy(final boolean evaluation) {
happy = evaluation;
}
#Override
public boolean equals(final Object theObject) {
if (!(theObject instanceof SelfEvaluationTopic)) {
return false;
}
final SelfEvaluationTopic other = (SelfEvaluationTopic) theObject;
return getId().equals(other.getId());
}
#Override
public int hashCode() {
return getId().hashCode();
}
#Override
public String toString() {
return String
.format("SelfEvaluationTopic {id: %d, topic: %s, sad: %b, normal: %b, happy: %b}",
getId(), topic, sad, normal, happy);
}
}
XHTML Site
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="templates/template.xhtml">
<!--header and footer template-->
<ui:define name="content">
<f:loadBundle basename="internationalization.selfEval" var="msg" />
<h:form id="form">
<p:growl id="info" autoUpdate="true" />
<p:dataTable id="selfEval" var="eval" value="#{selfEvalBean.selfEvaluations}" >
<f:facet name="header">
#{msg['header']}
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column>
<f:facet name="header">#{msg['selfEval']}</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="sad.png"/>
</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="normal.png"/>
</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="happy.png"/>
</f:facet>
</p:column>
</p:row>
</p:columnGroup>
<p:subTable var="t" value="#{eval.topics}">
<f:facet name="header">
<h:outputText value="#{eval.title}" />
</f:facet>
<p:column id="topic" >
<h:outputText value="#{t}" /> <!--t is of type List<SelfEvaluation> and not SelfEvaluationTopic-->
<p:commandButton style="float:right; width:22px; height: 22px; background-color: #cd001e;" title="Delete" update=":form" action="#{selfEvalBean.remove(t)}" icon="fa fa-trash-o" />
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="s" value="#{t}" />
</div>
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="n" value="#{t}" />
</div>
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="h" value="#{t}" />
</div>
</p:column>
</p:subTable>
</p:dataTable>
<center>
<p:commandButton id="addSelfEvalTopic" styleClass="button" value="#{msg['actionAdd']}" onclick="PF('evalDialog').show();" update=":form" />
<p:commandButton id="selection" styleClass="button" style="float:right;" value="#{msg['actionSelect']}" action="#{selfEvalBean.save}" />
</center>
</h:form>
<p:dialog widgetVar="evalDialog" header="#{msg['newTopic']}" showEffect="clip" hideEffect="clip" resizable="false">
<h:form id="dialog">
<h:panelGrid columns="2">
<p:outputLabel value="Description:" />
<p:inputText value="#{selfEvalBean.topic.topic}" required="true" maxlength="60" />
<p:commandButton value="#{msg['actionSave']}" styleClass="button" action="#{selfEvalBean.addTopic}" update=":form" oncomplete="PF('evalDialog').hide();" />
<p:commandButton value="#{msg['actionCancel']}" styleClass="button" immediate="true" oncomplete="PF('evalDialog').hide();" />
</h:panelGrid>
</h:form>
</p:dialog>
</ui:define>
</ui:composition>
Manager Class fills the Database with some initial data, so there is nothing really interesting going on.
JSF version is 2.2.12 and PrimeFaces version is 6.0.
I'm using Maven for build and the webapp is running on GlassFish 4.1.1.
I would like to limit the number of rows a user can select to 4 and require a minimum of 1 one to be selected. Can this be done with a Primefaces DataTable?
This can easily be done using Primefaces Datatable. I've done an example for you below
XHTML Code:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Test</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable value="#{tBean.availablePersonList}" var="person" id="table"
selection="#{tBean.selectedPersonList}" selectionMode="multi"
rowKey="#{person.name}">
<p:ajax event="rowSelect" listener="#{tBean.rowSelect}" update=":form:table"/>
<p:column headerText="Name">
#{person.name}
</p:column>
<p:column headerText="Address">
#{person.address}
</p:column>
</p:dataTable>
<p:commandButton value="Submit" actionListener="#{tBean.submit}"></p:commandButton>
</h:form>
</h:body>
</html>
Person Class
public class Person {
private String name;
private String address;
public Person(String name, String address) {
super();
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
ManagedBean Code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
#ManagedBean(name = "tBean")
#ViewScoped
public class TestBean implements Serializable {
private List<Person> availablePersonList;
private List<Person> selectedPersonList;
public TestBean() {
availablePersonList = new ArrayList<Person>();
availablePersonList.add(new Person("John", "London"));
availablePersonList.add(new Person("Pat", "London"));
availablePersonList.add(new Person("Meerkut", "Houston"));
availablePersonList.add(new Person("Ali", "London"));
availablePersonList.add(new Person("Parker", "Edinburgh"));
availablePersonList.add(new Person("Laurent", "Paris"));
}
public void submit(ActionEvent e) {
if (selectedPersonList.size() < 1) {
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage("Select at least one item"));
return;
}
}
public void rowSelect(SelectEvent event) {
System.out.println(selectedPersonList.size());
if (selectedPersonList.size() > 3) {
selectedPersonList.remove(event.getObject());
RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage("You cannot selected more than 3"));
return;
}
}
public List<Person> getAvailablePersonList() {
return availablePersonList;
}
public void setAvailablePersonList(List<Person> availablePersonList) {
this.availablePersonList = availablePersonList;
}
public List<Person> getSelectedPersonList() {
return selectedPersonList;
}
public void setSelectedPersonList(List<Person> selectedPersonList) {
this.selectedPersonList = selectedPersonList;
}
}
Outcome:
in this example, we iterate all checkboxes and add a click event listener to each one. if checkbox is clicked then we check selected row count.
<h:form id="form">
<p:dataTable var="car" value="#{listBean.cars}"
selection="#{listBean.selectedCars}"
rowKey="#{car.id}"
paginator="true" rows="10"
widgetVar="myDataTable">
<p:column selectionMode="multiple" style="width:2%;text-align:center"/>
<p:column headerText="Id">
<h:outputText value="#{car.id}"/>
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}"/>
</p:column>
<p:column headerText="Manufacturer">
<h:outputText value="#{car.manufacturer}"/>
</p:column>
<p:column headerText="Model">
<h:outputText value="#{car.model}"/>
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}"/>
</p:column>
</p:dataTable>
<script type="text/javascript">
var MAX_ROW_SELECTION_COUNT = 4;
$(function () {
if (myDataTable.isSelectionEnabled()) {
var dataTableId = myDataTable.jqId;
// hide check all button
$(dataTableId + ' thead:first > tr > th.ui-selection-column .ui-chkbox-all').hide();
var checkboxes = $(dataTableId + ' tbody.ui-datatable-data:first > tr > td.ui-selection-column .ui-chkbox-box');
checkboxes.each(function (index, element) {
var chckbx = $(element);
console.log(chckbx);
chckbx.on("click", function (e) {
var disabled = chckbx.hasClass('ui-state-disabled'),
checked = chckbx.hasClass('ui-state-active');
if (!(checked || disabled)) {
if (myDataTable.getSelectedRowsCount() >= MAX_ROW_SELECTION_COUNT) {
alert('You cannot select more than ' + MAX_ROW_SELECTION_COUNT +' rows.');
return false;
}
}
});
});
}
});
</script>
</h:form>
I have a problem that i can't solve. I have my xhtml page:
The problem is that i have a form where i insert the name and select the location of a travel. It renders an external panel "Volo" where the selectionMenu is updated with some values got from DB based on location selected. Next i want to get a value from Volo selection and update the another panel with ID="HE"(is the one called HotelEsc).
I'm in trouble with the selectionMenu in "Volo" because i can't get the value into it. Always gives an NullPointException error. Probably the problem is that i'm trying to understand how Update and render work and i am mistaking something about these operations. Hope on your help thank you.
Code of xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:panel header="DefaultPackage Form">
<h:panelGrid columns="3" id="regGrid">
<h:outputLabel for="Name">Name:</h:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<h:outputLabel for="location">Locations Available:</h:outputLabel>
<h:selectOneMenu for="location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:ajax listener="#{addDefaultPackageBean.Search()}" render="Volo" />
<f:selectItems id="location"
value="#{addDefaultPackageBean.availableLocations}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo">
<h:outputLabel for="Fly">Volo:</h:outputLabel>
<h:selectOneMenu for="Fly" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Fly" value="#{addDefaultPackageBean.elelisfly}"
var="ElementDTO" itemValue="#{ElementDTO.name}"
itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.sel()}" value="HE" render=":form,:form:regularGrid,:form:Volo" update=":form:Volo" process="form:regGrid,#this"></p:commandButton>
</p:panel>
<p:panel header="HotelEsc" id="HotelEscursioni">
<h:panelGrid columns="3" id="regularGrid">
<h:outputLabel for="Hotel">Hotel:</h:outputLabel>
<h:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
<p:message for="Hotel" />
<h:outputLabel for="Escursion">Escursioni:</h:outputLabel>
<f:facet name="header">Clicca su view per vedere i dettagli</f:facet>
<p:dataTable id="Escursion" var="esc"
value="#{addDefaultPackageBean.elelisescursion}"
rowKey="#{esc.name}"
selection="#{addDefaultPackageBean.selectedEscursions}"
selectionMode="multiple">
<p:column headerText="Nome"> #{esc.name} </p:column>
<p:column headerText="Costo"> #{esc.cost} </p:column>
<p:column headerText="Data Iniziale"> #{esc.startingDate} </p:column>
<p:column headerText="Data Fine"> #{esc.endingDate} </p:column>
<f:facet name="footer">
</f:facet>
</p:dataTable>
</h:panelGrid>
</p:panel>
</h:form>
</h:body>
</html>
Code of related bean:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean{
/**
*
*/
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private boolean flag=true;
private boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
}
#PostConstruct
public void init()
{
this.elelisfly=new ArrayList<ElementDTO>();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.setElelis(elemMgr.getAllElements());
this.availableLocations=new ArrayList<String>();
this.flyElem=new ElementDTO();
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
this.AssignElemFlyFromSelection();
this.AssignElemHotelFromSelection();
this.AssignElemEscursionFromSelection();
defpackMgr.save(defpackDTO);
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila" );
this.setElelis(this.elemMgr.getAllElementsByLocation(this.defpackDTO.getLocation()));
for(ElementDTO e:elelis)
{
System.out.print("elemento della location Haiti "+e.getName());
}
this.AssignElemFlyFromSelection();
System.out.print(this.fly+"Il volo selezionato per la location è "+this.getFlyElem().getName() );
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&((e.getEndingDate().before(this.flyElem.getEndingDate()))))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
this.getElelishotel().add(e);
}
}
}
}
this.setFlag(true);
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}
You are somehow misunderstood the use of some attributes.
I'll post my notes on your code.
The p:commandButton inside Volo section is confusing
it doesn't have a render attribute, it's the update instead, you should remove render.
The update you have is updating the current section Volo is that what you need ?
it's processing only the first section which is regGrid, which means that the values inside Volo section won't be updated to the model inside the managedBean (causing the NullPointer), is that what you want ? don't think so.
Your "HE" button should be link this (If I understood what you want correctly)
<p:commandButton action="#{addDefaultPackageBean.sel()}"
value="HE"
update="HotelEscursioni" process="#parent">
</p:commandButton>
Hope this Helps...
After lots of attempts, i understood how render/update works. I hope the solution with the xhtml here down helps other people with the same problem:
The updates have to be done on the components that you want to refresh(for example in my situation the targets of the updates given from chosen values in selections); process has to be used to specificate which components are used to implement the action.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:outputLabel for="Name">Name:</p:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<p:outputLabel for="Location">Locations Available:</p:outputLabel>
<p:selectOneMenu id="Location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:selectItems
value="#{addDefaultPackageBean.availableLocations}" />
</p:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.Search()}" value="Ciao" render=":form:Volo" update=":form:Volo :form"></p:commandButton>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo" rendered="#{addDefaultPackageBean.flag}">
<h:panelGrid columns="3" id="voloGrid">
<p:outputLabel for="Volare">Volo:</p:outputLabel>
<p:selectOneMenu for="Volare" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Volare" value="#{addDefaultPackageBean.elelisfly}"
var="Ciao" itemValue="#{Ciao.name}"
itemLabel="#{Ciao.name}" />
</p:selectOneMenu>
<p:commandButton actionListener="#{addDefaultPackageBean.sel()}" value="hesef" update=":form:voloGrid :form:HotelEscursioni" process=":form:Location,:form:voloGrid,#this"/>
</h:panelGrid>
</p:panel>
<p:panel header="HotelEscurs" id="HotelEscursioni" rendered="#{addDefaultPackageBean.flagdopo}">
<p:outputLabel for="Hotel">Hotel:</p:outputLabel>
<p:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</p:selectOneMenu>
<p:message for="Hotel" />
<p:dataTable id="Escursion" var="esc"
value="#{addDefaultPackageBean.elelisescursion}"
rowKey="#{esc.name}"
selection="#{addDefaultPackageBean.selectedEscursions}"
selectionMode="multiple">
<p:column headerText="Nome"> #{esc.name} </p:column>
<p:column headerText="Costo"> #{esc.cost} </p:column>
<p:column headerText="Data Iniziale"> #{esc.startingDate} </p:column>
<p:column headerText="Data Fine"> #{esc.endingDate} </p:column>
</p:dataTable>
</p:panel>
</h:form>
</h:body>
</html>
I have a table showing list from a bean. When I click one of the rows, I want to view details from another bean list what would I write to value to second detail datatable list ?
Let say I have a bean of list students datatable containing name, surname and numbers, when I click a row, on the second datatable there is a bean list of student's address, city and country
Now I can System.out.print the adress detail of student when I click to row in student table but I can't show it on datatable
I'm asking how I can take the values to a datatable, what will be the value in datatable?
Thanks for your help
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<f:view>
<h:form id="form">
<p:dataTable id="users" var="user" value="#{userOS.osList}"
paginator="true" rows="10" rowKey="#{user.kisiid}"
selection="#{userOS.selectedOS}" selectionMode="single">
<f:facet name="header">
Kullanıcı detaylarını görmek için view butonuna tıklayınız
</f:facet>
<p:ajax event="rowSelect" listener="#{userOS.onRowSelect}" update=":form:display"
oncomplete="userDialog" />
<p:column headerText="Student No" sortBy="ogrencino"
filterBy="ogrencino" id="ogrencino">
<h:outputText value="#{user.ogrencino}" />
<f:param name="kid" value="#{userOS.osList.rowIndex}" />
</p:column>
<p:column headerText="Name" sortBy="ad" filterBy="ad" id="ad">
<h:outputText value="#{user.ad}" />
</p:column>
<p:column headerText="Surname" sortBy="soyad" filterBy="soyad"
id="soyad">
<h:outputText value="#{user.soyad}" />
</p:column>
<p:column headerText="Faculty" sortBy="altbirim.ad"
filterBy="altbirim.ad" id="altbirim">
<h:outputText value="#{user.altbirim.ad}" />
</p:column>
<p:column headerText="Department" sortBy="bolum.ad"
filterBy="bolum.ad" id="bolum">
<h:outputText value="#{user.bolum.ad}" />
</p:column>
<p:column headerText="Status" sortBy="ogrencidurum.ad"
filterBy="ogrencidurum.ad" id="ogrencidurum">
<h:outputText value="#{user.ogrencidurum.ad}" />
</p:column>
<f:facet name="footer">
</f:facet>
</p:dataTable>
<p:panel id="dialog" header="User Detail" widgetVar="userDialog">
<h:panelGrid id="panelgrid" columns="2" cellpadding="4">
<p:dataTable id="display" var="adres" value="#{userOS.adresList}">
<p:column headerText="Adres Tipi">
<h:outputText value="#{adres.AddressType}" />
</p:column>
<p:column headerText="Adres">
<h:outputText value="#{adres.Address}" />
</p:column>
<p:column headerText="İl">
<h:outputText value="#{adres.City}" />
</p:column>
<p:column headerText="Ülke">
<h:outputText value="#{adres.Country}" />
</p:column>
</p:dataTable>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</h:body>
</html>
And KisiInfoProcess.java code :
package com.revir.process;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.SelectEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.revir.managed.bean.AddressBean;
import com.revir.managed.bean.OgrenimSureciBean;
import com.revir.domain.Adres;
import com.revir.domain.AdresDAO;
import com.revir.domain.Kisi;
import com.revir.domain.KisiDAO;
import com.revir.domain.Kisiadresi;
import com.revir.domain.Ogrenimsureci;
import com.revir.domain.OgrenimsureciDAO;
import com.revir.domain.Ulke;
import com.revir.process.KisiInfoProcess;
#ManagedBean(name = "userOS")
#SessionScoped
public class KisiInfoProcess implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory
.getLogger(KisiInfoProcess.class);
private List<OgrenimSureciBean> osList;
private List<AddressBean> adresList;
private List<AddressBean> adresListesi;
public List<AddressBean> getAdresListesi() {
return adresListesi;
}
public void setAdresListesi(List<AddressBean> adresListesi) {
this.adresListesi = adresListesi;
}
private OgrenimSureciBean selectedOS;
private AddressBean selectedAdres;
public OgrenimSureciBean getSelectedOS() {
return selectedOS;
}
public void setSelectedOS(OgrenimSureciBean selectedOS) {
this.selectedOS = selectedOS;
}
public AddressBean getSelectedAdres() {
return selectedAdres;
}
public void setSelectedAdres(AddressBean selectedAdres) {
this.selectedAdres = selectedAdres;
}
public List<OgrenimSureciBean> getOsList() {
OgrenimsureciDAO ogrenimsureciDAO = new OgrenimsureciDAO();
List<OgrenimSureciBean> osList = new ArrayList<OgrenimSureciBean>();
for (Iterator i = ogrenimsureciDAO.findByMezunOgrenciler((short) 8)
.iterator(); i.hasNext();) {
Ogrenimsureci og = (Ogrenimsureci) i.next();
OgrenimSureciBean osBean = new OgrenimSureciBean();
osBean.setBolum(og.getBolum());
osBean.setAd(og.getKisiByKisiid().getAd());
osBean.setSoyad(og.getKisiByKisiid().getSoyad());
osBean.setAltbirim(og.getAltbirim());
osBean.setOgrencino(og.getOgrencino());
osBean.setKisiid(og.getKisiByKisiid().getKisiid());
osBean.setOgrencidurum(og.getOgrencidurum());
osList.add(osBean);
System.out.println("osBean : " + osBean.toString());
}
return osList;
}
public void setOsList(List<OgrenimSureciBean> osList) {
this.osList = osList;
}
public void onRowSelect(SelectEvent event) {
System.out.println("On Row Select Metodu çalıştı");
try {
getAdresList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<AddressBean> getAdresList() throws Exception {
if (getSelectedOS() != null) {
log.debug("PersonalInfoProcess - getAddressInfo - Start");
List<AddressBean> adresList = new ArrayList<AddressBean>();
KisiDAO kisiDAO = new KisiDAO();
AdresDAO adresDAO = new AdresDAO();
Long kisiid = getSelectedOS().getKisiid();
System.out.println("kisiid :" + kisiid);
Kisi kisi = kisiDAO.findById(kisiid);
for (Iterator i = kisi.getKisiadresis().iterator(); i.hasNext();) {
Kisiadresi kisiAdresi = (Kisiadresi) i.next();
System.out.println("i :" + i);
Adres tmpAdres = adresDAO.findById(kisiAdresi.getId()
.getAdresid());
if (tmpAdres != null) {
AddressBean address = new AddressBean(kisiid);
if (tmpAdres.getAdresturu() == null) {
address.setAddressType(null);
} else {
address.setAddressType(tmpAdres.getAdresturu().getAd());
System.out.println("Adres Türü:" +tmpAdres.getAdresturu().getAd());
}
address.setAddress(tmpAdres.getAdres());
System.out.println("Şehir:" +tmpAdres.getAdres());
if (tmpAdres.getIl() == null) {
address.setCity(null);
} else {
address.setCity(tmpAdres.getIl().getAd());
System.out.println("Şehir:" +tmpAdres.getIl().getAd());
}
if (tmpAdres.getUlke() == null) {
address.setCountry(null);
} else {
address.setCountry(tmpAdres.getUlke().getAd());
System.out.println("Ülke:" +tmpAdres.getUlke().getAd());
}
adresList.add(address);
System.out.println("adres" + address);
System.out.println("adreslist" + adresList);
}
log.debug("PersonalInfoProcess - getAddressInfo - End / Returning");
}
}
return adresList;
}
public void setAdresList(List<AddressBean> adresList) {
this.adresList = adresList;
}
}