2015-10-29 71 views
0

我想創建以下元素:如何創建形式的數組元素 - Zend框架2

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

我試圖在myproject的/模塊/會員/ SRC /會員/窗體/ 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 
      ), 
     )); 

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

,但它無法正常工作。

回答

4

用於文件上傳Zend Framework 2 has a special FileInput class

使用這個類很重要,因爲它也可以做其他重要的事情,如validation before filtering。還有special filters like the File\RenameUpload爲您重命名上傳。

考慮到$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' 
); 

要文件中的元素附加到形式:

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

檢查the documentation有關文件上傳的更多信息。 或者查詢the documentation here如何進行上傳表格

+0

感謝您的回覆。 我試過了你的代碼,但遇到了錯誤: 發生了錯誤 執行過程中發生錯誤;請稍後再試。 其他信息: 的Zend \表格\異常\ InvalidElementException 文件: /var/www/html/actifiti/admin/vendor/ZF2/library/Zend/Form/FormElementManager.php:121 消息: 類型的插件Zend \ InputFilter \ FileInput無效;必須實現Zend \ Form \ ElementInterface –

+0

@ErFaiyazAlam $ this'在這種情況下是一個'InputFilter'類。嘗試添加到您的輸入過濾器實例,而不是您的表單。 – Wilt

+0

@ErFaiyazAlam我編輯了我的答案並添加了更多鏈接和示例。有很多關於文件上傳的文檔。 – Wilt