commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
Asked Answered
D

13

369

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?

Douse answered 22/1, 2010 at 16:18 Comment(0)
B
722

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>jakarta.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

  1. 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.

  2. 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?.

  3. 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.

  4. 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 JSF dataTable.

  5. 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).

  6. 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

  7. 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.

  8. 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.

  9. If you're using Ajax, and the submitted values end up being null or the command is not invoked, 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.

  10. 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?

  11. 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.

  12. 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.

  13. Make sure that the ActionEvent argument of actionListener is an jakarta.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.

  14. 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().

  15. 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.

  16. 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

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).

js console

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">.

network monitor

(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.

debug server

Brilliantine answered 22/1, 2010 at 20:13 Comment(13)
your 2nd point made me think -- for a long while. I just found out that an f:view tag in my main file was the cause of most of my problems. And probably because it renders a form, right?Grapeshot
@pauloguedes I cant find anything that states that f:view renders a form. My understanding is that it is just a container. In my experience, f:view does not render any elements.Distinct
@balusc A little clarification on point 4, if the commandLink is not in the dataTable itself, does it still matter?Distinct
thanks, the point is the point:Putting the bean in the view scope and/or making sure that you load the data model in (post)constructor of the bean (and thus not in the getter method!) should fix it.Transitive
For me the issue came when disabled attribute was used.Celinacelinda
additional information for point 8 : we also had this issue but the strange thing was that on glassfish it was working fine and after deploying the same war to tomcat it was not working (no error messages) so it seems that glassfish and tomcat are handling this a little bit different (having the multipart set but no filter which is handling it correctly, removing the enctype solved the issue for us)Gnathion
@sMaN: it is not exhaustive. Plain wrong method signatures not in line with the EL are at least not in this listLabrum
@Kukeltje: that would have thrown an EL exception (already covered by 1st paragraph in the answer)Brilliantine
Note that (5) includes the pushbutton itself. If the rendering of the pushbutton that you push becomes false as a result of pushing the button, the button doesn't get pushed.Bernardobernarr
@BalusC: What about lazy datatable + requestscoped? I checked all the points that you have listed, I believe that my problem is in the point 4. I'm using RequestScoped, I load my LazyDataModel in the PostConstruct (but because is RequestScoped, the objects change, same value but different objects).Everything works.. paginator, sort, filters but not the commandButton. How can I get the commandButton working in this scenario? Could you help me?Interphone
#4 is hard to understand at first. I realized I was actually concerned only after I found out the problem by myself and came back to comment. I think that a seperate point 4-bis. like "if you are displaying a list of content loaded from a request bean, beware that ajax calls imply separate requests" would help a lot of people understand they are actually concerned (as I was).Firebird
thanks a lot @BalusC, i was struggling this problem for whole day: "input value not set/updated". now i can see that the cause was cause number one (plain HTML form).Gimp
I've been through every potential problem and not gotten anywhere. I have debugged on UICommand as suggested but code doesn't reach it (for my problem page, does for others). I see the request and response coming back and my filter being hit (not blocking it), so I've no idea where it's going AWOLEasterling
T
56

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!

Trackless answered 8/11, 2010 at 22:25 Comment(2)
Ok, that was not entirely clear to me. I hope my answer is helpful anyway, since in my case at least I was not dealing explicitly with UICommand/UIData. The "solution" was promoting a backing bean from request-scope to session scope ...Trackless
I second Jens comment...setting my RequestScoped bean to be SessionScoped made the difference on my dataTable - thanksEscaut
G
32

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!)

Glassine answered 3/1, 2013 at 18:51 Comment(5)
The default for PrimeFaces process is @form. So if the action isn't invoked this way, but does when using @this, then most likely point 3 of my answer applies.Brilliantine
This can't be. I had a p:commandButton that didn't invoke the actionListener method until I added process="@this". Furthermore, the PrimeFaces User's Guide explicitly lists the defaults I mentioned in section 3.18 and 3.19. It is here: primefaces.googlecode.com/files/primefaces_users_guide_3_4.pdf ... maybe the defaults were changed?Glassine
It's likely an error in documentation. Remove process="@this" and add <p:messages autoUpdate="true"> (or just read server log for queued but undisplayed messages) and you'll see that actually a conversion/validation error has occurred.Brilliantine
Why did you remove this question stackoverflow.com/questions/60673695/…Labrum
I thought it might not provide much value now... I undeleted it.Glassine
B
12

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!

