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

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

问题描述

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

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

</ui:repeat>

我需要为每个问题保存选中的选项.

我该怎么做?

解决方案

您需要以某种方式将输入值与重复变量 var 相关联.现在您没有在任何地方这样做并且基本上将所有输入值绑定到一个相同的 bean 属性.因此,当表单被提交时,每次迭代都会用当前迭代轮次的值覆盖 bean 属性,直到您最终获得上一轮迭代轮次的值.这绝对是不对的.

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

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

与:

私人地图<问题,字符串>selectedOptions = new HashMap<>();

不管是哪种方法,在action方法中,只要迭代它就可以收集它们.

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

The simplest way would be to directly associate it with the object represented by 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):

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

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

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