symfony/symfony — pull request #10071 by leevigraham (2014-01-19 13:43:32+00:00)
Title: Added additional data attributes for collection type output

Refactored and up to date w/ master version of: #7713

| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | yes
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | na
| License | MIT
| Doc PR | WIP

- [x] fix the tests as they have not been updated yet
- [ ] submit changes to the documentation

----

I've added 4 extra data-* attributes to collections in twig and php views for easier js manipulation.

New attributes:

* `data-form-widget='collection'`: This is a collection and all children are form types
* `data-collection-allow-add`: Allow adding of new elements
* `data-collection-allow-delete`: Allow deletion of elements (new and existing)
* `data-prototype-name`: The prototype name

This should make javascript integration much easier.

Example js:

```js
$('[data-form-widget=collection]').each(function(){

var $collection = $(this),
prototypeString = $collection.data('prototype'),
prototypeName = $collection.data('prototypeName') || '__name__',
prototypeNameRegx = new RegExp(prototypeName+"(label__)?","g"),
count = $collection.children().length;

console.log(this, count, prototypeString);

var $deleteLink = $("", {
'class': 'js-delete',
'text': 'Delete'
});

var $addLink = $("", {
'class': 'js-add',
'text': 'Add'
});

if($collection.data('collectionAllowDelete')) {

$collection
.children()
.append($deleteLink.clone(true));

$collection.on('click', '.js-delete', function(){
event.preventDefault();
$(this).parent().remove();
});
}

if($collection.data('collectionAllowAdd')) {

$addLink.click(function(event){
event.preventDefault();
var newPrototypeString = prototypeString.replace(prototypeNameRegx, count),
$newPrototype = $(newPrototypeString).append($deleteLink.clone(true));
$newPrototype.insertBefore($addLink);
count++;
});

$collection.append($addLink);
}
});
```

Replaces #7713