File Input Hidden Field

When using a file input in a form Yii creates a hidden input like so:




    <input type="hidden" value="" name="Section[image]">



This input never has a value, even when the form is in edit mode and we do actually have a value.

What is the purpose of this hidden field? To me it looks like a lousy hack.

I suspect it’s there so that you get a value for that attribute even when no file is uploaded. If a file is uploaded, that form field will be overridden by the actual file name in the POST data.

Yii does a similar thing with checkboxes, so you can ensure that the attribute always has a value which can be used in validation rules.

It never has a value and there is no way to give it a value.

I have often seen hidden fields like this on update forms, however they always have a value if there is an existing record.

Again, I think it’s there for another reason and still looks like a hack.

I’ve put some simple examples together, mainly to check that I understood correctly, but they may make it clearer.

Here’s basic PHP code with just a file field:




<?= var_dump($_POST); ?>


<form action="" method="POST" enctype="multipart-formdata">

    <input type="file" name="file" />

    <input type="submit" value="GO" />

</form>



With a file selected, the var_dump of the POST array looks like this:




array (size=1)

  'file' => string 'test.txt' (length=<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />



Without a file selected, the var_dump of the POST array looks like this:




array (size=0)

  empty



There’s no way to tell that that field was even submitted.


Now compare the following code, which adds a hidden input:




<?= var_dump($_POST); ?>


<form action="" method="POST" enctype="multipart-formdata">

    <input type="hidden" name="file" value="" />

    <input type="file" name="file" />

    <input type="submit" value="GO" />

</form>



If I submit with a file selected:




array (size=1)

  'file' => string 'test.txt' (length=<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />



But, without a file selected:




array (size=1)

  'file' => string '' (length=0)



Now we can tell that the file was submitted as part of the form but was left empty.

If your form only contains file fields and you rely on checking whether $_POST[‘ModelName’] is set, then the first version will not be able to tell that the form was submitted if no file is selected, so will not run any validation. The second version will see that the form was submitted and validate the missing file, in turn giving a useful error message to the user.