CommandButton action is not invoked [duplicate] - button

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>

Related

How to update ContextBinding (Element Binding) automatically after the size of its child ListBinding (Aggregation Binding) has changed?

Note: In order to demonstrate the below issue, I've created an example in Plunker. In there, I'm using a mock server due to the flaw of the writable service from odata.org. Nevertheless, the issue is reproducible with a real server as well.
Currently, I'm binding a child collection to a list relative to an expanded single entity through a navigation property. Something like this:
<Page title="Products"
binding="{
path: 'odataModel>/BusinessPartnerSet(\'0100000000\')',
parameters: {
expand: 'ToProducts'
}
}"
>
<List items="{odataModel>ToProducts}">
<StandardListItem title="{odataModel>ProductName}" />
</List>
</Page>
Now, if I delete an item from the list, the ListBinding sends a batch request containing DELETE and GET. Here is a screenshot of the batchRequestSent event:
The deleted item is gone from the ListBinding and the list is updated as expected. If I have an additional list with the same bindings, then that additional list gets also updated because of the TwoWay data binding (like the Plunker example above). So far so good.
Problem
But the problem is: The parent ContextBinding (in this case, the element binding of the Page) is not updated. This can be seen if you call bindingContext.getProperty("ToProducts") and it will return a list of binding paths in which the ones of the already deleted items are still there. I guess this is because there was no GET request sent from the ContextBinding but from the ListBinding only.
My question
If the change took place in the child ListBinding (either through DELETE or CREATE), how can the parent ContextBinding get notified about the change and update itself without sending an additional request, so that bindingContext.getProperty("ToProducts").length returns always the correct length?
Or differently, when the change occurs, how can I prevent UI5 from sending a GET request from the child ListBinding and let it send the request from the parent ContextBinding instead, so that the change gets propagated to the child ListBinding afterwards automatically?
Is there any standard approach to solve this kind of problem in UI5?
PS: The same problem does not apply to JSON-based bindings. It seems to be OData only.
If someone encounters the same issue: it turned out to be a bug in UI5 which is fixed in 1.46.7+.
[FIX] ODataListBinding: Update expanded list array
If the fix is not available in your current release, one workaround would be to refresh the parent binding by calling parentControl.getElementBinding("modelName").refresh(false, "yourDeferredGroupId") so that the GET request can be sent together with the DELETE request in a single batch request.
Additionally, we can turn off refreshAfterChange (as krisho suggested) so that UI5 doesn't append yet other GET requests for corresponding ListBindings (relatively bound as well as absolutely bound ones). A disadvantage of this approach is that the absolutely bound ListBinding (which has the same content as the relatively bound one) has to be refreshed manually as well - if there is any.
To stop the framework from making the 'GET' call after Delete, you can use the property 'refreshAfterChange' on sap.ui.model.odata.v2.ODataModel, which can be set to 'false'.
After the success of 'Delete', you can 'refresh' the binding on the page, so that all bindings are consistent.

JSF Identify errors generated in process validations phase

I'm new to JSF and want to make modifications in existing code. While the code is working fine, I have a problem with an A4J (Rich faces) onchange event.
My tech stack related here is JSF1.2, RichFaces 3.3
The code snippet is as below:
<h:selectOneMenu required="#{order.required}"
id="modelCBFS" label="Model" value="#{order.modelDTO}" converter="ModelConverter">
<f:selectItem itemLabel="-Select-" itemValue =""/>
<f:selectItems value="#{order.modelDropDown}" />
<a:support ajaxSingle="false" limitToList="true"
reRender="elevationCBFS"
event="onchange"
action="#{order.modelChanged}"
onsubmit="onHourGlass()" oncomplete="offHourGlass()"/>
</h:selectOneMenu>
Now, when the above code is rendered on page, the ajax event is being fired, but the JSF page does not go thru 4th and 5th phases (Update Values and Invoke Application phases) ONLY for the first onchange event!
It works correctly for the subsequent requests though. Also, the onchange a4j events for every other component works fine.
When I researched on net, the solution to debug the issue was to use FacesContext and use the debug messages from it. But this is not configured in the current app.
Can someone help me with a solution for debugging the issue? or any possible root causes is appreciated.
I found out the problem! I was enabling and disabling fields based on a master method where in the rule was conflicting in the child for a particular field..
Nevertheless it is absurd on the way I approached this problem by trial and error method...
If anyone have any thoughts on what could have happened technically, please shed some light!

Which Seam component to use: <h:outputLink> or <h:commandLink>?

