Issues

ZF-4140: Zend_Form_Element_File - No validation / upload when required isn't set (or false)

Description

It is not possible at the moment to create an upload element. When I set required = false, the file is not uploaded and there is no validation. When I set required = true a file is needed. It is not possible to set the form element optional.

Requirements for my form:

Image is optional. Image are upload ->validate this. Image not uploaded -> ignore image.

Here's my config ini:

news.create.elements.image.type = "file" news.create.elements.image.options.label = "Bild" news.create.elements.image.options.validators.size.validator = "Size" news.create.elements.image.options.validators.size.options = "20MB" news.create.elements.image.options.validators.mimetype.validator = "Mimetype" news.create.elements.image.options.validators.mimetype.options = "image/gif,image/jpeg,image/png" news.create.elements.image.options.required = false

My php:

$config = Zend_Registry::get ('config'); $form = new My_Form ($config->news->create); $form->image->setDestination (ROOT_DIR . '/public/images/neuigkeiten');

if ($this->_request->isPost ()) { $formData = $this->_request->getPost ();

    if ($form->isValid ($formData)) {
              ...
  } else {
                $form->populate ($formData);
   }

}

Comments

To validate only the file we are interesting in ( $this->getName() ) and return true if : 1 : the validation only failed because no file were uploaded (Zend_Validate_File_Upload::NO_FILE ) AND 2 : the file were not required (isRequired() == false)

Also clean the error ( $adapter->clearErrors() ) so no error message will be displayed on the form for a non required file input.

Sorry, the last one is wrong. This one is good.

Just add the "clearErrors()" so we can remove the "NoFile" error on a non required file input.

Please try r11258 and see if it fit's your needs.

Problem was solved differenty as the underlaying feature is not only related to HTTP POST.

Almost.

In Form_Element_File, we should only try to receive the file that we are actualy validation, otherwise, if you mixed required and not require file input in the same form, the validation will fail on the required file.

Index: Form/Element/File.php

--- Form/Element/File.php (revision 11259) +++ Form/Element/File.php (working copy) @@ -272,7 +272,7 @@ } }

  • if($adapter->receive($value)) {
  • if($adapter->receive($this->getName())) { return true; }

And, in File_Transfer_Adapter_Abstract, just a little fix :

Index: File/Transfer/Adapter/Abstract.php

--- File/Transfer/Adapter/Abstract.php (revision 11259) +++ File/Transfer/Adapter/Abstract.php (working copy) @@ -506,7 +506,7 @@ } }

  • if ($this->_options['ignoreNoFile'] and (isset($this->_messages['fileUploadErrorNoFile']))) {
  • if ($this->_options['ignoreNoFile'] and (isset($fileerrors['fileUploadErrorNoFile']))) { $fileerrors = array(); }

Thank you!