Skip to content

[CollectionType] Get binded data in FormType #19123

Closed
@cavasinf

Description

@cavasinf

I don't know if it is an expected behavior,
but when using an Embed Collection of Forms,
when you try to access the bound data with $builder->getData(), the result is null.

// src/Form/TaskType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->add('tags', CollectionType::class, [
        'entry_type' => TagType::class,
    ]);
}

// src/Form/TagType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->getData(); // <-- Is null
}

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

You need to go through the PRE_SET_DATA eventListener to get the data with $event->getData().

// src/Form/TagType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
         $event->getData(); // <-- Is OK
    });
}

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

Even worth, when the form (which call the CollectionType) sets the by_reference to false,
the entire form must to be inside a PRE_SET_DATA event.

// src/Form/TaskType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->add('tags', CollectionType::class, [
        'entry_type' => TagType::class,
        'by_reference' => false, // $event->getData() inside TagType::class will be null
    ]);
}
// src/Form/TaskType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
   $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
       $form = $event->getForm();
       $form->add('tags', CollectionType::class, [
            'entry_type' => TagType::class,
            'by_reference' => false, // $event->getData() is OK
       ]);
   });
}

If it is a thing,
I think it is worth mentioning that somewhere in the doc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    StalledhasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions