JSF 2.0 h:datatable not using supplied id attribute - jsf-2

I'm observing the following behavior within a JSF 2 page (Mojarra 2.1.18 / RedHat EAP 6.1, if that's useful). I've got a form wrapping a data table, and I'm supplying an ID attribute value for both the form and the table. When I view the resulting html source file, I see that the table ID is set to an auto-generated value and the form ID attribute is not prepended to the auto-generated table ID. That is:
This set of tags:
<h:form id="form4">
<h:datatable id="notices" ...>
...
</h:datatable>
</h:form>
Yields the following html:
<form id="form4" ...>
<table id="j_itd68"> //i.e. id != "notices"
...
</table>
</form>
There are more elements in the JSF xhtml file preceding the h:form/h:datatable, but I've intentionally excluded them here (hoping that someone might recognize this symptom without additional clutter). Things go wrong for me when I attempt to include some PrimeFaces p:commandbutton instances within the table. They don't get named properly (i.e. they don't include the enclosing form ID in the generated ID), and this causes a "component not found for ID" servlet error. The same improper naming occurs if I replace the p:commandbutton instances with h:commandbutton instances (so I don't believe this is a PrimeFaces issue). This behavior seems like the result of a malformed JSF page, but I haven't found anything yet (a NetBeans XML check on the JSF xhtml file returns a successful result). Any help is appreciated.
Best regards,
-Andy

Related

JSF Primefaces: ActionListener on MenuItem is not called [duplicate]

Sometimes, when using <h:commandLink>, <h:commandButton> or <f:ajax>, the action, actionListener or listener method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted UIInput values.
What are the possible causes and solutions for this?
Introduction
Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
Possible causes
UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a #ViewScoped bean or making sure that you're properly preinitializing the condition in #PostConstruct of a #RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to #Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also #SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.
Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().
Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
Debugging hints
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="#form" render="#form">.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:
The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.
So if the underlying data-source is request scoped, the h:commandLink does not work!
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="#this" to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both #form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="#this" and render="#none" respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
I would mention one more thing that concerns Primefaces's p:commandButton!
When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".
Hope this will help someone!
Got stuck with this issue myself and found one more cause for this problem.
If you don't have setter methods in your backing bean for the properties used in your *.xhtml , then the action is simply not invoked.
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope. The data backing the table itself was in a sort of ViewScope (in reality, temporarily in SessionScope).
If the row display was increased via the control which value was also bound to the datatable's rows attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
I had lots of fun debugging an issue where a <h:commandLink>'s action in richfaces datatable refused to fire. The table used to work at some point but stopped for no apparent reason. I left no stone unturned, only to find out that my rich:datatable was using the wrong rowKeyConverter which returned nulls that richfaces happily used as row keys. This prevented my <h:commandLink> action from getting called.
One more possibility: if the symptom is that the first invocation works, but subsequent ones do not, you may be using PrimeFaces 3.x with JSF 2.2, as detailed here: No ViewState is sent.
I fixed my problem with placing the:
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
In:
<h:form>
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
</h:form>
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from #ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
</p:dialog>
</h:form>
<h:form id="form2">
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
</p:dialog>
</h:form>
</ui:composition>
To solve;
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!-- Working -->
</p:dialog>
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Working -->
</p:dialog>
</h:form>
<h:form id="form2">
<!-- .......... -->
</h:form>
</ui:composition>

validate Date Ajax and KeyUp in Calendar JSF [duplicate]

Sometimes, when using <h:commandLink>, <h:commandButton> or <f:ajax>, the action, actionListener or listener method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted UIInput values.
What are the possible causes and solutions for this?
Introduction
Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
Possible causes
UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a #ViewScoped bean or making sure that you're properly preinitializing the condition in #PostConstruct of a #RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to #Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also #SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.
Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().
Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
Debugging hints
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="#form" render="#form">.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:
The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.
So if the underlying data-source is request scoped, the h:commandLink does not work!
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="#this" to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both #form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="#this" and render="#none" respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
I would mention one more thing that concerns Primefaces's p:commandButton!
When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".
Hope this will help someone!
Got stuck with this issue myself and found one more cause for this problem.
If you don't have setter methods in your backing bean for the properties used in your *.xhtml , then the action is simply not invoked.
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope. The data backing the table itself was in a sort of ViewScope (in reality, temporarily in SessionScope).
If the row display was increased via the control which value was also bound to the datatable's rows attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
I had lots of fun debugging an issue where a <h:commandLink>'s action in richfaces datatable refused to fire. The table used to work at some point but stopped for no apparent reason. I left no stone unturned, only to find out that my rich:datatable was using the wrong rowKeyConverter which returned nulls that richfaces happily used as row keys. This prevented my <h:commandLink> action from getting called.
One more possibility: if the symptom is that the first invocation works, but subsequent ones do not, you may be using PrimeFaces 3.x with JSF 2.2, as detailed here: No ViewState is sent.
I fixed my problem with placing the:
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
In:
<h:form>
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
</h:form>
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from #ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
</p:dialog>
</h:form>
<h:form id="form2">
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
</p:dialog>
</h:form>
</ui:composition>
To solve;
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!-- Working -->
</p:dialog>
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Working -->
</p:dialog>
</h:form>
<h:form id="form2">
<!-- .......... -->
</h:form>
</ui:composition>

PrimeFaces dataTable rowEditor not working for list object [duplicate]

Sometimes, when using <h:commandLink>, <h:commandButton> or <f:ajax>, the action, actionListener or listener method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted UIInput values.
What are the possible causes and solutions for this?
Introduction
Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
Possible causes
UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in #PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a #ViewScoped bean or making sure that you're properly preinitializing the condition in #PostConstruct of a #RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to #Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also #SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.
Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().
Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
Debugging hints
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="#form" render="#form">.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:
The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.
So if the underlying data-source is request scoped, the h:commandLink does not work!
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="#this" to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both #form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="#this" and render="#none" respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
I would mention one more thing that concerns Primefaces's p:commandButton!
When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".
Hope this will help someone!
Got stuck with this issue myself and found one more cause for this problem.
If you don't have setter methods in your backing bean for the properties used in your *.xhtml , then the action is simply not invoked.
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope. The data backing the table itself was in a sort of ViewScope (in reality, temporarily in SessionScope).
If the row display was increased via the control which value was also bound to the datatable's rows attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">.
In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.
Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.
Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).
Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.
What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.
I had lots of fun debugging an issue where a <h:commandLink>'s action in richfaces datatable refused to fire. The table used to work at some point but stopped for no apparent reason. I left no stone unturned, only to find out that my rich:datatable was using the wrong rowKeyConverter which returned nulls that richfaces happily used as row keys. This prevented my <h:commandLink> action from getting called.
One more possibility: if the symptom is that the first invocation works, but subsequent ones do not, you may be using PrimeFaces 3.x with JSF 2.2, as detailed here: No ViewState is sent.
I fixed my problem with placing the:
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
In:
<h:form>
<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
</h:form>
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from #ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
</p:dialog>
</h:form>
<h:form id="form2">
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
</p:dialog>
</h:form>
</ui:composition>
To solve;
<ui:composition>
<h:form id="form1">
<p:dialog id="dialog1">
<p:commandButton value="Save" action="#{bean.method1}" /> <!-- Working -->
</p:dialog>
<p:dialog id="dialog2">
<p:commandButton value="Save" action="#{bean.method2}" /> <!--Working -->
</p:dialog>
</h:form>
<h:form id="form2">
<!-- .......... -->
</h:form>
</ui:composition>

Submitted value seems to be ignored

I have a selectOneMenu which is suposed to be processed when its value is changed.
The xhtml is quite generic so it's not very clear. Here it is:
<p:selectOneMenu
id="#{myId}"
value="#{obj[attr]}"
panelStyle="font-size: 10px;"
disabled="#{cc.attrs.grid.readonly}"
style="margin-top: 3px; width:79px;"
styleClass="#{change.getChangeClass(cc.attrs.grid)} toUpdate">
<f:selectItems value="#{cc.attrs.grid.valuesString}" var="elem" itemValue="#{elem}" itemLabel="#{elem}"/>
<f:validator validatorId="GenericValidator" />
<p:ajax
process="#this"
listener="#{rules.process()}"
update="#this"/>
Here is a part of the generated html which is clearer:
behaviors:{change:function(event){
PrimeFaces.ab({
source:'masterCenter:fuel3Content:j_idt621:fuel_codeCat',
event:'valueChange',
process:'masterCenter:fuel3Content:j_idt621:fuel_codeCat',
update:'masterCenter:fuel3Content:j_idt621:fuel_codeCat'}, arguments[1]);}
}
When I select a value, it gets posted (I can see with chrome tools that it is in the form data being posted).
But my validation method (GenericValidator.validate()) is not called.
When I submit the whole form, the validation method is called, but it indicates that the value of the combo is null.
I have the feeling that this value is not set as it should during the apply request values phase.
But this behaviour depends on the context:
This selectOneMenu is in a panel. The first time I open this panel (loaded with ajax), it works fine. I can change the value of the selectOneMenu and my validation method is called with the value that I've chosen.
Now when I open this panel again, the selectOneMenu doesn't work any more. However the generated html is exactly the same.
I also have the same behaviour with a p:inputTextarea in this form.
I'm using primefaces 3.4.1 with Mojarra 2.1.10. It looks to me like a primefaces/mojarra bug, but I haven't found notes of this problem.
in value expression value="#{obj[attr]}", why you are using a map? And how you set attr value? can you give more details?
In versions prior to jsf 2.0 validaton is ignored for empty and null fields. In jsf 2.0 if your jsf runs in environment where bean validation is supported then your empty or null fields are validated by default.
If you are using non j2ee 6 compliant servers like tomcat 6 or jetty in which bean validation is not supported then validation won't happen for null or empty fields.
If you want to enforce validation on empty fields you can use either required="true" or
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
Hope this helps. Leave a comment if you need further help

wrong ids when render h:panelGroup's inside c:forEach

I have page where I render some h:panelGroup panels. Those panels are realized as plugins registered in a plugin registry on startup.
Part of the plugins api is a custom jsf component where I get the registered plugins for extension point and include their facelet templates by path:
<c:forEach items="#{pluginRegistry.getPlugins(point)}" var="extension">
<ui:include src="#{extension.path}" />
</c:forEach>
The page where I include the panels looks like:
<h:panelGrid id="dashboard" columns="3">
<cmf:insertPageFragments point="dashboardExtensionPoint" />
</h:panelGrid>
For every panel there are facelet templates like the one below:
<rich:panel id="caseDetailsPanel" header="panel label">
<!-- panel content -->
</rich:panel>
Now, the problem is that the very first panel in the list returned by the pluginsRegistry is rendered in the page with the provided id like formId:caseDetailsPanel for example. The rest of them have generated ids like formId:j_idt223 !!! Obviously if I want to rerender some of the panels, I can't do that.
That happens when environment is jboss AS 7.1 with JSF 2.1, richfaces 4.2.3.Final.
When deployed on jboss-eap-6.1 everything looks fine but for now I can't use this jboss version.
Any suggestions on how to workaround this issue?
There can not be multiple JSF components with the same ID. Each JSF component must have an unique ID. When dynamically creating JSF components using JSTL, you need to manually assign and ensure an unique ID, otherwise JSF will discard the provided ID and autogenerate an unique ID.
There are several ways to achieve this, depending on the concrete functional requirement and the existing code.
Use use the iteration index of <c:forEach>.
<c:forEach ... varStatus="loop">
...
<rich:panel id="caseDetailsPanel_#{loop.index}" ...>
This will generate caseDetailsPanel_0, caseDetailsPanel_1, etc depending on the current iteration index.
Use the unique identifier of the currently iterated item. It isn't clear based on the information provided so far if you have any, so here's just a fictive example assuming that the class behind #{extension} has an id property representing the technical DB identifier.
<c:forEach ... var="extension">
...
<rich:panel id="caseDetailsPanel_#{extension.id}" ...>
Wrap #1 or #2 if necessary in a <f:subview> with an unique identifier, so that you don't need to modify the includes.
<c:forEach ... varStatus="loop">
<f:subview id="panel_#{loop.index}">
<ui:include ... />
The <f:subview> creates a new NamingContainer around it, so you end up getting formId:panel_0:caseDetailsPanel, formId:panel_1:caseDetailsPanel and so on.
A completely different alternative would be to use <ui:repeat> instead of <c:forEach>. The <ui:repeat> does not run during view build time, but during view render time. This way there's physically only one <rich:panel id="caseDetailsPanel"> component in the component tree which is reused multiple times during generating HTML whereby JSF will take care of generating the right IDs with the <ui:repeat> index like so formId:repeatId:0:caseDetailsPanel. However, this in turn may cause trouble with <ui:include> as it also runs during view build time and thus can't get the #{extension} at hands.

Resources