У меня есть 2 страницы, один для ввода вопросов, а один для ввода ответов. Поэтому используются 2 формы, которые отправляют свой контент (вопрос или ответ) на индексную страницу. Я также добавил вновь созданный вопрос/ответ в свою базу данных.Почему bindFromRequest использует неправильную форму?
Но странно все, что я вхожу, входит в вопросник. Это из-за опечатки где-то или bindFromRequest не работает так, как предполагалось?
класс контроллера application.java:
static List<Question> questionListAll = new ArrayList<Question>();
static List<Answer> answerListAll = new ArrayList<Answer>();
private static final Form<Question> newQuestionForm = Form.form(Question.class);
private static final Form<Answer> newAnswerForm = Form.form(Answer.class);
// Go to the ask question page
public static Result askQuestion(){
List<Question> questionHelper = new ArrayList<Question>();
for (Question questionItem : Question.find.all()) {
questionHelper.add(questionItem);
}
return ok(views.html.frageAntwort.render(newQuestionForm, questionHelper));
}
// Send the question to the indexpage
public static Result sendQuestion(){
// Create new question-form and fill it with the values from the other page
Form<Question> boundQuestion = newQuestionForm.bindFromRequest();
Question newQuestion = boundQuestion.get();
Question.create(newQuestion);
questionListAll.add(newQuestion);
return ok(views.html.index.render(questionListAll, answerListAll));
}
// Write an answer, goto answerpage
public static Result writeAnswer(){
List<Answer> answerHelper = new ArrayList<Answer>();
for (Answer answerItem : Answer.find.all()) {
answerHelper.add(answerItem);
}
return ok(views.html.antwortGeben.render(newAnswerForm, answerHelper));
}
// Send answer to indexpage
public static Result sendAnswer(){
Form<Answer> boundAnswer = newAnswerForm.bindFromRequest();
Answer newAnswer = boundAnswer.get();
Answer.create(newAnswer);
answerListAll.add(newAnswer);
return ok(views.html.index.render(questionListAll, answerListAll));
}
Мой antwortGeben.scala.html вид класса, где вы можете ввести новый ответ:
@import models.Question
@import models.Answer
@import helper._
@import helper.twitterBootstrap._
@(answerForm: Form[Answer], answerList: List[Answer])
@main("Antwort geben"){
@helper.form(action = routes.Application.sendAnswer()){
<fieldset>
@helper.inputText(answerForm("answerID"))
@helper.inputText(answerForm("questionID"))
@helper.inputText(answerForm("answerText"))
@helper.inputText(answerForm("voteScore"))
@helper.inputText(answerForm("userID"))
</fieldset>
<input type="submit" class="btn btn-default">
}
}
Мой frageAntwort.scala .html посмотреть класс, где вы можете ввести новые вопросы:
@import models.Question
@import models.Answer
@import helper._
@import helper.twitterBootstrap._
@(questionForm: Form[Question], questionList: List[Question])
@main("Frage stellen"){
@helper.form(action = routes.Application.sendQuestion()){
<fieldset>
@helper.inputText(questionForm("questionID"))
@helper.inputText(questionForm("questionText"))
@helper.inputText(questionForm("voteScore"))
@helper.inputText(questionForm("userID"))
</fieldset>
<input type="submit" class="btn btn-default">
}
}
Мой routes.conf:
# Home page
GET / controllers.Application.index()
#Questions
GET /FrageStellen controllers.Application.askQuestion()
POST / controllers.Application.sendQuestion()
#Answers
GET /AntwortGeben controllers.Application.writeAnswer()
POST / controllers.Application.sendAnswer()
Так что, когда я иду на страницу, где вы можете ввести новый ответ, я печатаю в форме answerID, ... и когда я нажимаю кнопку, каждый вход входит в вопросник в моей БД.
У меня уже есть googled для решения. Я также сделал activator clean ... activator compile ... activator run
и очистил в своей среде Scala IDE (Eclipse).
Использование play framework 2.3.8 и Scala IDE 4.0.0.
Почему каждый вход входит в мою таблицу вопросов в БД?
Вы действительно правы, когда я меняю маршрут, он работает правильно. Дело в том, что я хочу перейти на мой index.scala.html ... в основном: 'mysite.com/ = index ... пользователь нажимает кнопку для нового вопроса, получает перевод на ' mysite.com/enterQuestion. .. пользователь вводит вопрос и обращается в "submit", получает перевод на mysite.com/ = index' С этим пользователь переходит к 'mysite.com/Antwort' вместо' mysite.com/ = index' ... любая идея, как это сделать? – hamena314
@ hamena314 В этом случае я бы сделал следующее: после того, как вы поместили свои новые данные вопроса в базу данных, вместо использования 'return ok (...)' try' return redirect (controller.routes.Application.index()) '- пользователь будет перенаправлен на' mysite.com/ = index' – Anton