简体   繁体   English

ui:repeat中的输入组件,如何保存提交的值

[英]input component inside ui:repeat, how to save submitted values

I'm displaying a list of questions from database and for each question I have to display a list of options, in this case radio buttons. 我正在显示数据库中的问题列表,对于每个问题,我必须显示选项列表,在此情况下为单选按钮。

<ui:repeat value="#{formData.questions}" var="question">
    <div>
        <p:outputLabel value="#{question.name}" />
        <p:selectOneRadio value="#{formData.selectedOption}">
            <f:selectItems value="#{formData.options}" />
        </p:selectOneRadio>
    </div>
</ui:repeat>

I need to save the checked option for each question. 我需要为每个问题保存选中的选项。

How can I do this? 我怎样才能做到这一点?

You need to associate the input value with the repeated variable var in some way. 您需要以某种方式将输入值与重复变量var关联。 Right now you're not doing that anywhere and basically binding all input values to one and same bean property. 现在,您不会在任何地方执行此操作,并且基本上将所有输入值绑定到一个相同的bean属性。 So, when the form gets submitted, every iteration will override the bean property everytime with the value of the current iteration round until you end up getting the value of the last iteration round. 因此,提交表单时,每次迭代都会使用当前迭代回合的值每次覆盖bean属性,直到最终获得上一轮迭代的值为止。 This is definitely not right. 这绝对是不对的。

The simplest way would be to directly associate it with the object represented by var : 最简单的方法是直接将其与var表示的对象关联:

<p:selectOneRadio value="#{question.selectedOption}">

In your specific case, this only tight-couples the "question" model with the "answer" model. 在您的特定情况下,这仅将“问题”模型与“答案”模型紧密结合在一起。 It's reasonable to keep them separated. 将它们分开是合理的。 A more proper solution in your specific case is to map it with currently iterated #{question} as key (provided that it has a proper equals() and hashCode() implementation, obviously): 在您的特定情况下,更合适的解决方案是使用当前迭代的#{question}作为键来映射它hashCode()显然,它具有适当的equals()hashCode()实现):

<p:selectOneRadio value="#{formData.selectedOptions[question]}">

With: 带有:

private Map<Question, String> selectedOptions = new HashMap<>();

Regardless of the approach, in the action method, just iterate over it to collect them all. 不管采用哪种方法,在动作方法中,只需对其进行迭代以收集所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM