简体   繁体   English

如何在表单中创建数组元素-Zend Framework 2

[英]how to create an array element in form - zend framework 2

I want to create the following element : 我想创建以下元素:

<input type="file" name="file[]">

I have tried the following code in myproject/module/Member/src/Member/Form/EditForm.php : 我在myproject / module / Member / src / Member / Form / EditForm.php中尝试了以下代码:

$this->add(array(
            'name' => 'file',
            'type'  => 'file',
            'attributes' => array(                
                'class' => 'form-control col-md-7 col-xs-12',                
                'id' => 'file',                
            ),'options' => array(
                'multiple'=>TRUE
            ),
        ));

and

$this->add(array(
            'name' => 'file[]',
            'type'  => 'file',
            'attributes' => array(                
                'class' => 'form-control col-md-7 col-xs-12',                
                'id' => 'file',                
            ),'options' => array(
                'multiple'=>TRUE
            ),
        ));

but it is not working. 但它不起作用。

For file upload Zend Framework 2 has a special FileInput class . 对于文件上传, Zend Framework 2具有一个特殊的FileInput

It is important to use this class because it also does other important things like validation before filtering . 使用此类非常重要,因为它还会执行其他重要操作,例如在过滤之前进行验证 There are also special filters like the File\\RenameUpload that renames the upload for you. 还有一些特殊的过滤器,例如File\\RenameUpload ,可以为您重命名上载。

Considering that $this is your InputFilter instance the code could look like this: 考虑到$this是您的InputFilter实例,代码可能如下所示:

$this->add(array(
    'name' => 'file',
    'required' => true,
    'allow_empty' => false,
    'filters' => array(
        array(
            'name' => 'File\RenameUpload',
            'options' => array(
                'target' => 'upload',
                'randomize' => true,
                'overwrite' => true
            )
        )
    ),
    'validators' => array(
        array(
            'name' => 'FileSize',
            'options' => array(
                'max' => 10 * 1024 * 1024 // 10MB
            )
        )
    ),
    // IMPORTANT: this will make sure you get the `FileInput` class
    'type' => 'Zend\InputFilter\FileInput'
);

To attach file element to a form: 要将文件元素附加到表单:

// File Input
$file = new Element\File('file');
$file->setLabel('My file upload')
     ->setAttribute('id', 'file');
$this->add($file);

Check the documentation for more information on file upload. 查看文档以获取有关文件上传的更多信息。 Or check the documentation here on how to make an upload form 在此处查看有关如何制作上传表单的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM