How to pass around action outcome to jsf composition? - jsf

I have this JSF snippet which works fine. When the commandbutton is clicked it should reload the page by redirecting to itself.
<p:dataTable value="#{fileModel.files}"
var="file" scrollable="true" scrollHeight="400">
<p:column headerText="#{msgs.lbl_file}">
#{file.name}
</p:column>
<p:column width="150">
<p:commandButton value="#{msgs.lbl_import}"
actionListener="#{fileModel.importFile(file, module)}"
**action="mypage.jsf?faces-redirect=true"**/>
</p:column>
<p:column width="150">
<p:commandLink value="#{msgs.lbl_view}" target="_blank" ajax="false"
actionListener="#{fileModel.view(file)}"/>
</p:column>
</p:dataTable>
Because I want to reuse this in multiple pages I tried to make this JSF template and include it via ui:include. Only thing is that I need the action to be configurable depending on the page it is used in.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:dataTable value="#{fileModel.files}"
var="file" scrollable="true" scrollHeight="400">
<p:column headerText="#{msgs.lbl_file}">
#{file.name}
</p:column>
<p:column width="150">
<p:commandButton value="#{msgs.lbl_import}"
actionListener="#{fileModel.importFile(file, module)}"
**action="#{redirectTo}"**/>
</p:column>
<p:column width="150">
<p:commandLink value="#{msgs.lbl_view}" target="_blank" ajax="false"
actionListener="#{fileModel.view(file)}"/>
</p:column>
</p:dataTable>
</ui:composition>
With the inclusion
<ui:include src="moduleSettingImportDialog.xhtml">
<ui:parameter name="redirectTo" value="mypage.jsf?faces-redirect=true"/>
</ui:include>
The error I get is something like
javax.el.ELException: Not a Valid Method Expression: #{redirectTo}
at
com.sun.el.lang.ExpressionBuilder.createMethodExpression(ExpressionBuilder.java:311)
at
com.sun.el.ExpressionFactoryImpl.createMethodExpression(ExpressionFactoryImpl.java:96)
at
org.jboss.weld.util.el.ForwardingExpressionFactory.createMethodExpression(ForwardingExpressionFactory.java:43)
at
org.jboss.weld.el.WeldExpressionFactory.createMethodExpression(WeldExpressionFactory.java:53)
at
com.sun.faces.facelets.tag.TagAttributeImpl.getMethodExpression(TagAttributeImpl.java:240)
at
com.sun.faces.facelets.tag.jsf.ActionSourceRule$ActionMapper2.applyMetadata(ActionSourceRule.java:107)
at
com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:81)
A similar error I get when using JSF composite components.
<c:interface>
<c:attribute name="module"/>
<c:attribute name="redirectTo" type="java.lang.String"/>
</c:interface>
<c:implementation rendered="#{systemSettingModel.LOG_REASON_FOR_CHANGES_ISAKTIV}">
<p:dataTable value="#{fileModel.files}"
var="file" scrollable="true" scrollHeight="400">
<p:column headerText="#{msgs.lbl_file}">
#{file.name}
</p:column>
<p:column width="150">
<p:commandButton value="#{msgs.lbl_import}"
actionListener="#{fileModel.importFile(file, cc.attrs.module)}"
**action="#{cc.attrs.redirectTo}"**/>
</p:column>
<p:column width="150">
<p:commandLink value="#{msgs.lbl_view}" target="_blank" ajax="false"
actionListener="#{fileModel.view(file)}"/>
</p:column>
</p:dataTable>
</c:implementation>
#{cc.attrs.redirectTo}: javax.el.ELException:
java.lang.IllegalArgumentException: Cannot convert
multimodulesettings.jsf?faces-redirect=true&includeViewParams=true of
type class java.lang.String to class javax.el.MethodExpression
javax.faces.FacesException: #{cc.attrs.redirectTo}:
javax.el.ELException: java.lang.IllegalArgumentException: Cannot
convert
multimodulesettings.jsf?faces-redirect=true&includeViewParams=true of
type class java.lang.String to class javax.el.MethodExpression at
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315) at
javax.faces.component.UIData.broadcast(UIData.java:1108) at
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) at
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:78)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at
org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
How to pass a fixed string to a JSF template or composite component that is used in the action attribute of a commandButton?

As a workaround I implemented a JSF bean method that just returns the passed in string like so.
public String echo(String s) {
return s;
}
Then instead of passing the fix string as a parameter to the component it is being passed by an EL expression.
<ui:include src="moduleSettingImportDialog.xhtml">
<ui:parameter name="redirectTo" value="#{jsfBean.echo('mypage.jsf?faces-redirect=true')}"/>
</ui:include>

Related

Binding in JSF not working

I am trying to make a h:panelgrid visible and invisible by clicking on a button that's why i made this code:
<p:menu styleClass="ui-menubar" style="width:auto">
<p:menuitem value="khraaaaaaaaa" actionListener="#{accounts.buttonUser()}"></p:menuitem>
</p:menu>
<h:panelGrid id="naalobouk" binding="#{accounts.pg1}">
<h1>Activer/désactiver un compte étudiant</h1>
<hr/>
<h:form id="etudiants">
<p:dataTable emptyMessage="Pas d'étudiant!"
paginator="true"
paginatorPosition="bottom"
rows="4"
value="#{accounts.etudiants}"
var="stu">
<f:facet name="header">
<h:outputText value="Les comptes étudiant" />
</f:facet>
<p:column headerText="#">
<h:outputText value="#{stu.id}" />
</p:column>
<p:column headerText="nom">
<h:outputText value="#{stu.nom}" />
</p:column>
<p:column headerText="prenom">
<h:outputText value="#{stu.prenom}" />
</p:column>
<p:column headerText="email">
<h:outputText value="#{stu.email}" />
</p:column>
<p:column headerText="password">
<h:outputText value="#{stu.password}" />
</p:column>
<p:column headerText="action">
<p:commandButton rendered="#{accounts.butshow}" value="#{stu.actif?'desactiver':'activer'}" action="#{accounts.doToggleStudentState(stu)}" update=":etudiants"/>
</p:column>
</p:dataTable>
</h:form>
</h:panelGrid>
and here is my bean code
private HtmlPanelGrid pg1 = new HtmlPanelGrid();//getter and setter
public void buttonUser(){
if(pg1.isRendered()==true){
pg1.setRendered(false);;
}
if(pg1.isRendered()==false){
pg1.setRendered(true);
}
}
When i click on the button nothing happens. What's the problem here ?
I'm assuming you want the method to negate the rendered property. In that case the method is flawed, as mentioned in the comments. The simplest code would be
public void buttonUser() {
pg1.setRendered(!pg1.isRendered());
}
The main problem is that the p:menuItem by default uses ajax, which by default does'nt update anything on the page. So either update something, or don't use ajax;
<p:menuitem value="khraaaaaaaaa" actionListener="#{accounts.buttonUser()}" ajax="false">
With ajax you need to wrap the panelGrid in a component that will always be rendered, since you can't update a component that has not been rendered in the first place. Wrap the panelGrid in a panelGroup:
<h:panelGroup id="container">
and update that:
<p:menuitem value="khraaaaaaaaa" actionListener="#{accounts.buttonUser()}" update=":container">

p:dialog does not set properties to Entity

