开发者

Symfony forms - remembering a previously selected file

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

If the form is not valid, I present it again to the user, to correct 开发者_JS百科the erroneous field(s).

The problem I am experiencing is that currently, when the foem fails to validate (for whatever reason), the picture file that was specified by the user is lost (i.e. they have to select the file again).

How can I show the form to the user again, with the selected picture file still there (so they dont have to select the file again)?

In my action that process the POSTed form, I call getFiles($key) and then index the retrieved array to get the file information, and setting the default value of the widget (see below). However, the rendered widget is empty (does not retain the value of the pathname to the previously selected file.

A snippet of my (action) code looks like this:

$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?


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

The user needs to implicitly choose the file every time he/she submits the form. The solution Tomas proposes is a good one. Store the file to a temp folder, store this information in the session (so you can show this in your form again somewhere) and after a succesfull form submittal clear the session info for the file and move the file to the right 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


I don't think you can save the state of a file upload control. And I don't think you should.

You could upload the files before the rest of the form is processed. Thus you split the process in two:

  1. File validation
  2. Form validation

If the form validation fails and the user does not attempt to re-submit it using correct information, you discard the files later. This adds some overhead but improves the user experience in my view. The user can mistakenly enter wrong data but as you reload the page with appropriate instructions, the files are still there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