InputFilter" setRequired"不适用于html5倍数

时间:2014-03-30 15:55:37

标签: forms zend-framework2 multifile-uploader zend-inputfilter

我很难处理fileinput的奇怪行为。 这是我的表格:

namespace Frontend\Form;

use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;

use Zend\ServiceManager\ServiceManagerAwareInterface;

class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;

public function __construct($name=null) {

    parent::__construct("frmEnrollStructure");
    $this->setAttribute("action", "/registrazione_struttura/submit")
        ->setAttribute('method', 'post')
        ->setAttribute("id", "iscrizione_struttura")
        ->setAttribute("class", "form fullpage");
    $this->addInputFilter();
}

public function init()
{
    $structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
    $structureFs->setUseAsBaseFieldset(true);

    $structureFs->remove("id")
        ->remove("creationTime")
        ->remove("latLon");

    $file = new Element\File("images");
    $file->setAttribute('multiple', true);

    $this->add($structureFs)->add($file);

    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type' => 'submit',
            'value' => 'Iscriviti',
            'id' => 'sbmtEnrollStructure',
            'class' => 'submit_btn'
        ),
    ));

    $this->setValidationGroup(
        array(
        'structure' =>
            array(
                'companyname',
                'vatNumber',
                'addressStreet',
                'addressZip',
                'addressCity',
                'addressRegion',
                'fax',
                'publicPhone',
                'publicEmail',
                'website',
                'status',
                'ownerNotes',
                'category',
                'subcategory',
                "facilities",
                "agreeOnPolicy",
                "agreeOnPrivacy",
                "subscribeNewsletter",
                "contact" => array("name", "surname", "email", "role", "phone"),
            ),
            "images"
    ));

}

/**
 * Set service manager
 *
 * @param ServiceManager $serviceManager
 */
public function setServiceManager(ServiceManager $serviceManager)
{
    $this->sm = $serviceManager;
}

public function addInputFilter()
{
    $inputFilter = new InputFilter\InputFilter();
    // File Input
    $fileInput = new InputFilter\FileInput('images');
    $fileInput->setRequired(true);

    $fileInput->getValidatorChain()
        ->attachByName('filesize',      array('max' => "2MB"))
        ->attachByName('filemimetype',  array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
        ->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));

    $inputFilter->add($fileInput);

    $this->setInputFilter($inputFilter);
}



}

基本上,我主要使用的字段集包含我向用户请求的大部分数据,以及文件输入字段。

这是Fieldset结构:(最重要的部分......)

 use Zend\Form\Element;
 use Zend\Form\Fieldset;
 use Zend\InputFilter\InputFilterProviderInterface;

 use Zend\ServiceManager\ServiceManager;
 use Zend\ServiceManager\ServiceManagerAwareInterface;
 use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
 use Zend\Validator\Identical;
 use Zend\Validator\NotEmpty;
 use Zend\Validator\Regex;
 use Zend\Validator\StringLength;


class Structure extends Fieldset implements InputFilterProviderInterface,    ServiceManagerAwareInterface
{
protected $sm;

public function __construct()
{
    parent::__construct('structure');
}

public function init()
{
    $this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
    $this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
    $id = new Element\Hidden("id");

    $name = new Element\Text("companyname");
    $name->setLabel("Ragione Sociale");

       ...........
}

public function getInputFilterSpecification()
{
    return array
    (
        "id" => array(
            "required" => false,
        ),
        "companyname" => array(
            "required" => true,
            "validators" => array(
                array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
            ),
        ),
      .....
 }

}

这是我的控制者:

    public function submitAction()
{
    try {
        $this->layout("layout/json");

        $form = $this->getForm('Frontend\Form\EnrollStructure');
        //$form->addInputFilter();
        $structure = $this->getServiceLocator()->get("Structure_Structure");

        $viewModel = new ViewModel();
        $request = $this->getRequest();

        if ($request->isPost())
        {
            $post = array_merge_recursive
            (
                $request->getPost()->toArray(),
                $request->getFiles()->toArray()
            );

            $form->setData($post);

            if ($form->isValid())
            {
                $structure = $form->getObject();
                $contact = $structure->getContact();
                $this->getServiceLocator()->get('Structure_ContactService')->save($contact);
                $files = $request->getFiles()->toArray();

                if(isset($files['images']))
                {
                    $count = 3;
                    foreach($files['images'] as $pos => $file)
                    {
                        $fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
                        if(!empty($fpath))
                        {
                            if(--$count ==0) break;
                            $asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
                            $this->getServiceLocator()->get("Application_AssetService")->save($asset);
                            $structure->addImage($asset);
                        }
                    }
                }

                $this->getServiceLocator()->get('Structure_StructureService')->save($structure);
                $retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
            }
            else
            {

                $messages = $form->getMessages();
                if(empty($messages))
                    $retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
                else
                    $retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
            }


            $viewModel->setVariable("retcode", $retCode);
            return $viewModel;
        }
    } catch(Exception $e)
    {
        throw $e;
    }
}

奇怪的是,如果我从字段“images”中删除“multiple”属性一切正常,导致表单无法验证,我收到此消息:

    [images] => Array
    (
        [fileUploadFileErrorFileNotFound] => File was not found
    )

然而,如果我将属性设置为多个,并且用户没有上传文件我没有得到任何错误,但表单无效(这就是我的控制器中这个“坏”代码的原因:)

     $messages = $form->getMessages();
                if(empty($messages))
                    $retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
                else
                    $retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);

1 个答案:

答案 0 :(得分:0)

我发现问题是由Jquery表单插件引起的,没有它它可以正常工作。 :(如果有人需要,我认为可以在这里找到正确的行动代码(无论如何我还没试过) https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php