Play Framework验证:重新显示输入

时间:2012-08-31 16:05:39

标签: java error-handling playframework playframework-1.x

我创建了一个输入表单。当用户提交值并且未通过验证时,如何从用户显示原始值?我可以正确地看到声明“字段是必需的”验证错误消息。它转发回输入表单并显示验证错误,但不保存用户输入的值。

模特

@Entity
public class Question extends BaseModel {

    @Required
    @MaxSize(100)
    public String title;
    @Required
    @MaxSize(5000)
    public String txt;
}

控制器

public class Questions extends Controller {

    public static void ask() {
        Question question = new Question();
        render(question);
    }

    public static void addQuestion(Question question) {
        // save question
        if (!question.validateAndSave()) {
            params.flash();
            Validation.keep();
            ask();            
        }
        Application.index();
   }
}

视图

#{form @exchange.Questions.addQuestion()}

  <label class="control-label" for="question.title">Question Title</label>
  <input type="text" class="input-large" name="question.title" value="${question.title}" />
  #{if errors.forKey('question.title')}<span class="alert-error"> #{error 'question.title'/}</span> #{/if}

  <label class="control-label" for="question.txt">Details</label>
  <textarea class="input-xxlarge span7" rows="6" name="question.txt">${question.txt}</textarea>
  #{if errors.forKey('question.txt')}<br/><span class="alert-error"> #{error 'question.txt'/}</span> #{/if}
  <button type="submit" class="btn btn-primary">Ask Question</button> 

#{/form}

1 个答案:

答案 0 :(得分:1)

当您致电Params.flash时,会将您在表单中提交的值添加到Flash Cookie中。因此,在您的视图中,您可以通过执行以下操作来访问值

特别注意使用flash来获取表单字段的值。

#{ifErrors}
   <h1>Oops...</h1>
#{/ifErrors}

#{form @Application.hello()}
   <div>
      Name: <input type="text" name="name" value="${flash.name}" />
      <span class="error">#{error 'name' /}</span>
   </div>
   <div>
      Age: <input type="text" name="age" value="${flash.age}" /> 
      <span class="error">#{error 'age' /}</span>
   </div>
   <div>
      <input type="submit" value="Say hello" /> 
   </div>
#{/form}