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

时间:2016-12-09 09:21:15

标签: php forms zend-framework zend-framework2 templatefield

我现在有这个: 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)
    )
));

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

1 个答案:

答案 0 :(得分: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>