Zend framework 2 在表单字段旁边添加删除按钮

Zend framework 2 add remove button next to form field

我现在有这个:

它是用这个代码生成的:

$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)
    )
));

我想在每个表单域旁边添加一个删除按钮,这样我也可以删除附件。我该怎么做?

使用集合时,指定 allow_addallow_remove 不会告诉 ZF 创建适当的按钮,只是告诉集合可以包含任意数量的元素(由 [=15= 指定的最小值) ]).

将集合添加到表单后,您还需要添加一个按钮,单击该按钮会调用一个函数以根据模板添加另一个元素。

来自手册:

<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>