我正在构建某种测验,用户可以在其中得到一个问题和几个可能的答案。答案列在单选组中,并且可能重复!
示例:
How tall is tall?
- Very!
- Depends on your definition!
- Very!
问题和答案来自列表并保存在数据库中。 根据用户是否点击了正确的答案,该答案将获得新的分数。
我现在的问题是:我可以获取单击的单选按钮的文本,但无法获取/查看 Controller 中匹配答案的 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>
用户单击单选按钮,然后在 Controller 中我绑定(bind)表单中的答案:
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传输到 Controller 吗?或者以其他方式查看/获取它?
最佳答案
您应该确保您的输入选项具有唯一值,因为助手会自动将输入 ID 生成为“Classname_value”,并使用值属性来提交表单。在您的示例中,这将导致两个输入字段的 id_attribute“Answer_Very!”和相同的值属性,因为您使用answerText作为值而不仅仅是作为标签。
尝试更改选项序列的键,该序列会将输入元素的值属性转换为唯一的内容,例如 answer.answerID
@helper.inputRadioGroup(
answerRadioForm("Answer"),
options = answerList.map(answer => answer.answerID -> answer.answerText)
)
关于java - 如何获取 helper.form 中单选组中项目的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30766407/