Search code examples
phpsymfonyformbuilder

CollectionType elements missing data


I've embedded forms with CollectionType:

$builder->add('battlePages', CollectionType::class, [
    'label'          => 'Battle Pages',
    'entry_type'     => BattlePageCollectionType::class,
    'error_bubbling' => false,
    'constraints'    => [
        new Valid(),
    ],
]);

and 'battlePages' is an ArrayCollection with many elements.

  public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var BattlePage $entity */
    $entity = $builder->getData();
    ...

But '$entity' is empty however collection was walking through.

My goal would be to get BattlePage entity's data in the 'BattlePageCollectionType' which is my second in examples ($entity).

Anybody had have similar issues?


Solution

  • The $builder->getData(); method doesn't return an entity.

    You should use Form Events

    Example with PRE_SET_DATA event:

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $entity = $event->getData();
          $form   = $event->getForm();
    
          $form->add('someField', TextType::class);
    });