I'm very new to Seam and am just getting used to the different components available. I'm wondering which one I should use for this situation.
The answer to this question explains the difference between <h:outputLink> and <h:commandLink>, that <h:outputLink> produces just a basic HTML link tag with GET request and <h:commandLink> submits a POST via a click event.
I just want to attach a simple jQuery click event to a link. I don't want the link to redirect to anywhere or submit a form. I basically want the equivalent of href="#" (I understand that commandLink generates href="#" but it seems heavy-handed for a simple link with no form submission). But <h:outputLink> implicitly adds an href value unless I put value="#" (which seems hacky).
What component do I want to use here? I seem to be missing some very basic element.
(First: <h:outputLink> and <h:commandLink> are standard JSF components, not part of the Seam framework.) In this case, you can just use the standard HTML tag <a>, because you appear not to be using anything special to JSF.

Styles does not load if the navigation stays the same JSF page

I have a command button which i bind its action method.
<f:view >
<pm:page title="Title">
<pm:view id="viewId" swatch="c">
<p:outputPanel id="panelId">
<h:form id="formId">
<p:commandButton action="#{bean.actionMethod}" update="formId" value="Click" />
</h:form>
</p:outputPanel>
</pm:view>
</pm:page >
</f:view>
Inside action method. the navigation refers the same page. Some values are updated inside action method.
public String applyPeriod(String caller)
{
.....
retrun SAMEPAGE;
}
Every thing is ok. but the styles is not rendered. the page returns to the default styles.
Any idea how i can load the styles. I do not want to change URL by doing real refresh. i should managed it by ajax calls.
I trace the requests of the page. There is exactly no call for styles.
I use primefaces, primefaces mobile and it is a mobile page.
If you didn't use : behind your form's ID I believe the problem can be related to a relative component search, trying to finding the form based on a relative identifier. By using the different element's ID you're getting the expected behaviour, I pressume because they're correctly referenced in a relative way to the context of your <p:commandButton/>.
Try using either update="#form" or update=":formId". Also, as a side note, if you want to use full ajax and you won't be redirecting the user anywhere, your method should either be void or return null.
I really do not know the reason behind the scenes. However, i solved the issue by giving exact components ids to update attributes of commandButton.
<p:commandButton action="#{bean.actionMethod}" update="ListOfComponentIds" value="Click" />

Detecting value change in <h:selectOneMenu> inside a <tr:table>

There is a table like this:
<h:panelGroup rendered="#{ImportFromCSVFile.step2Visible}">
<div style="width: 100%; overflow: auto; max-height: 400px;">
<tr:table id="step2ColumnMappings" var="columnMappingEntry" rows="0" rowBandingInterval="1" value="#{ImportFromCSVFile.columnMappings}">
<tr:column>
<tr:outputLabel value="#{columnMappingEntry.columnIndex}"/>
</tr:column>
<tr:column>
<tr:outputLabel value="#{columnMappingEntry.columnValue}"/>
</tr:column>
<tr:column>
<h:selectOneMenu value="#{columnMappingEntry.columnType}" validator="#{ImportFromCSVFile.validateColumnType}" onchange="submit()" valueChangeListener="#{ImportFromCSVFile.columnMappingChanged}">
<f:selectItems value="#{ImportFromCSVFile.columnsToBeMapped}" />
</h:selectOneMenu>
</tr:column>
</tr:table>
</div>
</h:panelGroup>
which renders (properly) as a table with three columns: text in the first two and dropdowns in the last one. dropdowns are also properly initialized based on values in the model.
What I need to do is to be able to run some logic everytime a value in any of the dropdowns changes. I was thinking of using valueChangeListener on selectOneMenu, as you can see in the code, but it doesn't get called. The only thing that comes to mind right now is working with POST parameters when the form is submitted, which would not be optimal.
Do you know how I can get valueChangeListener to work in this context? JSF 1.2. I may be missing an obvious or known solution, but unfortunately I have very very little prior experience with JSF and do not work with it on a regular basis.
Thank you very much in advance!
xmlns:h="http://java.sun.com/jsf/html"
xmlns:tr="http://myfaces.apache.org/trinidad"
The easiest thing to do would be to use <tr:selectOneChoice instead of <h:selectOneChoice. Use it's valueChangeListener in the same way. However, you can't just submit the form via Javascript like that because it is not aware of the JSF life-cycle (not post'ing the right stuff and your code shouldn't interact with that level of JSF internals anyway). If you set <tr:selectOneChoice autoSubmit="true"... this will cause a post to occur when the drop-down menu value changes that calls your value change listener.
Invoking a javascript function like the way you mentioned in the code snippet will not submit your form.To invoke
valuechange
listener you need to submit a request to the backing bean which will check your application level logic. You can try removing the
onClick
attribute and also please put a message as you have placed a
validator
. At times it so happen, that when validation is not succeeded and you have not attached a corresponding message or notification for the same, the desired action won't be performed. So even though your logic might be write but he JSF lifecycle interrupts at
validation phase
and your remaining action is not invoked.

Resources