How to call JS function on click of JSF button and block page reload/navigation? - jsf

What is the preferred way to create a button with JSF to call JS function ?
Actually I use :
<p:button onclick="myJSFunction();" href="#"/>
but my urls are suffixed with the anchor symbol (#).
Is there another recommended way to create button which will not reload/navigate to URL but call JS function please ?

That's because it's actually navigating to #. You need to block the button from performing its default action, which is navigating to the current view, or to the URL as specified in href or outcome. You can achieve this by adding return false; to the end of onclick.
<p:button onclick="myJSFunction(); return false;" />
Or, if myJSFunction() actually returns a boolean which should determine if the button should continue its default action, then delegate to it:
<p:button onclick="return myJSFunction();" />
The <h:button> works exactly the same way, it's only in standard look'n'feel.
An alternative is to use <p:commandButton type="button">, which generates a real <input type="button"> without any navigation. This way you don't need to return false from onclick.
<p:commandButton type="button" onclick="myJSFunction()" />
This however requires a <h:form> (although placing it outside any form doesn't break any functionality). The same applies to <h:commandButton>.

Related

How to open an arbitrary URL in new window using a PrimeFaces button

I have the below output link which does its job:
<h:outputLink value="#{verDocumentoController.url()}" target="_blank">
show document
</h:outputLink>
It opens an URL obtained as a bean property in a new window.
However, I'd like to turn the link into a button in PrimeFaces look'n'feel. I tried as below:
<p:commandButton value="show document" action="#{verDocumentoController.url()}"
onclick="form.target='_blank'" ajax="false" />
But it only reopens the current page in a new window and not the URL specified as bean property. How can I achieve this anyway?
The <p:commandButton> basically submits a POST request to the URL as specified by its parent <h:form>, which defaults indeed to the current request URL (you know, "postback"). The action attribute basically invokes a bean method and uses the returned value as navigation case outcome. An URL does not necessarily represent a sensible navigation case outcome.
Just use window.open() instead on a simple <p:button>.
<p:button value="show document"
onclick="window.open('#{verDocumentoController.url()}');return false;" />
You can also do this on a <p:commandButton>, but that's unnecessarily overcomplicated.

Setting a command button to selected by default

I have a form in which I needed to have radio buttons that look like bootstrap toggle buttons. I achieved this by using command buttons in a button group, and setting the attribute data-toggle="buttons-radio", like so:
<div id="flightChoiceButtons" class="btn-group" data-toggle="buttons-radio">
<h:commandButton type="button" styleClass="btn btn-inverse" value="One Way"><f:ajax render="flexibleDates" listener="#{searchFlightsBean.setDirectionOneWay}"/></h:commandButton>
<h:commandButton type="button" styleClass="btn btn-inverse" value="Round Trip"><f:ajax render="flexibleDates" listener="#{searchFlightsBean.setDirectionRoundtrip}"/></h:commandButton>
</div>
The problem I'm stuck with right now is that I need the "Round Trip" button to be selected, or in the down state, when the page loads. I don't need the button's ajax call to be fired, because the data displayed on the page is already in the state it needs to be in.
Anyone have any ideas?
If any more information is needed I'd be glad to supply it.
The bootstrap button's active state is identified by presence of active style class. Knowing that, you can just let JSF print the style class conditionally. The way how your model is setup is unclear, so here's just a kickoff example provided that you've a #{searchFlightsBean.direction} property returning an enum.
<h:commandButton ... styleClass="btn btn-inverse #{searchFlightsBean.direction == 'ONE_WAY' ? 'active' : ''}">...</h:commandButton>
<h:commandButton ... styleClass="btn btn-inverse #{searchFlightsBean.direction == 'ROUND_TRIP' ? 'active' : ''}">...</h:commandButton>
You can replace the #{searchFlightsBean.direction == '...'} part by any other boolean condition. You can find examples in this answer: Conditionally displaying JSF components.

Button as link, <h:button outcome /> not working (no navigation cases used)

I am trying to achieve the following, though with a button.
<h:outputLink value="/admin/category/read">
Cancel
<f:param name="cat" value="" />
<f:param name="subcat" value="" />
</h:outputLink>
I have tried using h:button, though the outcome property does not work since /admin/category/read is not a specified navigation-case.
How to use a button as link, without having to use a navigation-case or server side method?
No, there's no solution using JSF attributes, at least not if you really don't have a navigation case for the h:button.
If possible, I'd advise to use CSS styling as already mentioned in the comments.
But h:button just creates a plain HTML link with onclick="window.location.href=URL". So if you really want, you can build the URL yourself and just use a plain HTML input button like this:
<input type="button" value="Cancel"
onclick="window.location.href='/admin/category/read?cat=&subcat='; return false;" />
Related:
Difference between h:button and h:commandButton
When should I use h:outputLink instead of h:commandLink?

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.

Open new window by POST using h:commandButton

I need to open a JSF page in a new window by POST on click of a <h:commandButton>. I know I can acheive this using the JavaScript. But I would like to achive this using JSF and not JavaScript.
How can I achieve this? I'm using JSF 2.0.
The only non-JS way is to set target="_blank" in the parent <h:form>.
<h:form target="_blank">
...
<h:commandButton value="Open in new Window" />
</h:form>
This however affects all non-ajax(!) actions which are performed in the very same form. So if you're smart, make the action which shouldn't open in a new window an ajax action. However, ajax is also JavaScript and you mentioned that you don't want to use JS (I hope you don't get shocked once you discover that PrimeFaces is actually full of JavaScript).
If you absolutely need to restrict it to a single action, then you really can't go around asking little help to JavaScript.
<h:form>
...
<h:commandButton value="Open in new Window" onclick="this.form.target='_blank'" />
</h:form>
When you restrict the target only to a single action, maybe you want to get the form in its initial state.
With the oncklick action you set the target of the form to a _blan page.
After the click, the page is opened in a new tab/page (triggers the action event).
At last, the onblur action is triggered and set the form again to its initial state (the rest of the buttons will open in the _self page)
With this code, you can restrict to only a h:commandbutton to open in a new page.
The rest of the buttons will be opened in the self page:
<h:commandButton
onclick="this.form.target='_blank'"
onblur="this.form.target='_self'"
id="listadoRebuts"
action="#{giaquaBusquedaCorte.abrirListadoRebuts}"
value="#{msg.seqVisorbtnRecibos}">
</h:commandButton>

Resources