tags:

views:

199

answers:

4

I have a form with text inputs and file inputs; the text fields are being validated. Is there a way to have the form remember which files the user has already selected if they hit submit but need to go back because one of the text fields didn't validate?

A: 

Hi Brandon,

I would suggest an alternative method: validate the text inputs with AJAX before submission.

That will improve the usability of your forms, too.

rossmcf
A: 

files input fields are read-only you can't set an initial value for them

mck89
A: 

You can upload the Files anyway and display the filenames instead of the file select box. To remember the fields, you can use a $_SESSION variable.

Fu86
+3  A: 

You can't "pre-fill" the contents of a file upload field for security reasons. Also, that would mean the file would get re-uploaded every time the form is submitted, which would not be good.

Instead, do this:

  • Create a file upload field with name file_upload.
  • On the server-side, process the upload in any case, even if the rest of the form validation fails.
  • If the form validation failed, but the file was uploaded, insert a hidden input into the form with name file containing the name of the just uploaded file.
  • Display a user-visible indication that the file is okay. If it's an image, display a thumbnail version of it. If it's any other file, display its filename and/or icon.
  • If the user chooses to upload a different file in the file_upload field, process the upload and store the new value in file.

Pseudocode:

<?php
    $file = null;
    if (!empty($_POST['file'])) {
        $file = $_POST['file'];
    }
    if (!empty($_POST['file_upload'])) {
        // process upload, save file somewhere
        $file = $nameOfSavedFile;
    }

    // validate form
?>


<input type="file" name="file_upload" />
<input type="hidden" name="file" value="<?php echo $file; ?>" />
<?php
    if (!empty($file)) {
        echo "File: $file";
    }
 ?>
deceze
Thanks, I'm using the Codeignitor framework and I'm new to it but I'll try to implement this somehow.
Brandon
Works now, it was easier to do in CI than I thought.
Brandon