<h:commandButton> not firing the action method - jsf

I have a nested <h:form>, and inside the inner most <h:form> I have a <h:commandButton> like this,
<h:commandButton value="Next" actionListener="#{billController.saveFiles}"\>
public void saveFiles(ActionEvent event){
//code
}
But this method is not getting invoked by clicking the action button.
Can anyone give a solution to this?

Just stop nesting forms. Nested forms are invalid in HTML. You should never nest HTML <form> elements. As JSF is merely a HTML code generator, it's also not different from JSF side on. You should never nest JSF <h:form> components as well.
The browser behavior on nested forms is unspecified.

Can you post your whole jsp page? If button is not inside <h:form> tag it wont call action method

Related

onclick for p:outputLabel works on loading/refreshing page but doesn't work when clicking

I have some problems with calling a bean method when clicking on Label.
When page is loading or refreshing click handler function pokus() is called, but when the label is clicked it isn't.
Part of my web page:
<h:form id="pokus">
<p:outputLabel id="pokus2" value="klikni" onclick="#pozadavkyBean.pokus(5)}"/>
</h:form>
and a method in bean:
public void pokus(int i){
System.out.printf("kliknuto sloupec:%d",i);
}
I've also tried it with:
<p:ajax event="click" listener="....
with the same result - method called on loading/refreshing but not when clicking
also tried others events: mousedown, mouseup, .... with same result
using PrimeFaces 5.0
If you will check official document of Primeface regarding Tag outputLabel.You can easily get attribute onclick used for
Client side callback to execute when component is clicked.
But here you are trying to run Managed bean method directly from onclick attribute while onclick used to call JavaScript functions.
As #Mahendran Ayyarsamy Kandiar mentioned and its simple thing outputLabel is not used to call any bean method. Its Just Simply used to show something in the page.In mean time for your requirement you can use CommandButton,CommandLink or some other component but its all depend upon your requirment etc.

<p:commandLink> not firing actions at all

I can't make my commandLink fire a bean action.
I've tried calling my bean method with <p:commandButton>, <h:commandLink>, <h:outputLink> and <p:commandLink>.
Also, i've used onclick, onmousedown, action and actionListener and none of those worked.
My code looks like this at the moment:
base.xhtml
<div>
<h:form>
<p:commandLink id="logoutButton" action="#{loginController.logout}">
<p:graphicImage name="/images/logout.png"/>
</p:commandLink>
</h:form>
<!-- Rest of code (layout with some layoutUnits) -->
</div
Bean method (Testing purposes, not the actual method):
public void logout() {
System.out.println("logged out");
}
According to BalusC, my question is duplicated. I had already searched for similar problems before making this question, and guess what? Nothing worked. Looking at same question that has already been answered, here are my answers to the previously described problems:
1 - The commandLink is inside a form.
2 - The commandLink is not in a nested form.
3 - No UIInput value validation/conversion is showing errors.
4 - The commandLink is not inside a iterating component.
5 - As the pages load, the button is not rendered. I've set it to render only if the user log-ins with a commandLink placed in that same form. It is indeed using AJAX.
6 - The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm are not throwing a JavaScript error.
7 - base.xhtml has a <h:head>
8 - The parent of my <h:form> is not being updated/rendered.
9 - Im not using enctype="multipart/form-data" in my form.
10 - I'm not using actionListener.
11 - I'm not using PhaseListener or EventListener.
12 - There is no Filter or Servlet blocking the request to the FacesServlet.
Bonus:
Debugging with Firebug, i've noticed that when i click the logout button i'm getting a code 200 response from the server, meaning it is supposed to be OK.
My form is in a Template file (base.xhtml). After that form, i am using a <p:layout> element and my website code is inside it's <p:layoutUnit>.

Primefaces RequestContext scrollTo does not work

Primefaces v3.5
Trying to use RequestContext.getContext().scrollTo("") to scroll to my form programmatically at the end of an ajax request.
XHTML snippets:
<h:form id="genericMessagesForm">
<p:messages id="genericMessages" />
</h:form>
<p:commandButton id="testButton"
value="Test" process="#{cc.attrs.itemName}Final, #this"
actionListener="#{myBean.methodCalledByAjax()}" />
Bean:
public void methodCalledByAjax() {
List<String> updateTargets = new ArrayList<String>();
updateTargets.add("currentRecordForm");
updateTargets.add("genericMessagesForm");
RequestContext.getCurrentInstance().update(updateTargets);
RequestContext.getCurrentInstance().scrollTo("genericMessagesForm");
}
Update does work.
ScrollTo does NOT work (same ID!).
No server errors thrown.
No javascript console errors thrown.
Browsers tried: Firefox (latest), Chrome (latest), IE8.
Did you look in the documentation? Here's a cite from the RequestContext#scrollTo() javadoc:
scrollTo
public abstract void scrollTo(String clientId)
Scroll to a component after ajax request is completed.
Parameters:
clientId - Client side identifier of the component.
Look, it says client ID, not component ID. It makes also sense, the scrolling job is ultimately done by JavaScript via document.getElementById() and friends. That works only with a client ID.
For starters who haven't memorized the whole NamingContainer thing, an easy way to figure the right client ID is by looking at the JSF-generated HTML output via rightclick, View Source in webbrowser.
For a
<h:form id="genericMessagesForm">
<p:messages id="genericMessages" />
</h:form>
that's thus something like
<form id="genericMessagesForm" ...>
<div id="genericMessagesForm:genericMessages" ...>
...
</div>
</form>
So, fix the call accordingly:
requestContext.scrollTo("genericMessagesForm:genericMessages");
By the way, if the form contains solely the <p:messages>, then you can alternatively also just get rid of the whole form altogether. The <p:messages> is not an EditableValueHolder nor ActionSource component and does therefore not require to be placed in an UIForm component. This way you can keep using your initial attempt.
See also:
How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Difference between h:button and h:commandButton

