0

I have a view file with this form

echo $this->Form->create('Project', array('enctype' => 'multipart/form-data'));
echo $this->Form->input('subject', array('label' => 'Task Name'));
echo $this->Form->input('Project', array('label' => 'Project Files', 'type' => 'file'));                                    
echo $this->Form->end();    

and I have a model which validate subject to be not empty.

If nothing wrong, everything is good. But, if say:

1. I go to the page
2. Click Browse button, and then choose a file
3. forget to fill out subject
4. click submit

It will trigger validation error which say subject should not be empty, but the problem is the file upload field is empty out (due to page refresh I assumed when it submit), so now if the user realize they forget to fill the subject field, they will field it out, and click submit again without realizing that, the file he try to upload has not been upload yet.

How to prevent this from happening? how can I trigger validation but it still keeping the file upload field populate?

Harts
  • 4,023
  • 9
  • 54
  • 93
  • Why don't you add the "subject" validation on JS? I am not saying to remove the validation in your model but simply adding a JS function that validates subject is not empty. – Guillermo Mansilla Feb 12 '14 at 01:22
  • @GuillemoMansilla it's not just empty validation though, there's a lot other validation and some other field(it's not just this one field). I'm just trying to keep it cakephp style. – Harts Feb 12 '14 at 01:24
  • possible duplicate of [How to keep input type=file field value after failed validation in ASP.NET MVC?](http://stackoverflow.com/questions/967916/how-to-keep-input-type-file-field-value-after-failed-validation-in-asp-net-mvc) – scrowler Feb 12 '14 at 02:11
  • You should validate on the front end **and** the backend, this is really the only way to solve this problem as you can't repopulate the value of a file input field, but if you had prevented the user leaving the page originally with Javascript, voila! – scrowler Feb 12 '14 at 02:12
  • CakePHP 2.3+ will automatically add the `required` form input attribute to form fields based on your model's validation rules. You can manually add the `required` attribute to your form fields in your view as it appears your are on a Cake version below 2.3. Refer to the [book](http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements). However, the `required` attribute will not work on IE9 and below as well as Safari. You might have to proceed with JS validation as mentioned in the comments above to overcome the browser compatibility. – jimmymadon Feb 12 '14 at 14:07

0 Answers0