JSF- passing a parameter to valuechangelistener

Tim Tuckle picture Tim Tuckle · Oct 17, 2010 · Viewed 18.6k times · Source

I have a litte radiobutton like this :

<h:selectOneRadio value="#{test.answer}" valueChangeListener="#{TestService.changeanswer}" immediate="true" id="answer">
 <f:selectItem  itemValue="A" itemLabel="Absolutely True"/>
 <f:selectItem  itemValue="B" itemLabel="True"/>
 <f:selectItem  itemValue="C" itemLabel="Partially True"/>
 <f:selectItem  itemValue="D" itemLabel="Not True"/>
 <f:selectItem  itemValue="E" itemLabel="Definitely Not True"/>
 <f:ajax event="change" process="answer"></f:ajax></h:selectOneRadio>

And my listener is like that :

public void changeanswer(ValueChangeEvent vcEvent) { 
System.out.println("comeon= " + vcEvent.getOldValue()); 
System.out.println("comeon= " + vcEvent.getNewValue());}

I would like to pass a parameter to the changeanswer method.For example I want to pass the questionid to the changeanswer function. I need to make some arrangements in it.

How can I do that?

Many many many thanks in advance.

Brad - the Rookie..

Answer

Donato Szilagyi picture Donato Szilagyi · Dec 15, 2012

You can use the f:attribute tag to send any data to the ValueChangeListener:

<h:selectOneRadio value="#{test.answer}"
                  valueChangeListener="#{TestService.changeanswer}"
                  immediate="true" id="answer">
    <f:attribute name="myattribute" value="#{test.questionid}" />
    <f:selectItem  itemValue="A" itemLabel="Absolutely True"/>
    ...
</h:selectOneRadio>

If we suppose questionId is an Integer, then you can receive the data the following way:

public void changeanswer(ValueChangeEvent vcEvent) { 
  Integer questionId =
    (Integer) ((UIInput) vcEvent.getSource()).getAttributes().get("myattribute");