2016-12-09 30 views
1

我有這樣的時刻: form fieldZend框架2添加刪除下一個按鈕,以形成場

它使用此代碼生成:

$this->add(array(
    'type' => 'Zend\Form\Element\Collection', 
    'name' => 'attachments', 
    'options' => array(
     'count' => 1, 
     'should_create_template' => true, 
     'allow_add' => true, 
     'allow_remove' => true, 
     'target_element' => new AttachmentFieldset($this->entityManager) 
    ) 
)); 

我想下一個加去除按鈕每個表單字段,所以我也能夠刪除附件。我怎樣才能做到這一點?

+0

嗨!您的問題在官方文檔中有適當的答案:https://framework.zend.com/manual/2.4/en/modules/zend.form.collections.html#adding-new-elements-dynamically。要麼你沒有看到,要麼你有更具體的問題,所以請添加詳細信息,以幫助我們更多! –

回答

0

使用集合時,指定allow_addallow_remove不會告知ZF創建適當的按鈕,只是該集合可能包含任意數量的元素(最小值由count指定)。

將集合添加到表單後,您還需要添加一個按鈕,單擊該按鈕時會調用一個函數以添加基於模板的其他元素。

從手冊:

<button onclick="return add_category()">Add a new category</button> 

<script> 
    function add_category() { 
     var currentCount = $('form > fieldset > fieldset').length; 
     var template = $('form > fieldset > span').data('template'); 
     template = template.replace(/__index__/g, currentCount); 

     $('form > fieldset').append(template); 

     return false; 
    } 
</script> 

要添加刪除按鈕,改變上述功能的按鈕添加到模板中,並創建一個刪除功能:

<script> 
    function add_category() { 
     var currentCount = $('form > fieldset > fieldset').length; 
     var template = $('form > fieldset > span').data('template'); 
     template = template.replace(/__index__/g, currentCount) 
          .replace('</fieldset>', '<button onclick="return remove_category(this)">Remove</button></fieldset>'); 
     $('form > fieldset').append(template); 

     return false; 
    } 
    function remove_category(el) { 
     $(el).parent().remove(); 
    } 
</script>