如何获取 helper.form 中单选组中项目的 ID?

How can I get the ID of an item in a radio-group in a helper.form?

我正在构建某种测验,用户可以在其中得到一个问题和几个可能的答案。答案列在一个单选组中,可能 重复 !

示例:

How tall is tall?
- Very!
- Depends on your definition!
- Very!

问题和答案来自列表并保存在数据库中。 根据用户是否点击了正确的答案,答案会得到一个新的分数。

我现在的问题是:我可以获取单击的单选按钮的文本,但无法获取/查看控制器中匹配答案的 ID。我该怎么做?

quiz.scala.html:

@import models.Question
@import models.Answer

@import helper._
@import helper.twitterBootstrap._

@(questionList: List[Question], answerList: List[Answer], answerRadioForm: Form[Answer])
@helper.form(action = routes.Application.nextQuizPage(), 'id -> "answerRadioForm"){
            <fieldset>
                @helper.inputRadioGroup(
                answerRadioForm("Answer"),
                options = answerList.map(answer => answer.answerText.toString -> answer.answerText),
                '_label -> "answer",
                '_error -> answerRadioForm("Answer").error.map(_.withMessage("select answer"))
                )
            </fieldset>

        <button type="submit" class="btn btn-default" value="Send">
            Next question
        </button>

用户点击单选按钮,我在控制器中绑定表单中的答案:

Application.java:

Form<Answer> filledForm = answerForm.bindFromRequest();
// I try to find the answerID my matching the answerText, 
// which is really unreliable - think of 2 answers with the same answerText ...
List<Answer> findAnswerList = Answer.find
                                    .where()
                                    .like("answer_text", filledForm.data().get("Answer").toString())
                                    .findList();

Answer.java(型号中):

@Entity
public class Answer extends Model implements Comparable<Answer>{
    // The questionID is needed to somehow link the answer to a question, as an answer can not be without one
    @Id
    public String answerID;
    public String questionID;
    public String answerText;
    public Integer voteScore;
    public String ownerID;
    public Integer page;
}

我已尝试将 ID 字段附加到辅助表单: '_id -> answer.answerID 但我收到错误提示 "answer" 未知。

那么,有什么办法可以将 answerID 传输到控制器吗?或者以其他方式查看/获取?

您应该确保您的输入选项具有唯一值,因为帮助程序会自动生成输入 ID 作为 "Classname_value" 并使用 value-attribute 提交表单。在您的示例中,这将导致两个输入字段具有 id_attribute "Answer_Very!" 和相同的值属性,因为您将 answerText 用作值而不仅仅是标签。

尝试更改选项序列的键,将输入元素的值属性转换为唯一的值,例如 answer.answerID

 @helper.inputRadioGroup(
      answerRadioForm("Answer"),
      options = answerList.map(answer => answer.answerID -> answer.answerText)
 )