How can I create toggle buttons in JSF? - jsf

How can I create toggle buttons in JSF?
Basically, I need two buttons "in" and "out". They essentially call the same managed bean, but as a result of every click the one should be disabled and the other should be enabled and vice versa. How can this be done? Should I use ajax functionality?

Just have a boolean property which you inverse in action method and use exactly that property in the disabled attribute of the both buttons, inversed.
Kickoff example:
#ManagedBean
#ViewScoped
public class Bean {
private boolean enabled;
public void toggle() {
enabled = !enabled;
}
public boolean isEnabled() {
return enabled;
}
}
With
<h:form>
<h:commandButton value="Enable" action="#{bean.toggle}" disabled="#{bean.enabled}" />
<h:commandButton value="Disable" action="#{bean.toggle}" disabled="#{not bean.enabled}" />
</h:form>
Ajax is technically not necessary. Feel free to add <f:ajax> to both buttons to improve the user experience though.
A #ViewScoped bean is in turn very necessary. A #RequestScoped one would be trashed on end of request and recreated in next request, hereby causing the boolean to be reinitialized to default and thus seemingly fail to work after second click, because JSF will as part of safeguard against tampered/hacked requests also check the disabled (and rendered) attribute before actually invoking the action.
See also:
How to choose the right bean scope?
commandButton/commandLink/ajax action/listener method not invoked or input value not updated (point 5)

Related

Does JSF prevent calls to unrendered managed bean actions by tampered requests

A method in a managed bean is protected by JSF? See the code:
Managed Bean
#ManagedBean
public class My {
public void test() {
System.out.println("called");
}
}
XHTML
<h:form>
<h:commandButton rendered="true" action="#{my.test}" value="Teste" />
</h:form>
If the button is not rendered (rendered="false"), a HTTP POST request (as the button would do) can be done and call the test() method?
In other words, JSF prevents calls to managed beans methods by tampered requests?
In other words, JSF prevents calls to managed beans methods by tampered requests?
Yes.
JSF re-evaluates the component's rendered attribute during apply request values phase. If it's false, then in case of UICommand components the ActionEvent simply won't be queued, regardless of whether the (tampered) HTTP request parameter indicates that the button is being pressed.
JSF has similar safeguard against tampered requests on the disabled and readonly attributes, also those of UIInput components. And, in UISelectOne/UISelectMany components, JSF will validate if the submitted value is indeed part of the provided available options.
JSF does this all also with help of the view state. If JSF were stateless, there would be more risk that one or other may fail if those attributes suddenly become request scoped instead of view scoped.
See also:
commandButton/commandLink/ajax action/listener method not invoked or input value not updated - point 5
Validation Error: Value is not valid
How to disable/enable JSF input field in JavaScript?
What is the usefulness of statelessness in JSF?

Set bean value on click of selectbooleancheckbox

I have a bean class and a selectBooleanCheckbox in xhtml page. I want that on the click of the box the value should be set in the backing bean.
Here is code:
<h:selectBooleanCheckbox id="provisioningTargetCollector"
value="#{targetSource.provisioningTargetCollector}">
</h:selectBooleanCheckbox>
Bean Class:
public boolean isProvisioningTargetCollector() {
return _provisioningTargetCollector;
}
public void setProvisioningTargetCollector(boolean provisioningTargetCollector) {
_provisioningTargetCollector = provisioningTargetCollector;
}
But the getter and setter are called only on page load. How can I set the value in bean method on click of checkbox.
The model with be filled with form data only when submit button will be pressed. If you want to do partial update to the server you need to send an AJAX request. Luckily, starting from JSF 2 it has been quite simple with the introduction of <f:ajax> tag. It adds ajax capabilities to UIComponent instances that implement the ClientBehaviorHolder interface, i.e. components that are capable of triggering ajax requests.
To do partial update of compenets you need to specify their client ids in execute attribute of <f:ajax> tag. As the default value of execute attribute evaluates to #this, or the component to which the tag is attached it. As soon as you want to update only the given <h:selectBooleanCheckbox> you can do it as simple as nesting a pure <f:ajax /> tag within you checkbox, i.e.:
<h:selectBooleanCheckbox id="provisioningTargetCollector" value="#{targetSource.provisioningTargetCollector}">
<f:ajax />
</h:selectBooleanCheckbox>

Setting Managed Bean attribute's value from JSF page and using it in bean's methods

