PrimeFaces Datatable always selecting the first element - jsf

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

Related

Primefaces subTable in dataTable not working

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.

Button doesnot call managed bean method in Primefaces

Hi trying to call the method on button click, but it doesnt work i also tried onclick instead action it also doesnt work. i couldnt understand where is the mistake please help me
here is my managed bean
package com.primefaces.managedbean;
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.ManagedProperty;
import javax.faces.bean.ViewScoped;
import com.primefaces.domain.KenLocation;
import com.primefaces.service.ILocationService;
#ManagedBean(name = "locationbean")
#ViewScoped
public class LocationBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1101264226039168006L;
/**
*
*/
#ManagedProperty(value = "#{LocationService}")
private ILocationService locationService;
private List<KenLocation> locationList = new ArrayList<KenLocation>();
KenLocation kenLocation;
private String locationName;
private String address1;
private String address2;
private String city;
private String pincode;
private String state;
private String contactNo;
private String organisationName;
#PostConstruct
private void init() {
locationList = locationService.onLoad();
}
public void addnewlocation() {
System.out.println("I am inside newlocation");
kenLocation = new KenLocation();
kenLocation.setLocationName(locationName);
kenLocation.setAddress1(address1);
kenLocation.setAddress2(address2);
kenLocation.setCity(city);
kenLocation.setPincode(Integer.parseInt(pincode));
kenLocation.setPhone(contactNo);
System.out.println(kenLocation);
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public ILocationService getLocationService() {
return locationService;
}
public void setLocationService(ILocationService locationservice) {
this.locationService = locationservice;
}
public List<KenLocation> getLocationList() {
return locationList;
}
public void setLocationList(List<KenLocation> a_locationList) {
locationList = a_locationList;
}
}
and JSF
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<ui:composition 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"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h5>Product List {9 Products can be added per mail}</h5>
<p:separator></p:separator>
<p:growl id="growlLocationtable"></p:growl>
<p:commandButton id="new_location" title="CreateLocation" type="button"
icon="ui-icon-document" onclick="PF('dlg1').show()" />
<p:commandButton id="edit_location" title="EditLocation"
icon=" ui-icon-pencil" />
<p:commandButton id="delete_location" title="DeleteLocation"
icon="ui-icon-trash" />
<h:form id="Locationdataform">
<h:panelGrid columns="2" id="Locationdatatablepanel" resizable="false"
size="600">
<p:dataTable id="Locationdatatable" var="odt"
value="#{locationbean.locationList}">
<p:column headerText="Location Name">
<h:outputText value="#{odt.locationName}" />
</p:column>
<p:column headerText="Address Line1">
<h:outputText value="#{odt.address1}" />
</p:column>
<p:column headerText="Address Line2">
<h:outputText value="#{odt.address2}" />
</p:column>
<p:column headerText="City">
<h:outputText value="#{odt.city}" />
</p:column>
<p:column headerText="Pincode">
<h:outputText value="#{odt.pincode}" />
</p:column>
<p:column headerText="State">
<h:outputText value="#{odt.state}" />
</p:column>
<p:column headerText="Contact No">
<h:outputText value="#{odt.phone}" />
</p:column>
<p:column headerText="Organisation Name">
<h:outputText value="#{odt.ken_Org_ID.name}" />
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
<!-- dialog -->
<p:dialog header="Add Location" widgetVar="dlg1" minHeight="40"
modal="true">
<h:form id="addLocationForm">
<h:panelGrid columns="2" id="grid">
<h:outputLabel value="Location Name"></h:outputLabel>
<p:inputText id="txt_Name" value="#{locationbean.locationName}" />
<h:outputLabel value="Address1"></h:outputLabel>
<p:inputText id="txt_address1" value="#{locationbean.address1}" />
<h:outputLabel value="Address2"></h:outputLabel>
<p:inputText id="txt_address2" value="#{locationbean.address2}" />
<h:outputLabel value="City"></h:outputLabel>
<p:inputText id="txt_city" value="#{locationbean.city}" />
<h:outputLabel value="Pincode"></h:outputLabel>
<p:inputText id="txt_pincode" value="#{locationbean.pincode}" />
<h:outputLabel value="State"></h:outputLabel>
<p:inputText id="txt_state" value="#{locationbean.state}" />
<h:outputLabel value="Contactno"></h:outputLabel>
<p:inputText id="txt_contactno" value="#{locationbean.contactNo}" />
<h:outputLabel value="Organistaion name"></h:outputLabel>
<p:inputText id="txt_orgname"
value="#{locationbean.organisationName}" />
<p:commandButton id="addlocatin_btn" value="Save"
action="#{locationbean.addnewlocation}" type="submit" />
</h:panelGrid>
</h:form>
</p:dialog>

