infinite-networks / InfiniteFormBundle

A collection of useful form types and extensions for Symfony.
169 stars 40 forks source link

Add post-insert event hook when adding rows into collections #52

Closed ajcerqueti closed 8 years ago

ajcerqueti commented 8 years ago

It'd be helpful to be able to process post-insert events in jQuery.

This is very similar to #47, except it's event-based, so works if you're not adding programmatically.

This would allow devs to do things like check for empty fields and set default values; setting data in prototypes will overwrite entity data, whereas a data-default-value attribute in the form could be easily added to the form type and thus available to fetch in the prototype. Thus something like this:

$(window).on('infinite_collection_added', function (e) {
    var $targetRow = e.target;
    var index = e.index;
    var id = '#collection_type_associations_' + index + '_field';
    var $input = $(id, $targetRow);
    var value = $input.val();
    var defaultValue = $input.data('default-value');
    if ('' == value) {
        $input.val(defaultValue);
    }
});

There's obviously numerous other situations where executing something after an add would be useful. From what I can see, this isn't quite possible with #47 unless you're adding manually/programatically. Hopefully you can see the value in this small change.

merk commented 8 years ago

Is there any reason you can't do this in the infinite_collection_add event? All elements are created at that point, just not inserted into their final place.

If not, a few changes to the PR would be appreciated:

If you must rely on the index, setting a data property on the row would be a better approach than passing it around in events.

ajcerqueti commented 8 years ago

@merk You're right, it's probably makes sense to just use the existing event. When I'd inspected Event.$row, it had returned a weird parsed HTML array, rather than the row element I was expecting, but it does actually work. Will close this pull request, but in case anyone finds this and wonders how I used this:

CollectionFormType

...
'attr' => [
    'data-default-value' => 1.0,
    'class' => 'default-value-available',
],
....
$(window).on('infinite_collection_add', function (e) {
    var $targetRow = e.$row;
    var $input = $('input.default-value-available', $targetRow);
    $input.each(function (index, element) {
        var $element = $(element);
        var value = $element.val();
        var defaultValue = $element.data('default-value');
        if ('' == value) {
            $element.val(defaultValue);
        }
    });
});