Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2 Bind form from request

I am new to Play2 (I've already developed a project using Play1) and I have problems with form binding from request. The documentation about forms is really light.

Here is the code of my controller :

private final static Form<Estimation> estimationForm = form(Estimation.class);

/**
 * Get an estimation by form
 * @return
 */
public static Result estimation() {
    return ok(views.html.rate.estimation.render(
        estimationForm,
        City.findAll()
    ));
}

/**
 * Display estimation results
 * @return
 */
public static Result results() {
    if (request().method().equals("POST")) {
        Form<Estimation> form = estimationForm.bindFromRequest();
        if (form.hasErrors()) {
            System.out.println(form.errorsAsJson().toString());
            return ok(views.html.rate.estimation.render(
                form
                City.findAll()
            ));
        }
        else {
            System.out.println(form.get());
            return ok(views.html.rate.results.render(

            ));
        }
    }
    else {
        return estimation();
    }
}

I display cities in a select as this :

<select id="city" name="city">      
    <option value="1">Paris, France</option>
    <option value="2">Lyon, France</option>
    <option value="3">Marseille, France</option>
    <option value="4">Barcelona, Spain</option>
    <option value="5">Berlin, Germany</option>
</select>

When I submit the form, I have the following error : {"city":["Invalid value"]}

So here is my question : The binder seems to work well with simple fields (for example a String property in my model), but what about @ManyToOne relationships ?

Thank you.

like image 693
c4k Avatar asked Aug 26 '12 18:08

c4k


1 Answers

Set the name of the select field as name="city.id"

like image 115
biesior Avatar answered Sep 28 '22 09:09

biesior