onclick tag giving error in h:commandLink - jsp-tags

I'm using JSF 1.2 and I was trying to add onclick tag to h:commandLink which is throwing runtime error.
The code I'm trying to write in jsp is:
<h:commandLink id="btn" styleClass="button" onclick="performAction();">
<h:outputText value="some value" />
</h:commandLink>
It is giving me an error:" Unable to locate tag attribute info for tag attribute onclick. "
Any help is appreciated.
Thank you.

From h:commandLink it says...
The commandLink tag renders an HTML "a" anchor element that acts like a form submit button when clicked.The commandLink tag is used to submit an action event to the application.
Use <h:commandLink> tag to represent a link to POST form data.
h:commandLink tag must include a nested outputText tag, which represents the text the user clicks to generate the event.
The generated HTML uses syntax.
The commandLink tag will render JavaScript. If you use this tag, make sure your browser is JavaScript-enabled.
The onclick attribute is automatically populated with Javascript to submit the form.
Setting type = “reset” makes the link a reset button.
Use the action attribute to associate the link with a JavaBean’s method.
You should check the source code via view source and check for java script errors via Firefox.

Related

Is loading triggered from the click of a submit button generated by h:commandButton a full load?

A jsf page contains a form with a commandButton element like <h:commandButton action="#{bean.search}". This submit button will trigger a bean, which then will send more data back to this same jsf page.
Question: after the submit, is the jsf page fully loaded again? or is just the part containing the newly retrieved data reload and other parts are not loaded again?
By default JSF will fully reload the page. This can be tested by looking at the browser network developer tools while submitting the commandButton. If you intend to only render a part of the page - e.g. a label that outputs the result - you can do that by using AJAX.
For example if your commandButton is in a form, by adding
<f:ajax execute="#form" render="#form:result" />
within your commandButton tag, you can specify that only the contents of the form are processed by the server and only the label with the ID 'result' is rendered.
For further information take a look at this guide for AJAX in JSF: https://www.beyondjava.net/a-comprehensive-guide-to-jsf-ajax
You will see that the author shows the full page loading without AJAX.
Alternatively here is the official documentation for <f:ajax>:
https://jakarta.ee/specifications/faces/2.3/vdldoc/f/ajax.html

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.

commandlink in JSF not generating the intended HTML tag

I'm trying to call a managed bean from h:commandLink in JSF. But I don't see href attribute in the rendered HTML a tag.
Am I missing something?
There is a ManagedBean called AccountSetupController with a signUp method in it.
This is the tag I used in JSF:
<h:form prependId="false">
<h:commandLink action="#{accountSetupController.signUp()}"
value="#{msg['homepage.createaccount']}" styleClass="button large">
</h:commandLink>
</h:form>
This is the rendered tag. See there is nothing in href attribute.
<a href="#" onclick="mojarra.jsfcljs(document.getElementById('j_idt15'),
{'j_idt33':'j_idt33'},'');return false"
class="button large">CREATE MY ACCOUNT</a>
This is the form tag that is generated
<form id="j_idt15" name="j_idt15"
method="post" action="/myproject/faces/homepage/homepage.xhtml"
enctype="application/x-www-form-urlencoded"> .... </form>
As you can see, the form action is pointing to some place I don't need.
Am I missing something?
Command links in JSF are rendered that way. The form will be submitted by JSF via JavaScript's onclick method using JSF JS library, while the href will always stay #.
Moreover, you won't find the bound action / action listener method names in browser tools due to understandable reasons. Rather, JSF will find the id of a clicked link on the server and will trigger all of the component's action(listeners).
All in all, reading <h:commandLink> documentation unsurprisingly helps a lot (all emphasis mine):
General behavior: Both the encode and decode behavior require the ability to get the id/name for a hidden field, which may be rendered in markup or which may be programmatically added via client DOM manipulation, whose value is set by the JavaScript form submit (further referred to as hiddenFieldName.
Decode behavior: Obtain the "clientId" property of the component. Obtain the Map from the "requestParameterMap" property of the ExternalContext. Derive hiddenFieldName as above. Get the entry in the Map under the key that is the hiddenFieldName. If the there is no entry, or the entry is the empty String, or the entry is not equal to the value of the "clientId" property, return immediately. If there is an entry, and its value is equal to the value of the "clientId" property, create a new javax.faces.event.ActionEvent instance around the component and call queueActionEvent() on the component, passing the event.
Encode behavior: Render "#" as the value of the "href" attribute. Render the current value of the component as the link text if it is specified. Render JavaScript that is functionally equivalent to the following as the value of the "onclick" attribute: document.forms['CLIENT_ID']['hiddenFieldName'].value='CLIENT_ID'; ocument.forms['CLIENT_ID']['PARAM1_NAME'].value='PARAM1_VALUE'; document.forms['CLIENT_ID']['PARAM2_NAME'].value='PARAM2_VALUE'; return false; document.forms['CLIENT_ID'].submit()" where hiddenFieldName is as described above, CLIENT_ID is the clientId of the UICommand component, PARAM*_NAME and PARAM*_VALUE are the names and values, respectively, of any nested UIParameter children.

CommandButton action: use value of inputText as parameter in dynamic URL

I need to make a small form where user types a number into the inputField, and clicks on a button, then is sent to a page, using that number as a parameter to the page.
So far I got into this:
<p:inputText id="myText" style="width:75px;" />
<p:commandButton id="myButton" value="Ir"
action="/site/page.xhtml?id=${param['form:myButton']}"
title="Ir" ajax="false" proces="#this,myText" />
tried with ${param['form:myButton']} and #{param['form:myButton']}, error is the same.
Problem is, JSF thinks its a method expression...
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/intranet] threw exception [/myPage action="/site/page.xhtml?id=${param['form:myButton']}".xhtml #95,41 action="/site/page.xhtml?id=${param['form:myButton']}" Not a Valid Method Expression: action="/site/page.xhtml?id=${param['form:myButton']}" with root cause
javax.el.ELException: Not a Valid Method Expression: action="/site/page.xhtml?id=${param['form:myButton']}"
at org.apache.el.lang.ExpressionBuilder.createMethodExpression(ExpressionBuilder.java:236)
at org.apache.el.ExpressionFactoryImpl.createMethodExpression(ExpressionFactoryImpl.java:55)
at org.jboss.weld.util.el.ForwardingExpressionFactory.createMethodExpression(ForwardingExpressionFactory.java:43)
at org.jboss.weld.el.WeldExpressionFactory.createMethodExpression(WeldExpressionFactory.java:64)
at com.sun.faces.facelets.tag.TagAttributeImpl.getMethodExpression(TagAttributeImpl.java:222)
at com.sun.faces.facelets.tag.jsf.ActionSourceRule$ActionMapper2.applyMetadata(ActionSourceRule.java:104)
at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:81)
at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:129)
at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:102)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:402)
and this is the bottom-most exception trace.
Question: how can I pass the value typed into of the input-field into the action of the Button when the button is clicked, so the browser navigates to the desired page passing the value in the input as a parameter, without resorting to a backing bean.
I don't need to communicate with the server, just forward the page.
any solution using jQuery or plain javascript in tandem with JSF is acceptable too.
using mojarra, primefaces 3.3.1
use <f:param> It's explained in this article from BalusC http://balusc.blogspot.in/2011/09/communication-in-jsf-20.html#ProcessingGETRequestParameters
I do not need a bazooka to kill a mouse. The answer is very simple.
bind a javascript function to the onclick of the button, and in that function, retrieve the value of the input field by its id, then assemble URL with the parameters and navigate away from within the javascript function.
JSF code (assume they are inside a form with myForm as its id):
<p:inputText id="myInput" style="width:75px;" />
<p:commandButton id="myButton" value="Ir" onclick="navega();" title="Ir" ajax="false" proces="#none" />
Javascript script, declared on a separate file or later on in the xhtml document:
function navega() {
var submittedInputValue = $('#myForm\\:myInput').val();
window.location.href = "/site/mypage.xhtml?param1=whatever&id=" + submittedInputValue ;
}
Take note of the prepend id (myForm:myInput), of using \\ to escape the : in jQuery, and using & instead of & in the xhtml so its not treated as an entity.
Note: probably not all of those commandButton attributes are required, feel free to edit this answer and remove the useless ones.
EDIT: removed the submit and changed process to #none on the command button.