Beall answered 3/1, 2015 at 19:15 Comment(4)
this was my main problem in one of our pages, none of the points in the accepted answer brought us closer, where did you find this information?Nephron
Well, i have had that problem many times, and i did research and find that p:commandButton has the several values of type attribute, and button is one that concerns everything about client side. It's a bit hard to find this in Primefaces doc, but here is one link: developer.am/primefaces/…Beall
Your submit hint solved my problem I have been facing for days. Thanks a lot your post!Cohn
Thank you, it's my pleasure. I deliberately put this answer because many of us had such a problem. I had lost a few days too until realized what is about.Beall
B
5

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.

Brachycephalic answered 23/2, 2013 at 10:55 Comment(3)
It should have resulted in a rather self-explaining PropertyNotWritableException. If you didn't see it, perhaps you fired an ajax request without a proper ajax exception handler, but you should see it in server logs.Brilliantine
It didn't show that exception until I made p:commandButton's ajax="false".Brachycephalic
THANK GOD you saved my lifeRuler
C
4

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.

Cown answered 13/10, 2015 at 18:23 Comment(0)
D
3

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.

Detrition answered 11/4, 2017 at 16:11 Comment(0)
I
2

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.

Imprisonment answered 2/5, 2017 at 19:6 Comment(0)
T
0

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.

Timepleaser answered 17/8, 2017 at 22:22 Comment(0)
R
-1

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>
Reachmedown answered 8/2, 2019 at 19:38 Comment(1)
That is #1 in the >600 upvoted answer. No need to write it as a separate answer.Labrum
C
-1

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.

Clementius answered 9/12, 2019 at 7:5 Comment(1)
This solves what problem? What did you change to solve it? Why did your change fixed your problem? Are you sure it is not mentioned in the top answer?Ontiveros
V
-1

The solution that worked for me was putting the <p:commandButton> inside the form or inside where the form data is, say for intance in <p:outputPanel>.

Viperine answered 17/3, 2023 at 20:50 Comment(1)
That's cause 1 of the top answer.Ontiveros
C
-2
<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>
Chary answered 12/7, 2019 at 11:51 Comment(10)
Sorry, but this is in my humble opinion totally not true. You effectively state that 2 dialogs need to be in their own form to work. You with 99% certainty had a different problem that you solved and for which you now think this is the solution...Labrum
This is included page. Perhaps this may cause problem. You should test it before vote.Unnumbered
No, you should have created a minimal reproducible example before posting (and only then I can test)... And yes includes can result in problems with dialogs and forms, but then the problem is still not what you seem to want to solve here. You first example is perfectly fine and the second is with 100% certainty not a solution of a non-existent problemLabrum
Anyway. My application working fine. I think it's not important where dialogs box in the form. I have to create a second form to solve another problem.Unnumbered
Your application might be working, but that is not clear/visible from an original problem and your 'solution. Besides, you say _"I think it's not important where dialogs box in the form. "_But in your answer it seems to be important where they are. A contradiction that supports my statement. Sorry, but your answer is plain out wrong... (there is another downvote on it already)Labrum
I have to create second form to solve this problem. javax.el.PropertyNotFoundException: Target UnreachableUnnumbered
Then you have a completely different problem then what this question is about. The problem is not visible in your original code. Create a new question with a minimal reproducible example and we'll see if we can tell you why the change you made solved you original problem. But most likely it will be closed as duplicate of existing questions, but you'll at least learn what caused your problemLabrum
Sorry, my English not very well. Perhaps i could not explain what is The problem.Unnumbered
Also i havent got a problem now, just want to help users to solve same problem.Unnumbered
The english is not the problem, The code speaks for itself here. And the error you had which you eventually posted in a comment is the confirmation that your answer is in no way an answer to the question.Labrum

© 2022 - 2024 — McMap. All rights reserved.