JSF selectbooleancheckbox validation

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]
}
}

h:selecteOneMenu values

I have the following files in my application but I can't get the values from the selectOneMenu on file elementoUpdateDialog.xhtml to update the dataTable on gerirElementos.xhtml and sql table.
Where is my error?
elementoUpdateDialog.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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:dialog widgetVar="elementoUpdateDialogWidget"
id="elementoUpdateDialogId" height="300" width="500" modal="true"
closable="true" draggable="false" resizable="false">
<h:form id="elementoUpdateDialogForm" prependId="false">
<h:panelGrid columns="2">
<h:outputText value="elementoID" />
<h:inputText value="#{elementoMB.elemento.elementoId}"
required="true" label="elementoID" />
<h:outputText value="Posto" />
<h:outputText value="#{elementoMB.elemento.posto.postoId}" />
<h:selectOneMenu value="#{postoMB.posto.postoId}">
<f:selectItems value="#{postoMB.allPostos}" var ="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="# {elementoMB.elemento.posto.postoId}"/>
</h:selectOneMenu>
<br />
<h:outputText value="Classe" />
<h:outputText value="#{elementoMB.elemento.classe.classeId}" />
<h:selectOneMenu value="# {elementoMB.elemento.classe.classeId}">
<f:selectItems value="#{classeMB.allClasses}"/>
<f:selectItem itemValue="# {elementoMB.elemento.classe.classeId}" itemLabel="#{elementoMB.elemento.classe.classeId}"/>
</h:selectOneMenu>
<br/>
<h:outputText value="Nome" />
<h:inputText value="#{elementoMB.elemento.nome}" required="true"
label="Nome" />
<h:outputText value="NII" />
<h:inputText value="#{elementoMB.elemento.NII}" required="true"
label="NII" />
<p:commandButton value="Gravar" icon="ui-icon-plus"
action="#{elementoMB.updateElemento()}"
update=":messageGrowl :elementosForm:elementosTable"
oncomplete="closeDialogIfSucess(xhr, status, args, elementoUpdateDialogWidget, 'elementoUpdateDialogId')" />
<p:commandButton value="Cancelar" icon="ui-icon-cancel"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoUpdateDialogWidget.hide();" type="button" />
</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</html>
gerirElementos.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:ui="http://java.sun.com/jsf/facelets"
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>
<ui:composition template="/pages/protected/templates/master.xhtml">
<ui:define name="divMain">
<p:menubar>
<p:submenu label="Elementos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirElementos.xhtml" />
</p:submenu>
<p:submenu label="Classes" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirClasses.xhtml" />
</p:submenu>
<p:submenu label="Postos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirPostos.xhtml" />
</p:submenu>
<p:submenu label="RegistoSarPerm" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirRegistoSarPerm.xhtml" />
</p:submenu>
</p:menubar>
<h:form id="elementosForm">
<p:dataTable id="elementosTable" var="elemento"
value="#{elementoMB.allElementos}" paginator="true" rows="10"
selepaginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="1,5,10">
<f:facet name="header">
Lista de Elementos
</f:facet>
<p:column headerText="NII" sortBy="nii" id="nii">
#{elemento.NII}
</p:column>
<p:column headerText="Posto" sortBy="posto" id="posto">
#{elemento.posto.posto}
</p:column>
<p:column headerText="Classe" sortBy="classe" id="classe">
#{elemento.classe.classe}
</p:column>
<p:column headerText="Nome" sortBy="nome" id="nome">
#{elemento.nome}
</p:column>
<p:column>
<p:spacer width="10px" />
<p:commandButton value="Editar" icon="ui-icon-pencil"
update=":elementoUpdateDialogForm"
onclick="elementoUpdateDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
<p:commandButton value="Eliminar" icon="ui-icon-trash"
update=":elementoDeleteDialogForm"
onclick="elementoDeleteDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
</p:column>
</p:dataTable>
<p:commandButton value="Novo Elemento" icon="ui-icon-plus"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoCreateDialogWidget.show();" />
</h:form>
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoCreateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoUpdateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoDeleteDialog.xhtml" />
</ui:define>
</ui:composition>
</h:body>
</html>
Elemento.java
package com.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Elemento")
public class Elemento implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="elementoId")
private int elementoId;
#ManyToOne
#JoinColumn(name = "classeId")
private Classe classe;
#ManyToOne
#JoinColumn(name="postoID")
private Posto posto;
#Column(name="NII")
private String NII;
#Column(name="nome")
private String nome;
public Elemento(){
}
public Elemento(String NII, String nome){
this.NII = NII;
this.nome = nome;
}
//Getters and Setters
public int getElementoId() {
return elementoId;
}
public void setElementoId(int elementoId) {
this.elementoId = elementoId;
}
public String getNII() {
return NII;
}
public void setNII(String nII) {
NII = nII;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Classe getClasse() {
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public Posto getPosto() {
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
#Override
public int hashCode() {
return elementoId;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Elemento) {
Elemento elemento = (Elemento) obj;
return elemento.getElementoId() == elementoId;
}
return false;
}
}
ElementoMB.java
package com.mb;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.facade.ElementoFacade;
import com.model.Classe;
import com.model.Elemento;
import com.model.Posto;
#ViewScoped
#ManagedBean
public class ElementoMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
private Posto posto;
private Classe classe;
private Elemento elemento;
private List<Elemento> elementos;
private ElementoFacade elementoFacade;
public void createElemento() {
try {
getElementoFacade().createElemento(elemento);;
closeDialog();
displayInfoMessageToUser("Created With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void updateElemento() {
try {
getElementoFacade().updateElemento(elemento);
closeDialog();
displayInfoMessageToUser("Updated With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void deleteElemento() {
try {
getElementoFacade().deleteElemento(elemento);
closeDialog();
displayInfoMessageToUser("Deleted With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public List<Elemento> getAllElementos(){
if (elementos == null){
loadElementos();
}
return elementos;
}
public ElementoFacade getElementoFacade() {
if (elementoFacade == null) {
elementoFacade = new ElementoFacade();
}
return elementoFacade;
}
public Elemento getElemento() {
if (elemento == null) {
elemento = new Elemento();
}
return elemento;
}
public void setElemento(Elemento elemento) {
this.elemento = elemento;
}
private void loadElementos() {
elementos = getElementoFacade().listAll();
}
public void resetElemento() {
elemento = new Elemento();
}
public Posto getPosto() {
if (posto == null){
posto = new Posto();
}
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
public Classe getClasse() {
if (classe == null) {
classe = new Classe();
}
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public void resetClasse() {
classe = new Classe();
}
}
ElementoFacade.java
package com.facade;
import java.io.Serializable;
import java.util.List;
import com.dao.ElementoDAO;
import com.model.Elemento;
public class ElementoFacade implements Serializable {
private static final long serialVersionUID = 1L;
private ElementoDAO elementoDAO = new ElementoDAO();
public void createElemento(Elemento elemento) {
elementoDAO.beginTransaction();
elementoDAO.save(elemento);
elementoDAO.commitAndCloseTransaction();
}
public void updateElemento(Elemento elemento) {
elementoDAO.beginTransaction();
Elemento persistedElemento = elementoDAO.find(elemento.getElementoId());
persistedElemento.setNome(elemento.getNome());
persistedElemento.setNII(elemento.getNII());
elementoDAO.commitAndCloseTransaction();
}
public void deleteElemento(Elemento elemento){
elementoDAO.beginTransaction();
Elemento persistedElementoWithIdOnly = elementoDAO.findReferenceOnly(elemento.getElementoId());
elementoDAO.delete(persistedElementoWithIdOnly);
elementoDAO.commitAndCloseTransaction();
}
public Elemento findElemento(int elementoId) {
elementoDAO.beginTransaction();
Elemento elemento = elementoDAO.find(elementoId);
elementoDAO.closeTransaction();
return elemento;
}
public List<Elemento> listAll() {
elementoDAO.beginTransaction();
List<Elemento> result = elementoDAO.findAll();
elementoDAO.closeTransaction();
return result;
}
}
Here,
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="#{elementoMB.elemento.posto.postoId}"/>
Your itemLabel and itemValue attributes, representing the current option label and value, are wrong. They're for some unclear reason referencing a backing bean property instead of the currently iterated option object as definied in var="posto".
Fix it accordingly:
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{posto.postoId}" itemValue="#{posto}"/>
This should display the items correctly.
And here,
<h:selectOneMenu value="#{postoMB.posto.postoId}">
the selected item is wrong. This would only cause problems during submitting and during displaying a preselected item. You should refer the very same type as itemValue itself, not some ID (otherwise you're changing only the id of an entity instead of the entity itself, resulting in major potential trouble as those are references):
<h:selectOneMenu value="#{postoMB.posto}">
Supply if necessary a converter in case you don't have a #FacesConverter(forClass=Posto.class).
Apply the same lesson learnt on the other <h:selectOneMenu> you've there.
See also:
Our <h:selectOneMenu> wiki page
How to populate options of h:selectOneMenu from database?

Primefaces actionbutton called several times

I've been strugling with an issue I can't find the way to solve it and I can't find anything related on the web.
I'm using Netbeans with Primefaces to develop a JSF web app.
Everything works fine except that sometimes the call to the actionlisteners is being done several times.
For example this is my JSF page with primefaces:
<h:body>
<ui:composition template="home.xhtml">
<ui:define name="content">
<h2>Administración de alertas SMS</h2>
<p:panel id="display">
<p:selectBooleanCheckbox itemLabel="Enviar alertas SMS" value="#{smsConfigBean.alertsEnabled}"/>
<p>
<h:outputText value="Mensaje de Texto: " /><br /><br />
<p:inputTextarea rows="5" cols="50" counterTemplate="{0} caracteres restantes." counter="counter" maxlength="160" value="#{smsConfigBean.smsMessage}" id="smsMessage"/>
<br />
<h:outputText id="counter" />
</p>
<p>
<h:outputText value="Dispositivo de envio SMS: " />
<p:selectOneRadio id="options" value="#{smsConfigBean.usePhone}">
<f:selectItem itemLabel="Modem USB" itemValue="false" />
<f:selectItem itemLabel="Telefono Android" itemValue="true" />
</p:selectOneRadio>
</p>
<br />
<p:tabView id="tabView">
<p:tab id="tab1" title="Modem USB">
<h:panelGrid id="modemGrid" columns="2" cellpadding="4">
<h:outputText value="Puerto: " />
<p:inputText id="port" value="#{smsConfigBean.port}"/>
<h:outputText value="Bit Rate (Opcional): " />
<p:inputText id="bitRate" value="#{smsConfigBean.bitRate}"/>
<h:outputText value="Nombre de modem (Opcional): " />
<p:inputText id="modemName" value="#{smsConfigBean.modemName}"/>
<h:outputText value="PIN: " />
<p:inputText id="pin" value="#{smsConfigBean.modemPin}"/>
<h:outputText value="Centro de Mensajes: " />
<p:inputText id="smsc" value="#{smsConfigBean.SMSC}"/>
</h:panelGrid>
</p:tab>
<p:tab id="tab2" title="Telefono Android">
<h:panelGrid id="phoneGrid" columns="2" cellpadding="4">
<h:outputText value="Path ADB:" />
<p:inputText id="adbPath" value="#{smsConfigBean.adbPath}"/>
<h:outputText value="Directorio de Configuracion:" />
<p:inputText id="configPath" value="#{smsConfigBean.configPath}"/>
<h:outputText value="Modo de conexion " />
<p:selectOneRadio id="connectOptions" value="#{smsConfigBean.useWifi}">
<f:selectItem itemLabel="USB" itemValue="false"/>
<f:selectItem itemLabel="WiFi" itemValue="true" />
</p:selectOneRadio>
<h:outputText value="Direccion IP (Solo para WiFi): " />
<p:inputText id="ipDir" value="#{smsConfigBean.ipDir}"/>
</h:panelGrid>
</p:tab>
</p:tabView>
</p:panel>
<br />
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}" actionListener="#{smsConfigBean.saveChanges}"/>
</ui:define>
</ui:composition>
</h:body>
And this is my backend bean:
package Beans;
import helpers.Global; import javax.faces.bean.ManagedBean; import
javax.faces.bean.SessionScoped;
#ManagedBean #SessionScoped public class SmsConfigBean {
private Boolean alertsEnabled;
private Boolean usePhone;
private Boolean useWifi;
private String port;
private int bitRate;
private String modemName;
private String modemPin;
private String SMSC;
private String adbPath;
private String configPath;
private String ipDir;
private String smsMessage;
public SmsConfigBean() {
alertsEnabled = Global.getAlertsEnabled();
port = Global.getPort();
bitRate = Global.getBitRate();
modemName = Global.getModemName();
modemPin = Global.getModemPin();
SMSC = Global.getSMSC();
usePhone = Global.getUsePhone();
adbPath = Global.getAdbPath();
configPath = Global.getConfigPath();
useWifi = Global.getUseWifi();
ipDir = Global.getIpDir();
smsMessage = Global.getSmsMessage();
}
public Boolean getAlertsEnabled() {
return alertsEnabled;
}
public void setAlertsEnabled(Boolean alertsEnabled) {
this.alertsEnabled = alertsEnabled;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getBitRate() {
return bitRate;
}
public void setBitRate(int bitRate) {
this.bitRate = bitRate;
}
public String getModemName() {
return modemName;
}
public void setModemName(String modemName) {
this.modemName = modemName;
}
public String getModemPin() {
return modemPin;
}
public void setModemPin(String modemPin) {
this.modemPin = modemPin;
}
public String getSMSC() {
return SMSC;
}
public void setSMSC(String SMSC) {
this.SMSC = SMSC;
}
public Boolean getUsePhone() {
return usePhone;
}
public void setUsePhone(Boolean usePhone) {
this.usePhone = usePhone;
}
public String getAdbPath() {
return adbPath;
}
public void setAdbPath(String adbPath) {
this.adbPath = adbPath;
}
public String getConfigPath() {
return configPath;
}
public void setConfigPath(String configPath) {
this.configPath = configPath;
}
public Boolean getUseWifi() {
return useWifi;
}
public void setUseWifi(Boolean useWifi) {
this.useWifi = useWifi;
}
public String getIpDir() {
return ipDir;
}
public void setIpDir(String ipDir) {
this.ipDir = ipDir;
}
public String getSmsMessage() {
return smsMessage;
}
public void setSmsMessage(String smsMessage) {
this.smsMessage = smsMessage;
}
public void saveChanges(){
Global.setSmsMessage(smsMessage);
Global.setIpDir(ipDir);
Global.setUseWifi(useWifi);
Global.setConfigPath(configPath);
Global.setAdbPath(adbPath);
Global.setUsePhone(usePhone);
Global.setSMSC(SMSC);
Global.setModemPin(modemPin);
Global.setModemName(modemName);
Global.setBitRate(bitRate);
Global.setPort(port);
Global.setAlertsEnabled(alertsEnabled);
Global.sendInfoResponseMessage("Cambios guardados con exito");
}
}
The problem is that when saving the changes of this form by hitting the commandButton 'saveSmsAlerts' the call is being made twice. Resulting in the growl message to be shown twice too.
(You won't see the growl component because it was defined in the template)
This happens also in another page that I did for the same app that uploads a file using fileuploader. The file is uploaded 4 times!!
I'm using chrome to test the application and netbeans to develop it.
You should remove one of action or actionListener attribute.
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" action="#{smsConfigBean.saveChanges}"/>
if you remove action attribute you should change the action method signature
<p:commandButton id="saveSmsAlerts" value="Guardar" update="messages" actionListener="#{smsConfigBean.saveChanges}"/>
Like this
public void saveChanges(ActionEvent e){
...
}
here is the difference between action and actionListener
Differences between action and actionListener

Resources