2012-10-25 23 views
1

ZF2添加了formCollection,它讓我們在頁面加載後動態添加formElementZF2 - 動態輸入量(無JavaScript)

我有每個人都應該有這樣一個文本框行的動態量的表:

foreach ($types as $type) : 
    ?> 
    <tr><td><?php echo $type ?></td><td><?php echo $this->formRow($form->get('amount')); ?></td></tr> 
    <?php 
endforeach; 

我通過循環項目的排列和打印的行/列我的表,但似乎formCollection只允許您一次打印所有的字段。

是否有可能打印每個循環的文本字段之一?所有文檔都會介紹如何使用模板和JavaScript動態添加元素。但我基本上只想要一些我已經知道的數量的輸入。

看來我不能在我的控制器中更改它們的count。嘗試這樣:

$types = array(1,2,3,4,5) 
$form = new ThingsForm(); 
$form->get('amounts')->setOptions(array(
    'count' => count($types) 
)); 

我嘗試了具有收集count => 1,然後打印很多人,但是當你填寫他們只被當作一個項目。

回答

1

短,更多有用的版本:

$form->get('amounts')->setCount(count($types))->prepareFieldset(); 
+0

邪惡,謝謝:)我的版本是真髒 –

0

看起來就像我已經破解了,這是不容易的,所以我的問題,如果這是推薦的方式,或者如果它是一個未想到的用例組成:

集合項目:

$this->add(array(
     'type'  => 'Zend\Form\Element\Collection', 
     'name' => 'amounts', 
     'options' => array(
      'allow_add' => true, 
      // Has to be 0 as you set the count later (and that adds) 
      'count' => 0, 
      'target_element' => array(
       'type' => 'Application\Form\AmountForm' 
      ) 

     ), 
     'required' => true, 
    )); 

抓住形式和設置內部計數像控制器操作的地方:

$form = new AmountTypesForm(); 
$form->get('amounts')->setOptions(array(
    'count' => count($typesOfThings) 
))->prepareFieldset(); 

環路內視圖

foreach ($types as $type) : 
    ?> 
    <tr><td><?php echo $type ?></td><td><?php echo $this->formRow($form->get('amount')->getIterator()->extract()); ?></td></tr> 
    <?php 
endforeach;