I am new to JSF and want to have a button, which when clicked, will call a method of the backing bean. Is this possible or I have to use AJAX or something? I tried things like
<button onclick="#{myManagedBean.myMethod()}">MyButton</button>
But they didn't work. What's the normal way of doing it?
Edit:
That button is created by JqueryUI, and I am unable to change the button's type to commandButton. I am able to do only two customizations-
1. call javascript functions from that button
2. change the target of the form (inside which the button resides)
So, how can I call the backing bean method from these two ways, like from Javascript or on form submit?
In JSF you have action parameter for the JSF componenents which can be bound to a method in your managed bean. using this method binding you can invoke the method of your managed bean.
<h:commandButton value="click" action="#{managedbean.method}"/>
onClick is used to invoke a client-side scripting function like java script. In order to invoke a method on the server side(backing bean), you need to use the action attribute of the commandButton component. JSF provides a component h:commandButton for this purpose. The syntax for using the commandButton to invoke a method in the backing bean is
<h:commanButton value="button" action="#{myBean.methodName()}"/>
The method that you are invoking should be of the form String methodName()
, where the String value returned represents the outcome used by the navigation handler to determine what page to display next.
EDIT:
In order to call a backing bean method from your button, use the onClick attribute of your button to call a javascript function. You would need to create a hidden button in your form which invokes the required backing bean method. In the javascript function, use the below code to click the hidden button and thereby invoke the backing bean method.
document.getElementById('form:button').click();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With