Question

In play framework, is it possible to reject a field

filledForm.reject("myField", "You are missing files");
return badRequest(myform.render(filledForm));

without reloading the page?

I have a file input field which lets users select files. On the reject and reload, the files are cleared and the error is displayed. I want the files they selected to be there

Current behaviour: Before submit form:

Before

After submit (with error: files are gone)

Before

Was it helpful?

Solution

File select input fields (i.e. <input type="file" ... />) are different from other input fields -- you can't pre-populate the value from the server side. It would be a massive security hole if you could (think of <input type="file" value="/etc/passwd" .. />). At the server, when you get the submitted form, you don't get the full path to the file that was uploaded, just the name of the file and the contents.

If you really need to preserve the value of your file input field, you will need to go a different route: submit the form via Ajax (google for "ajax file upload" for some techniques and libraries to help with this), and use the Ajax response to indicate if the file was valid or not.


Further clarification: With the normal HTML/HTTP post method (which the Play forms helpers use), the original page is gone, and the server response is a new page with no connection to the previous page. The Play forms helpers will pre-populate the input fields on this page with the previous values, but as explained above this is not possible for a file input field.

This is why there are special-purpose Javascript libraries for uploading files. If your form is primarily concerned with doing file uploads, you should look at these. (e.g. http://fineuploader.com). On the server side, the target of the Ajax query will be a new Action that just processes the uploaded files and returns a success/failure message, which you would then display to the user.

OTHER TIPS

If server would be able to manipulate the value of a file field, that would be a major security risk as we could take any file from the user hard drive. If we look at the two requirements you have,

  • Get file contents on the server
  • Do not disturb client UI state

the only option is to use an AJAX file uploader. So your flow now becomes:

  • Submit the file via AJAX upload
  • Validate the contents
  • Save the file for later retrieval
  • Send back the status (OK or Error)
  • Display the error on Error
  • After the whole form is submitted, look up the previously saved file

You can probably cheat a bit if you don´t mind the load - just do the validation with AJAX to display the error message and let the file be uploaded again on a normal submit.

It`s all about working with the limits we have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top