【问题标题】:Zend framework 2 add remove button next to form fieldZend framework 2 在表单字段旁边添加删除按钮
【发布时间】:2024-05-18 06:15:01
【问题描述】:
我现在有这个:
它是用这段代码生成的:
$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)
)
));
我想在每个表单字段旁边添加一个删除按钮,这样我也可以删除附件。我该怎么做?
【问题讨论】:
标签:
php
forms
zend-framework
zend-framework2
templatefield
【解决方案1】:
使用集合时,指定allow_add 或allow_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>