Play Framework Form Error Handling

1.4k views Asked by At

This is my view file containing the form that has to filled in by the user:

@helper.form(call) {
    @helper.input(resumeForm("surname"), '_label -> "Surname") { (id, name, value, args) =>
        <input name="@name" type="text" value="@value" placeholder="Enter your surname">
    }
}

This is my custom field constructor:

@(elements: helper.FieldElements)

@if(!elements.args.isDefinedAt('showLabel) || elements.args('showLabel) == true) {
    <div class="input-with-label text-left">
        <span>@elements.label</span>
        @elements.input
    </div>
} else {
    @elements.input
}

Now I have a dilemma. When the entered value doesn't clear validation, I need to add the class field-error to the input and I need to add data-toggle, data-placement and title. However, I don't know of any way to check if there are errors for the specific field. What is the best way to implement this? I already looked at using inputText or something but that is basically the same as the base input thus also does not have access to any errors. I'm also unable to alter the HTML of the elements.input inside the field constructor.

1

There are 1 answers

2
Alexander B On BEST ANSWER

Have a look at play documentation: Writing your own field constructor. You can check on errors with @if(elements.hasErrors) within the template of your custom field constructor.

<div class="input-with-label text-left @if(elements.hasErrors){field-error}">
    ...

Edit:

You can pass the error state of your field via the args parameter to your input. From the play docs:

Note: All extra parameters will be added to the generated HTML, except for ones whose name starts with the _ character. Arguments starting with an underscore are reserved for field constructor argument (which we will see later).

You need to cast to the matching type though.

@input(resumeForm("surname"), '_label -> "Surname", 'hasErrors -> resumeForm("surname").hasErrors) { (id, name, value, args) =>
    <input name="@name" type="text" value="@value" placeholder="Enter your surname"
        class="@if(args.get('hasErrors).map(_ match { case x:Boolean => x}).get){field-error}">
}