Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display error in Play Framework 2

First of all I want to state that I think that the Play documentation for 2.0 is really, really bad.

I'm looking for a way to place a validation error underneath a HTML select like play would do it for an automatically generated input box.

I tried to copy the structure of the resulting HTML code of an Play input box, but I'm sure I'm missing some ifError-Scala template line in my HTML code.

To bad it's not possible to find Play 2.0 documentation for topics already covered by the Play < 2.0 documentation. So you will land on the old, not working, documentation if you're looking for solution in the docs. Very frustrating!

like image 569
schlingel Avatar asked Jan 12 '13 13:01

schlingel


2 Answers

The answer from 2manyprojects works very well but you can do the same thing in the controller. It all depends on your preference and style.

public static Result save() {
        Form<form> boundForm = form.bindFromRequest();
        if (boundForm.hasErrors()) {
            String errorMsg = "";
            java.util.Map<String, List<play.data.validation.ValidationError>> errorsAll = boundForm.errors();
            for (String field : errorsAll.keySet()) {
                errorMsg += field + " ";
                for (ValidationError error : errorsAll.get(field)) {
                    errorMsg += error.message() + ", ";
                }
            }
            flash("error", "Please correct the following errors: " + errorMsg);
            return badRequest(detail.render(boundForm));
        }
like image 86
fishjd Avatar answered Oct 19 '22 10:10

fishjd


I use this code to display a global bootstrap alert box with on the form:

@if(form.hasErrors) {
    <div class="alert alert-error">
        <a class="close" data-dismiss="alert">x</a>
        @if(form.errors.size() > 0) {
            @for((key, value) <- form.errors) {
                @key.toString() : 
                    @for(err <- value) {
                        @err.message().toString()
                    }
            }
        } else {No error returned.}
    </div>
}

The output for an form error key-value pair is a bootstrap alert box with @key.toString() : @value.message.toString.

If you wanted to display the error at the field level instead, you would want to modify it slightly with another conditional statement for the form.errors map value so that it only triggered for the specific field. I haven't tested this, but it'd go something like:

@if(form.hasErrors) {
    @if(form.errors.size() > 0) {
        @for((key, value) <- form.errors) {
            @for(err <- value) {
                @if(err.contains("YourSelectFieldName")) {
                    @err.message().toString()
                }
            }
        }
    }
}
like image 37
2manyprojects Avatar answered Oct 19 '22 11:10

2manyprojects