ui:repeat中的输入组件,如何保存提交的值 [英] input component inside ui:repeat, how to save submitted values

查看:145
本文介绍了ui:repeat中的输入组件,如何保存提交的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在显示数据库中的问题列表,对于每个问题,我必须显示选项列表,在此情况下为单选按钮.

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.

我该怎么做?

推荐答案

您需要以某种方式将输入值与重复变量var关联.现在,您不会在任何地方执行此操作,而是将所有输入值绑定到一个相同的bean属性.因此,在提交表单时,每次迭代都会使用当前迭代回合的值每次覆盖bean属性,直到最终获得上一轮迭代的值为止.这绝对是不对的.

You need to associate the input value with the repeated variable var in some way. Right now you're not doing that anywhere and basically binding all input values to one and same bean property. 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. This is definitely not right.

最简单的方法是将其直接与var表示的对象关联:

The simplest way would be to directly associate it with the object represented by var:

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

在您的特定情况下,这仅将问题"模型与答案"模型紧密结合在一起.将它们分开是合理的.在您的特定情况下,更合适的解决方案是使用当前迭代的#{question}作为键来映射它(显然,前提是它具有正确的equals()hashCode()实现):

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):

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

使用:

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

不管采用哪种方法,在action方法中,都需要对其进行迭代以收集所有信息.

Regardless of the approach, in the action method, just iterate over it to collect them all.

这篇关于ui:repeat中的输入组件,如何保存提交的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