ninsuo / symfony-collection

[NOT MAINTAINED] A jQuery plugin that manages adding, deleting and moving elements from a Symfony form collection
https://symfony-collection.fuz.org/
MIT License
445 stars 88 forks source link

Can't add custom attr on collection_widget block #34

Open soullivaneuh opened 8 years ago

soullivaneuh commented 8 years ago

According to your twig doc header:

# If you are already using a form theme, you can use both by using:
# {%
#   form_theme myForm
#       'FuzAppBundle::my-form-theme.html.twig'
#       'FuzAppBundle::jquery.collection.html.twig'
#       ...
# %}

So I did from config:

twig:
    debug:            '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    form_themes:
        - 'form_generic_fields.html.twig'
        - 'form_fields.html.twig'
        - 'jquery.collection.html.twig'

And in form_generic_fields.html.twig, I want to always add collection-type class like this:

{% block collection_widget -%}
    {% set attr = attr|merge({class: (attr.class|default('') ~ ' collection-type')|trim}) %}
    {{ parent() }}
{%- endblock collection_widget %}

The problem is this as no effect at all because your template also override this block and don't have any parent.

Is that a solvable issue or should I do it with another way?

soullivaneuh commented 8 years ago

I found another way. I put all here so you can add it on documentation if you want to.

Create a CollectionTypeExtension class:

<?php

namespace AppBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 */
final class CollectionTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // Here we add the collection-type class
        $view->vars['attr']['class'] = array_key_exists('class', $view->vars['attr'])
            ? $view->vars['attr']['class'].' collection-type'
            : 'collection-type';
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return CollectionType::class;
    }
}

And enable the service:

form.extension.collection:
    class: AppBundle\Form\Extension\CollectionTypeExtension
    tags:
        - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\CollectionType }

That's all! :+1: