JSF- passing a parameter to valuechangelistener

主宰稳场 提交于 2019-12-10 02:42:02

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3954652/jsf-passing-a-parameter-to-valuechangelistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!