In JSF 2, what is the difference between h:button and h:commandButton ?
<h:button>
The <h:button> generates a HTML <input type="button">. The generated element uses JavaScript to navigate to the page given by the attribute outcome, using a HTTP GET request.
E.g.
<h:button value="GET button" outcome="otherpage" />
will generate
<input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" />
Even though this ends up in a (bookmarkable) URL change in the browser address bar, this is not SEO-friendly. Searchbots won't follow the URL in the onclick. You'd better use a <h:outputLink> or <h:link> if SEO is important on the given URL. You could if necessary throw in some CSS on the generated HTML <a> element to make it to look like a button.
Do note that while you can put an EL expression referring a method in outcome attribute as below,
<h:button value="GET button" outcome="#{bean.getOutcome()}" />
it will not be invoked when you click the button. Instead, it is already invoked when the page containing the button is rendered for the sole purpose to obtain the navigation outcome to be embedded in the generated onclick code. If you ever attempted to use the action method syntax as in outcome="#{bean.action}", you would already be hinted by this mistake/misconception by facing a javax.el.ELException: Could not find property actionMethod in class com.example.Bean.
If you intend to invoke a method as result of a POST request, use <h:commandButton> instead, see below. Or if you intend to invoke a method as result of a GET request, head to Invoke JSF managed bean action on page load or if you also have GET request parameters via <f:param>, How do I process GET query string URL parameters in backing bean on page load?
<h:commandButton>
The <h:commandButton> generates a HTML <input type="submit"> button which submits by default the parent <h:form> using HTTP POST method and invokes the actions attached to action, actionListener and/or <f:ajax listener>, if any. The <h:form> is required.
E.g.
<h:form id="form">
<h:commandButton id="button" value="POST button" action="otherpage" />
</h:form>
will generate
<form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="form" value="form" />
<input type="submit" name="form:button" value="POST button" />
<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" />
</form>
Note that it thus submits to the current page (the form action URL will show up in the browser address bar). It will afterwards forward to the target page, without any change in the URL in the browser address bar. You could add ?faces-redirect=true parameter to the outcome value to trigger a redirect after POST (as per the Post-Redirect-Get pattern) so that the target URL becomes bookmarkable.
The <h:commandButton> is usually exclusively used to submit a POST form, not to perform page-to-page navigation. Normally, the action points to some business action, such as saving the form data in DB, which returns a String outcome.
<h:commandButton ... action="#{bean.save}" />
with
public String save() {
// ...
return "otherpage";
}
Returning null or void will bring you back to the same view. Returning an empty string also, but it would recreate any view scoped bean. These days, with modern JSF2 and <f:ajax>, more than often actions just return to the same view (thus, null or void) wherein the results are conditionally rendered by ajax.
public void save() {
// ...
}
See also:
How to navigate in JSF? How to make URL reflect current page (and not previous one)
When should I use h:outputLink instead of h:commandLink?
Differences between action and actionListener
h:button - clicking on a h:button issues a bookmarkable GET request.
h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server.
h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:
<h:form>
<h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>
this code generates the follwing html:
<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">
whereas the h:button is simpler and just used for static or rule based navigation as follows
<h:button outcome="page.xhtml" value="button"/>
the generated html is
<title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />
This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk
h:commandButton vs h:button
What’s the difference between h:commandButton|h:commandLink and
h:button|h:link ?
The latter two components were introduced in 2.0 to enable bookmarkable
JSF pages, when used in concert with the View Parameters feature.
There are 3 main differences between h:button|h:link and
h:commandButton|h:commandLink.
First, h:button|h:link causes the browser to issue an HTTP GET
request, while h:commandButton|h:commandLink does a form POST. This
means that any components in the page that have values entered by the
user, such as text fields, checkboxes, etc., will not automatically
be submitted to the server when using h:button|h:link. To cause
values to be submitted with h:button|h:link, extra action has to be
taken, using the “View Parameters” feature.
The second main difference between the two kinds of components is that
h:button|h:link has an outcome attribute to describe where to go next
while h:commandButton|h:commandLink uses an action attribute for this
purpose. This is because the former does not result in an ActionEvent
in the event system, while the latter does.
Finally, and most important to the complete understanding of this
feature, the h:button|h:link components cause the navigation system to
be asked to derive the outcome during the rendering of the page, and
the answer to this question is encoded in the markup of the page. In
contrast, the h:commandButton|h:commandLink components cause the
navigation system to be asked to derive the outcome on the POSTBACK
from the page. This is a difference in timing. Rendering always
happens before POSTBACK.
Here is what the JSF javadocs have to say about the commandButton action attribute:
MethodExpression representing the application action to invoke when
this component is activated by the user. The expression must evaluate
to a public method that takes no parameters, and returns an Object
(the toString() of which is called to derive the logical outcome)
which is passed to the NavigationHandler for this application.
It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action refers to some page's filename and not a method.

Modify dynamically JSF snippets by h:commandlink

I have a h:commandlink control in page1. the control uses f:ajax to call to the following h:panelgroup :
I have a h:panelgroup control in page2 (a snippet), which has a ui:include within it.
I have a h:panelgroup control in page3 (a snippet), which has a ui:include within it.
Now according to the choices made on page1, I would like to switch the snippets by clicking on the h:commandlink control.
I have a BIG problem there: it seems that only if I click twice on the commandlink, only then the snippet changes - and not on one click.
I have tried to remove the f:ajax to render the panelgroup, and still it does not work...
There are two potential causes of this problem.
The <f:ajax> is fully re-rendering another <h:form> than where it is sitting in. This way the view state of the other form will get lost which would require invoking the action on the other form twice before it really get executed.
The solution is to not re-render the other <h:form>, but only some container component in that form. E.g.
<h:form id="otherForm">
<h:panelGroup id="content">
...
<h:panelGroup>
</h:form>
with
<f:ajax render=":otherForm:content" />
When there's a rendered attribute on the <h:commandLink> or any of its parent components, then it must evaluate true during the apply request values phase of the postback request in order to get JSF to invoke the bean action associated with the <h:commandLink> during the invoke action phase of that request. Perhaps the bean is request scoped and/or some odd/illogical flow inside the bean caused that the rendered attribute is not properly been preserved.
Best is to maintain those rendered conditions in a #ViewScoped bean and let its action methods return void or null so that the bean lives as long as you're interacting with the same view. Change the rendered conditions during action methods only and not inside setters/getters or something.

Resources