简体   繁体   中英

Symfony: How to render a Collection Form Type in a custom format

According to the Symfony docs an individual collection form type can be customized. How can I have Symfony to detect my customized twig template? It does not seem to work out of the box, but I might have missed something..

src\\Form\\Type\\ItemAliasType:

class ItemAliasType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add("name", TextType::class, [
            "label"              => "item alias name",
            "required"           => true,
        ]);

        $builder->add("description", TextType::class, [
            "label"              => "item alias name",
            "required"           => true,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => ItemAlias::class,
        ]);
    }
}

src/Form/ItemForm:

class ItemForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /* ... code ... */

        $builder->add("aliases", CollectionType::class, array_merge([
            "label"              => "item-aliases",
            "entry_type"         => ItemAliasType::class,
            "allow_add"          => true,
            "allow_delete"       => true,
            "prototype"          => true,
        ], $inheritedOptions));

    }
}

templates/form/collections.html.twig:

{% block _aliases_entry_row %}
    <div class="custom">
        {{ form_widget(form.name) }}
        {{ form_widget(form.description) }}
    </div>
{% endblock %}

config/packages/twig.yaml:

twig:
    form_theme:
        - 'form/collections.html.twig'

The block in the twig template should have a different name

templates/form/collections.html.twig:

{% block _item_form_aliases_entry_row %}

to block identifier should be <form_name><form_child_name>_entry_(row|widget|label)

Artamiels link provides a clear explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM