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..
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");
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.
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