I have the following p:datatable that hold two buttons that call the View and the Add dialogs.
The problem is with the Add dialog, that does not seem to be setting properties to any of the Entity objects.
When I put a break on the save() method inside ChildrenController.java all values a 'null'.
I am using:
PrimeFaces 5.1 |
Mojarra 2.2.7 |
Glassfish 4.1 |
ChildrenDataTable.xhtml
<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">
<h:form id="form1">
<p:dataTable var="child" value="#{childrenController.children}"
scrollable="true"
scrollHeight="500">
<p:column>
<f:facet name="header">First Name</f:facet>
<h:outputText value="#{child.firstName}" />
</p:column>
<p:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{child.lastName}" />
</p:column>
<p:column>
<f:facet name="header">Parent Name</f:facet>
<h:outputText value="#{child.parent.firstName}" />
</p:column>
<p:column>
<f:facet name="header">Parent Last Name</f:facet>
<h:outputText value="#{child.parent.lastName}" />
</p:column>
<p:column style="width:32px;text-align: center">
<p:commandButton update=":mainForm:form1:childDetail"
oncomplete="PF('childDialog').show()"
process="#this"
icon="ui-icon-search"
title="View">
<f:setPropertyActionListener value="#{child}"
target="#{childrenController.selectedChild}" />
</p:commandButton>
</p:column>
<p:column style="width:32px;text-align: center">
<p:commandButton onclick="PF('childAddDialog').show()"
icon="ui-icon-person"
title="Add">
</p:commandButton>
</p:column>
</p:dataTable>
<!-- Dialog for the View button-->
<p:dialog header="Child Info"
widgetVar="childDialog"
modal="false"
showEffect="fade"
hideEffect="fade"
resizable="false">
<p:outputPanel id="childDetail" style="text-align:center;">
<p:panelGrid columns="2"
rendered="#{not empty childrenController.selectedChild}"
columnClasses="label,value">
<h:outputText value="First Name:" />
<h:outputText value="#{childrenController.selectedChild.firstName}" />
<h:outputText value="Last Name:" />
<h:outputText value="#{childrenController.selectedChild.lastName}" />
<h:outputText value="Birth Date:" />
<h:outputText value="#{childrenController.selectedChild.dateOfBirth}"/>
<h:outputText value="Medical Info:" />
<h:outputText value="#{childrenController.selectedChild.medicalInfo}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<!--Dialog for the Add button-->
<p:dialog header="Register Child"
widgetVar="childAddDialog"
modal="false"
showEffect="fade"
hideEffect="fade"
resizable="false">
<p:outputPanel id="childRegister" style="text-align:center;">
<p:panelGrid columns="2" >
<f:facet name="header">
Child info
</f:facet>
<h:outputText value="First Name:"/>
<h:inputText value="#{childrenController.child.firstName}"
required="true"/>
<h:outputText value="Last Name:"/>
<h:inputText value="#{childrenController.child.lastName}"
required="true"/>
<h:outputText value="Birth Date:"/>
<h:inputText value="#{childrenController.child.dateOfBirth}"
required="true"/>
<h:outputText value="Medical Info:"/>
<p:inputTextarea value="#{childrenController.child.medicalInfo}"
rows="5" cols="30" counter="display" maxlength="128"
counterTemplate="{0} characters remaining." autoResize="false"/>
<h:outputText id="display" />
</p:panelGrid>
<p:panelGrid columns="2" >
<f:facet name="header">
Parent info
</f:facet>
<h:outputText value="First Name:"/>
<h:inputText value="#{childrenController.parent.firstName}"
required="true"/>
<h:outputText value="Last Name:"/>
<h:inputText value="#{childrenController.parent.lastName}"
required="true"/>
<h:outputText value="Username:"/>
<h:inputText value="#{childrenController.user.username}"
required="true"/>
<h:outputText value="Password1:"/>
<p:password id="pwd1" value="#{childrenController.password1}"
match="pwd2"
required="true"/>
<h:outputText value="Password2:"/>
<p:password id="pwd2" value="#{childrenController.user.password}"
required="true"/>
<p:commandButton actionListener="#{childrenController.save()}"
value="Save"
process="#this"
oncomplete="childAddDialog.hide()">
</p:commandButton>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:composition>
ChildrenController.java
#Named
#SessionScoped
public class ChildrenController implements Serializable{
// This final string will be used to set the loginn role to parent
private static final String parentRole = "parent";
private String password1;
#EJB
private ChildEJB childEJB;
private Child currentChild;
private Child child = new Child();
#EJB
private ParentEJB parentEJB;
private Parent parent = new Parent();
#EJB
private RoleEJB roleEJB;
private Role role = new Role(parentRole);
#EJB
private UserEJB userEJB;
private User user = new User();
public Child getCurrentChild() {
return currentChild;
}
public void setCurrentChild(Child currentChild) {
this.currentChild = currentChild;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Child getSelectedChild() {
return selectedChild;
}
public void setSelectedChild(Child selectedChild) {
this.selectedChild = selectedChild;
}
private Child selectedChild;
public List<Child> getChildren() {
return childEJB.findAll();
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public void save(){
// Map the parent to the child and vice verca
parent.addChild(child);
child.setParent(parent);
// Persist the Parent
parent = parentEJB.addNew(parent);
// Persist the Child
child = childEJB.addNew(child);
// This will set the username for the parent role
role.setUsername(user.getUsername());
// This will set the role for the new username
user.setRole(role);
// This will map that the login belongs to a Parent
user.setParent(parent);
// Persist the new User
user = userEJB.addNew(user);
}
}
Stack Trace
Warning: A system exception occurred during an invocation on EJB ParentEJB, method: public entity.Parent EJB.ParentEJB.addNew(entity.Parent)
Warning: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy250.addNew(Unknown Source)
at EJB.__EJB31_Generated__ParentEJB__Intf____Bean__.addNew(Unknown Source)
at mb.ChildrenController.save(ChildrenController.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [entity.Parent] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=lastName, rootBeanClass=class entity.Parent, messageTemplate='{javax.validation.constraints.NotNull.message}'}
ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=firstName, rootBeanClass=class entity.Parent, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:160)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:95)
at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:202)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:91)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:191)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:807)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:780)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
at EJB.ParentEJB.addNew(ParentEJB.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor166.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor168.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 54 more
You didn't process your components in your question's code. What you did there to fix the problem in your own answer is including your form in the list of UIComponents to process. That means that JSF will not look at all your input components in your form and that's why it will not retrieve any values you entered in those fields to set them in your backing bean.
To get a better understanding of what process means, you may look at this question.
Solved the problem by putting the p:commandButton inside the p:panelGrid of the dialog which makes absolutely no sense to me whatsovever ! Anyway here is how the dialog looks like:
<h:form id="formName">
<p:dialog>
<p:panelGrid>
<p:commandButton process="#this :formName" ajax="false" actionListener="#{bean.method()}"/>
</p:panelGrid>
</p:dialog>
</h:form>
EDIT: edited code to be more readable

Dataexporter returns empty rows after filtering

I have a datatable in my xhtml view with filtering enabled. Additionally, there's the Primefaces export (for Excel) function in the context menu. When I use this function without filtering the datatable it works fine, but when I filter first and den export the data I get a file with empty rows.
This is my code:
<p:panel header="#{msg['prs.list']}">
<p:contextMenu for="persons">
<p:menuitem value="#{msg['com.view']}" icon="#{msg['icon.view']}"
action="#{personBean.redirectToEditPerson}"/>
<p:menuitem value="#{msg['student.new']}" icon="#{msg['icon.new']}"
action="#{personBean.redirectToNewStudent}"/>
<p:menuitem value="#{msg['prs.new']}" icon="#{msg['icon.new']}"
url="edit.xhtml"/>
<p:menuitem value="#{msg['report.export.excel']}" ajax="false" icon="#{msg['icon.export']}">
<p:dataExporter type="xls" target="persons" fileName="export" />
</p:menuitem>
</p:contextMenu>
<p:dataTable id="persons" var="person" value="#{personBean.personList}"
rowKey="#{person.id}" selection="#{personBean.selectedPerson}" selectionMode="single"
emptyMessage="#{msg['com.noEntries']}" paginator="true" rows="15">
<p:column headerText="Id">
<h:outputText value="#{person.id}"/>
</p:column>
<p:column headerText="#{msg['prs.name']}" filterBy="name" filterMatchMode="contains">
<h:outputText value="#{person.name}"/>
</p:column>
<p:column headerText="#{msg['prs.surname']}" filterBy="surname" filterMatchMode="contains">
<h:outputText value="#{person.surname}"/>
</p:column>
<p:column headerText="#{msg['prs.email']}" filterBy="email" filterMatchMode="contains">
<h:outputText value="#{person.email}"/>
</p:column>
</p:dataTable>
<f:facet name="footer">
<p:button value="#{msg['prs.new']}" icon="#{msg['icon.new']}"
outcome="edit"/>
</f:facet>
</p:panel>
I'm using Primefaces 4, JSF 2 and Java 7 on Wildfly 8
Solved. I found a warning in my log regarding the filteredValue property of the datatable.
[0m[33m17:26:45,701 WARNING [org.primefaces.component.datatable.DataTable] (default task-4) DataTable form:persons has filtering enabled but no filteredValue model reference is defined, for backward compatibility falling back to page viewstate method to keep filteredValue. It is highly suggested to use filtering with a filteredValue model reference as viewstate method is deprecated and will be removed in future.
I therefore added this property which then solved the problem
<p:dataTable id="persons" var="person" value="#{personBean.personList}"
rowKey="#{person.id}" selection="#{personBean.selectedPerson}"
selectionMode="single" emptyMessage="#{msg['com.noEntries']}"
paginator="true" rows="15" filteredValue="#{personBean.filtered}">
And added the following property in PersonBean as well
private List<PersonEntity> filtered;
public List<PersonEntity> getFiltered() { return filtered; }
public void setFiltered(List<PersonEntity> filtered) { this.filtered = filtered; }

Evaluate the Selected Datatable row in spring web flow

Anyone know how to pass the selected row values.I need to update the data table when the when the Approve button is pressed.
mainpage.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition 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"
template="/WEB-INF/layouts/standard.xhtml">
<ui:define name="notes">
<h:form>
<p:commandButton value="Sick Leave" action="sickleave" id="sickleave"/>
<p:commandButton value="Paid off Leave" action="paidleave" id="paidleave"/>
</h:form>
</ui:define>
<ui:define name="content">
<h2>Approve Leave</h2>
<h:form>
<h:dataTable value="#{employeeleave}" var="e"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
columnClasses="order-table-odd-column,order-table-even-column"
>
<h:column>
<f:facet name="header">
No.
</f:facet>
#{e.employeeId}
</h:column>
<h:column>
<f:facet name="header">
Start Date
</f:facet>
#{e.startDate}
</h:column>
<h:column>
<f:facet name="header">
End Date
</f:facet>
#{e.endDate}
</h:column>
<h:column>
<f:facet name="header">
Reason
</f:facet>
#{e.reason}
</h:column>
<h:column>
<f:facet name="header">
Status
</f:facet>
<h:selectOneMenu id="approveleavetype" value="#{employeeLeave.status}">
<f:selectItems value="#{referenceData.approveLeave}"/>
</h:selectOneMenu>
</h:column>
<p:column>
<f:facet name="header">Action</f:facet>
<p:commandButton value="Approve Leave" action="approveleave" id="approveleave" style="margin-left:250px;">
<f:setPropertyActionListener value="#{e}" target="#{employeeleave.selected}" /></p:commandButton>
</p:column>
</h:dataTable>
</h:form>
<h2>Please Apply for Leave Here</h2>
<h:form>
<h:panelGrid columns="3" id="leaveform" >
<h:outputLabel for="beds">Select the Type of the Leave</h:outputLabel>
<h:selectOneMenu id="leavetype" value="#{employeeLeave.type}">
<f:selectItems value="#{referenceData.leaveType}"/>
</h:selectOneMenu>
<div>
<h:outputLabel for="startDate">Start Date</h:outputLabel>
<p:calendar id="startDate" label="Start Date"
value="#{employeeLeave.startDate}" pattern="MM-dd-yyyy" timeZone="EST" required="true" />
</div>
<div>
<h:outputLabel for="endDate">End Date</h:outputLabel>
<p:calendar id="endDate" label="End Date"
value="#{employeeLeave.endDate}" pattern="MM-dd-yyyy" timeZone="EST" required="true" />
</div>
<div>
<h:outputLabel for="checkoutDate">Reason</h:outputLabel>
<h:inputTextarea id="reason" value="#{employeeLeave.reason}"
required="true"
label="reason" >
</h:inputTextarea>
</div>
</h:panelGrid>
<center><p:commandButton value="Apply Leave" action="applyleave" id="applyleave" style="margin-left:250px;"/></center>
</h:form>
<br></br>
<center> <h1 style="font-size: 16px;font-weight:bold;margin-top:100px;">Leave Application</h1></center>
</ui:define>
</ui:composition>
main-flow.xml
<action-state id="ApproveLeave">
<!-- <set name="viewScope.employeeleave" value="employeeleave.selected" /> -->
<evaluate expression="leaveBo.approveLeave(employeeLeave.selectedRow)"></evaluate>
<transition to="managerpage"></transition>
</action-state>
Here am trying to get the selected row and I try to evaluate it.
But I am getting the following error.
javax.el.ELException: /WEB-INF/flows/main/managerpage.xhtml #70,86 target="#{employeeleave.selected}": Cannot convert selected of type class java.lang.String to class java.lang.Integer
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:103)
at com.sun.faces.facelets.tag.jsf.core.SetPropertyActionListenerHandler$SetPropertyListener.processAction(SetPropertyActionListenerHandler.java:210)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIData.broadcast(UIData.java:1093)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at org.springframework.faces.webflow.FlowLifecycle.invokePhase(FlowLifecycle.java:127)
at org.springframework.faces.webflow.FlowLifecycle.execute(FlowLifecycle.java:70)
at org.springframework.faces.webflow.JsfView.processUserEvent(JsfView.java:120)
at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:226)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:196)
at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:258)
at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:183)
at org.springframework.faces.webflow.JsfFlowHandlerAdapter.handle(JsfFlowHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
As the error log says:
The method arguments for the setter setSelected need to be of type String in your case, like this:
public class Employeeleave {
public void setSelected(String newValue){
selected = newValue;
}
}

Primefaces DataTable with SubTable and multiple selection

I would like to have a table of bookings grouped by clients. From this table the user shall be able to select multiple booking for billing. So I am trying to use a SubTable for the grouping, however, I am unsure how to realize to selection functionality. Apparently the subtable doesn't allow the selection attribute and if I set the selection attribute on the parent DataTable I don't know how to choose the rowKey.
That is my try:
<p:dataTable style="border: 0px;" value='#{clientController.allClients}'
var='client' rowKey="#{item.id}" selectionMode="multiple"
selection="#{bookingController.bookingsToBill}">
<p:subTable value='#{client.billableBookings}' var='item'>
<f:facet name="header">
<h:outputText style="font-weight:bold;" value="#{client.name}" />
</f:facet>
<p:column>
<f:facet name="header">
<h:outputText value="Booking"/>
</f:facet>
<h:outputText value="#{item.title}"/>
</p:column>
</p:subTable>
</p:dataTable>
Well, this results in the following error when submitting the selection:
java.lang.NullPointerException
java.lang.reflect.Array.newArray(Native Method)
java.lang.reflect.Array.newInstance(Array.java:52)
org.primefaces.component.datatable.DataHelper.decodeMultipleSelection(DataHelper.java:238)
org.primefaces.component.datatable.DataHelper.decodeSelection(DataHelper.java:224)
org.primefaces.component.datatable.DataTableRenderer.decode(DataTableRenderer.java:64)
javax.faces.component.UIComponentBase.decode(UIComponentBase.java:787)
javax.faces.component.UIData.processDecodes(UIData.java:1162)
org.primefaces.component.datatable.DataTable.processDecodes(DataTable.java:531)
javax.faces.component.UIForm.processDecodes(UIForm.java:225)
javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1176)
javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1176)
javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:933)
com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
Is multiple selection supported for DataTables with SubTables? If so, how to do it right? If not, which way would you suggest to achieve a similar result?
I'm using: Primefaces 3.1.1 - Mojarra JSF 2.1 - Tomcat 6.0.14
Have you analyzed this solution described in Primefaces' showcase?
It basically boils down to this:
<p:dataTable style="border: 0px;" value='#{clientController.allClients}'
var='client' rowKey="#{item.id}"
selection="#{bookingController.bookingsToBill}" >
<p:subTable value='#{client.billableBookings}' var='item'>
<f:facet name="header">
<h:outputText style="font-weight:bold;" value="#{client.name}" />
</f:facet>
<p:column selectionMode="multiple" />
<p:column>
<f:facet name="header">
<h:outputText value="Booking"/>
</f:facet>
<h:outputText value="#{item.title}"/>
</p:column>
</p:subTable>
Or try with the ajax event listener, bound to your BookingController:
<p:ajax event="rowSelect" listener="#{bookingController.rowSelected}" />
<p:ajax event="rowUnselect" listener="#{bookingController.rowUnselected}" />
And you update your own list of selected items in these two functions:
List<Booking> selectedBookings = new ArrayList<>();
...
public void rowSelected(SelectEvent event) {
Booking book = (Booking) event.getObject();
selectedBookings.add(book);
}
public void rowUnselected(UnselectEvent event) {
Booking book = (Booking) event.getObject();
selectedBookings.remove(book);
}
It's not very elegant, but it brought my logic to work after getting this rather obscure NullPointerException.

Resources