It's generated with this code:
$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)
)
));
I'd like to add a removal button next to each form field so I'm also able to remove attachments. How can I do this?
When using a collection, specifying allow_add
or allow_remove
does not tell ZF to create the appropriate buttons, only that the collection may contain any number of elements (minimum specified by count
).
After adding the collection to the form, you also need to add a button that, on click, calls a function to add another element based on the template.
From the manual:
<button onclick="return add_category()">Add a new category</button>
and
<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>
To add a remove button, alter the above function to add a button to the template, and create a remove function:
<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>