Feeds:
Posts
Comments

Archive for May 1st, 2012

Quick post today 🙂

If you’re trying to pass parameters from client code (Javascript functions for instances) to your ManagedBeans/EJBs there’s a simple way to do it – Use hidden values.

Now, let’s suppose that i want each selection/change the user makes in a radio set to be persisted in my database . As it’s obvious, if the form is submitted, JSF will assign the parameters to your Managed Beans classes. However, if by some chance, the user doesn’t submit the form, then you’ll lose your data.

So, how to do it. We’ll need three items:

1) A Javascript function. Something like this:


function changedValues(buttonValue){

document.getElementById('formsTab:hiddenButton').value = buttonValue;
remoteChangeCommand();
}

2) Two HTML tags on your form (form id is formsTab btw)


<h:inputHidden id="hiddenButton" value="#{yourManagedBean.buttonValue}"/>

<p:remoteCommand name="remoteChangeCommand" process="hiddenButton"/>

…and of course your radio set:

<input type="radio" name="Opt1" value="1" onclick="changedValues('1');"/>
<input type="radio" name="Opt2" value="2" onclick="changedValues('2');"/>

3) Finally, your Managed Bean:


@ManagedBean(name = yourManagedBean")
@ViewScoped
public class MyManagedBean {

private String buttonValue;

...

public void setButtonValue(String buttonValue) {
this.buttonValue = buttonValue;

//call business logic here!! Ex:
....persist(buttonValue);
}

public String getButtonValue() {
return buttonValue;
}

}

So, how does this work. Well its something like this. When a radioButton is selected, the JavaScript function is called.

This function does two things:
A) First, sets the hidden input tag with the argument from the call.
B) Second, calls the remoteCommand.

The remoteCommand is a special Primefaces tag that allows you to set a Managed Bean Parameter. In this case, we call setButtonValue method (this is abstracted of course by JSF).
The rest is a small trick. We just have to put a small call within the ManagedBean set operation to another method to perform the required business operation (persist in this case).

Hope it helps someone! Well, it helped me!! 😀
Cumps!

Read Full Post »