JSF 2.0 navigating on commandLink and commandButton doesn't work

I'm using JSF 2.0 and I have a problem with navigation after both commandLink and commandButton. I use following code:
<h:commandLink action="login?faces-redirect=true"
value="#{showElementBean.showElement()}"> Login </h:commandLink>
<h:commandButton action="login?faces-redirect=true" value="Move to login.xhtml" />
These tags are inside a form, login is just an example. Result of clicking on rendered controls is always POST with refresh of a current page. What do I wrong?
Edit:
According to comments of BalusC I' adding real code fragment:
<h:commandLink actionListener="#{showElementBean.showElement(element)}"
value="View" > </h:commandLink>
I have a page with a list of elements and I want to add links that leads to element view page. Thus I need to pass this element to a show page. I'm JSF primer, e.g. in Rails I'd use GET and URL params, but I don't know how to do it 'in JSF-way'.
There are a lot of possible causes for this behaviour. They are all cited in the following answer, along with solutions: commandButton/commandLink/ajax action/listener method not invoked or input value not updated.
However, in your particular case, you seem rather to be interested in plain GET requests instead of POST requests, as all you want is simple page-to-page navigation. In that case, you need a <h:link> or <h:button> instead:
<h:link outcome="login" value="Login" />
<h:button outcome="login" value="Move to login.xhtml" />
(I have no idea what you're trying to do with both #{showElementBean.showElement()} and Login as command link value, so I omitted the former)
See also:
When should I use h:outputLink instead of h:commandLink?
Refer this info: JSF HTML Tags
h:commandButton
The commandButton tag renders an HTML submit button that can be
associated with a backing bean or ActionListener class for event
handling purposes. The display value of the button can also be
obtained from a message bundle to support internationalization (I18N).
Example
<h:commandButton id="button1" value="#{bundle.checkoutLabel}" action="#{shoppingCartBean.checkout}" />
HTML Output
<input id="form:button1" name="form:button1" type="submit" value="Check Out" onclick="someEvent();" />
h:commandLink
The commandLink tag renders an HTML anchor tag that behaves like a
form submit button and that can be associated with a backing bean or
ActionListener class for event handling purposes. The display value of
the link can also be obtained from a message bundle to support
internationalization (I18N).
Example
<h:commandLink id="link1" value="#{bundle.checkoutLabel}" action="#{shoppingCartBean.checkout}" />
HTML Output
Check Out
Noticed that backing bean method is not called if the form is for file upload:
<h:form name="searchForm" enctype="multipart/form-data" method="post" action="/search">
I also faced with that issue and adding the
<h:form><h:commandLink></h:commandLink> </h:form>
solved my problem.

Resources