Symfony Forms - Remembering a Previously Selected File

I am using Symfony 1.3.2 on Ubuntu, and I have a form containing several widgets. One widget is sfWidgetFormInputFile, which allows the user to select an image.

If the form is invalid, I submit it to the user again to correct the error field.

The problem I ran into is that currently, when foem fails to verify (for some reason), the image file that was specified by the user is lost (i.e. he must select the file again).

How can I show the form to the user again, with the selected image file still there (so that they don’t need to select the file again)?

In my actions processing the POSTED form, I call getFiles ($ key) and then index the resulting array to get the file information and set the default value for the widget (see below). However, the rendered widget is empty (does not save the value of the path name to the previously selected file.

An excerpt from my (action) code is as follows:

$files = $request->getFiles('foobar'); if(!empty($files) && isset($files['pict_path'])){ $pic_info = $files['pict_path']; $originalName =$pic_info['name']; $type = $pic_info['type']; $tempName = $pic_info['tmp_name']; $size = $pic_info['size']; $pict_file = new sfValidatedFile($originalName, $type, $tempName, $size); $this->form->setWidget('pict_path', new sfWidgetFormInputFile(array('default'=>$pict_file))); } 

Can anyone suggest how to correctly implement the desired behavior described above?

+4
source share
2 answers

The value attribute of the html input tag (with type = "file") is read-only. You cannot set a default value. This will allow you to upload any user hard drive file to your server by setting the value of the input tag.

The user must implicitly select a file each time he submits a form. The solution proposed by Thomas is a good one. Store the file in the temp folder, store this information in the session (so you can show it again in your form somewhere), and after the succesfull form submittal clears the session information for the file and move the file to the desired destination.

See this page, B.10.1 Security Issues for Forms on the W3C website: http://www.w3.org/TR/html401/appendix/notes.html#forms-security

+2
source

I do not think that you can save the state of file upload control. And I do not think you should.

You can upload files before the rest of the form is processed. Thus, you break the process into two:

  • File check
  • Form validation

If the form check fails and the user does not try to resubmit it using the correct information, you will release the files later. This adds some overhead, but improves the user experience in my view. The user may erroneously enter incorrect data, but when the page is reloaded using the appropriate instructions, the files still exist.

0
source

Source: https://habr.com/ru/post/1308985/


All Articles