简体   繁体   中英

play.data.Form - How best to fill default form values

Trying to add a filter form to a standard crud 'list' page.

// set filter defaults
ImageFilter defaultFilter = new ImageFilter();
defaultFilter.setYear(currentYear);
defaultFilter.setColor(user.getFavouriteColor());

// get filter for view
Form<ImageFilter> form = Form.form(ImageFilter.class).fill(defaultFilter).bindFromRequest();
ImageFilter filter = form.get()
  • bindFromRequest() alone gets a form with the filters a user specified, but on first load the fields have no selected value
  • fill(defaultFilter) alone does provide a form with the default filters selected
  • chained in this way the behaviour is just identical to the behaviour of the one called last.

What is the appropriate way to set the defaults?

Ideally, on the index page:

  • the default filter selection when not given any parameters
  • if requested with ?year=2010&color=blue those filters show on the form
  • if requested with ?year=2010 the form shows 2010 and the user's favourite color

Check if default values are present then go with the flow. If not present, add set it in filter or render on UI using querystring params.

You can achieve what you want by splitting your code into two actions.

In the first one you fill a form with the default filter and display it to a user.

public static Result show() {
    ImageFilter defaultFilter = new ImageFilter();
    defaultFilter.setYear(currentYear);
    defaultFilter.setColor(user.getFavouriteColor());
    Form<ImageFilter> form = Form.form(ImageFilter.class).fill(defaultFilter);

    return ok(index.render(form));
}

In the second action you simply bind form values from the request. If user changes some values form will be filled with them along with unchanged ones set as the defaults.

public static Result handle() {
    Form<ImageFilter> form = Form.form(ImageFilter.class).bindFromRequest();
    ImageFilter filter = form.get();
    return ok("TODO handle form");
}

Edit

If you want to fill missing fields with the defaults after user input without showing them in the view before submit I'm afraid you'll have to do it manually after binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM