Search code examples
symfonysymfony4symfony-forms

How to render only a specific grandchild in embedded forms?


My question is similar to Symfony form inheritance : Neither the property nor one of the methods exist but there are no templates included.

I have a nested form

demand
    home
       n children

DemandType

class DemandTypeExtension extends AbstractTypeExtension {
    public function buildForm(...): void
    {
        $builder
            ->add('home', HomeType::class, [
            ]);

HomeType

class HomeType extends AbstractType {
    public function buildForm(): void {
        $builder
            ->add('children', CollectionType::class, [
                'entry_type' => ChildrenType::class,
                'allow_add' => true,
                'by_reference' => false,
                'allow_delete' => true,
                'prototype' => true,
                'label' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void {
        $resolver->setDefaults([
            'data_class' => Home::class,
        ]);
    }
}

ChildrenType

class ChildrenType extends AbstractType {
    public function buildForm(...): void
    {
        $builder
            ->add('name', TextType::class, [
        ]);
    }

    public function configureOptions(OptionsResolver $resolver): void {
        $resolver->setDefaults([
            'data_class' => Children::class,
        ]);
    }

My form

{{ form_widget(form.children) }}

Neither the property "children" nor one of the methods "children()", "getchildren()"/"ischildren()"/"haschildren()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".

It seems I have to render the home input.

Is there no possibility to render only the children input? Perhaps with some special context (pseudo code)?

{% block form_context(form.home) %}
     {{ form_widget(form.children) }}
{% endblock form_context %}

Solution

  • Yes, you can do this. Assuming form in your twig example is an instance of DemandType, then you would do:

    {{ form_widget(form.home.children) }}
    

    However, this may not work because children is also a built in property on some Symfony form types. In HomeType I would rename the field children to something else, such as childrenCollection, in which case you would do this in your twig view:

    {{ form_widget(form.home.childrenCollection) }}