Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF- passing a parameter to valuechangelistener

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..

like image 687
Tim Tuckle Avatar asked Oct 17 '10 18:10

Tim Tuckle


2 Answers

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");
like image 171
Donato Szilagyi Avatar answered Nov 21 '22 02:11

Donato Szilagyi


Seeing how the component values are bound, I bet that it's inside a datatable. If that is indeed the case, you can use DataModel#getRowData() to obtain the current row. Add a DataModel property to the TestService bean like follows:

private List<Question> questions;
private DataModel<Question> questionModel;

@PostConstruct
public void init() {
    questions = getItSomehow();
    questionModel = new ListDataModel<Question>(questions);
}

public void change(ValueChangeEvent event) {
    Question currentQuestion = questionModel.getRowData();
    // ...
}

and change the view as follows:

<h:dataTable value="#{TestService.questionModel}" var="test">

That said, I'd suggest to use more sensible variable names than TestService, test and change(), like Questionaire, question and changeAnswer() respectively. This makes the code more self-documenting.

like image 26
BalusC Avatar answered Nov 21 '22 03:11

BalusC