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