I have a ViewScoped Managed Bean. In my .xhtml page I want to set bean's attribute's value and use it in methods in the same bean.
I managed to set the value from jsf page, but when i want to use it in some method the value of an attribute is not the value i have set before.
Description (xhtml):
In this form there is a command link which sets the value of an attribute. And it is working fine. Also, as command link is clicked, second form is being showed.
<h:form>
<h:commandLink value="Set" >
<f:setPropertyActionListener target="#{bean.attribute}" value="true" />
<f:ajax execute="#this" />
</h:commandLink>
</h:form>
This form executes method that uses attribute's value set before, but the value is not true, its false.
<h:form>
<h:commandButton id="submit" value="Execute" action="#{bean.execute}" />
</h:form>
Bean:
public void execute(){
if(isAttribute())
---do something---
}
The question is: Why execute() is not reading attribute's value right?
When I use one form, it's working fine. But I need them to be in separated forms.
The scope of your bean is incorrect. ViewScoped means that the minute the view is changed, the bean is discarded and re-created for the next view. So, in your case, the original data you had for the first view is lost.
I'm going to refer you to BalusC's blog:
http://balusc.blogspot.co.uk/2010/06/benefits-and-pitfalls-of-viewscoped.html
which states:
A #ViewScoped bean will live as long as you're submitting the form to the same view again and again. In other words, as long as when the action method(s) returns null or even void, the bean will be there in the next request. Once you navigate to a different view, then the bean will be trashed
I can't determine of you stay on the same page with both requests. If you do, viewScope should work even in two different forms. If you are navigating from 1 view to another, another viewScope will be created and you will loose the current one.
You could set the value in the sessionScope with java or by annotating the backingNean. But then everything in your backingBean becomes sessionScoped and that might not be needed.
You could also use a spring-like flow scope.
Example to do it with java:
public void callThisAfterFirstClick() {
Faces.setSessionAttribute(attribute, true)
}
public void callThisAfterSecondClick() {
Faces.getSessionAttribute(attribute);
}

further continuing of double press

In a previous question BalusC gave me good advice on how a button, in place of a commandButton is useful for non ajax navigation. In particular it updates the destination address in the http: position which is useful for the user to bookmark a page.
I tried to use this information to my advantage until I came upon a problem. In a button I tried to use outcome="#{backing.something}" to find out that it gives me a null result. This looks like a timing problem in that action="#{}" is evaluated only when the button is pressed whereas outcome apparently wants a fixed string which gets checked when the page is loaded.
So I went back to commandButton with ajax="false". This has a problem that my navigation address is the page I came from, not the one I am navigating to. This is the wrong bookmark for the user.
I appreciate all the help I have received in stackoverflow on my learning exercise.
Ilan
The <h/p:button outcome> is not intented to invoke a bean action method, but to contain the outcome string directly. Any EL in there is evaluated immediately as a value expression. So the method behind it would immediately be invoked when you just open the page containing the <h/p:button>.
There are in your particular case basically two ways to invoke a bean action method on navigation. If you need to invoke it before the navigation takes place and the action isn't intented to be re-invoked everytime when the enduser reopens/reloads the GET request, then make it a POST-Redirect-GET request. It's a matter of adding faces-redirect=true to the outcome value in query string syntax.
E.g.
<p:commandButton action="#{bean.submit}" ... />
with
public String submit() {
// ...
return "nextpage?faces-redirect=true";
}
This way the browser will be redirected to the target page after POST, hence the enduser will see the target URL being reflected in the address bar.
Or if you need to invoke the action everytime when the enduser reopens/reloads the GET request, do the job in the (post)constructor or preRenderView listener method of the request/view scoped backing bean instead.
E.g.
<p:button outcome="nextpage" ... />
with
#ManagedBean
#RequestScoped
public class NextpageBacking {
public NextpageBacking() {
// In constructor.
}
#PostConstruct
public void onPostConstruct() {
// Or in postconstructor (will be invoked after construction AND injection).
}
public void onPreRenderView() {
// Or before rendering the view (will be invoked after all view params are set).
}
// ...
}
The pre render view listener method needs to be definied as follows in the nextpage
<f:event type="preRenderView" listener="#{nextpageBacking.onPreRenderView}" />
See also:
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
Communication in JSF 2.0 - Processing GET request parameters

Re-enabled p:commandButton not firing ajax

If I initiate a commandButton disabled the AJAX event does not fire even after re-enabling the button.
<p:commandButton id="btnAJAX" value="AJAX" widgetVar="btnAJAX" disabled="true" action="#{bean.neverReached()}"/>
<p:commandButton id="btnEnabler" value="Enable" oncomplete="btnAJAX.enable()"/>
Similar problem identitifed here : http://forum.primefaces.org/viewtopic.php?f=3&t=7817
I am using primefaces 3.0.1 and JDK 1.7
Is there any solution to this?
You need to enable the button by JSF, not by JavaScript/HTML DOM. During processing of the form submit, JSF will verify in the server side view state as well if the button is enabled or not, as part of safeguard against tampered requests.
E.g.
<p:commandButton id="btnAJAX" value="AJAX" action="#{bean.someAction}" disabled="#{!bean.enabled}" />
<p:commandButton id="btnEnabler" value="Enable" action="#{bean.enableButton}" process="#this" update="btnAJAX" />
with
private boolean enabled;
public void enableButton() {
enabled = true;
}
public boolean isEnabled() {
return enabled;
}
Make sure that the bean is at least #ViewScoped and not #RequestScoped, otherwise the action of button will still fail because the bean is recreated during the form submit request and thus the enabled property will become the default value, which is false.
See also:
commandButton/commandLink/ajax action/listener method not invoked or input value not updated

Resources