我在我的表单中设置了一个fieldset(集合),我想要允许添加和删除元素..所以,我的代码是:
$hydrator = new Hydrator($this->getObjectManager(), 'Base\Entity\MyElements');
$fieldset = new MyElements();
$fieldset->setObjectManager($this->getObjectManager())
->setHydrator($hydrator)
->setObject(new \Base\Entity\MyElements())
->init();
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'myElements',
'options' => array(
'label' => 'My Elements',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'allow_remove' => true,
'target_element' => $fieldset
)
));
我可以添加元素,但是,删除按钮不会出现..我做错了或遗忘了什么?
PS:我的英语很差,但我正在努力改进它。抱歉。谢谢答案 0 :(得分:5)
allow_remove选项不会直接添加按钮。记住allow_add也没有添加按钮。正如您在the docs中看到的那样,您必须添加按钮
<button onclick="return add_category()">Add a new category</button>
和js函数添加元素:
<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>
完全如此,您必须添加删除按钮
<button onclick="return remove_category()">Remove</button>
和功能:
<script>
function remove_category() {
//write your logic to remove the last, or the current element, for isntance:
$('form > fieldset > fieldset').last().remove();
return false;
}
</script>