Symfony CollectionType Entity constructor arguments

Viewed 212

Form:

$builder->add('positions', CollectionType::class, [
    'entry_type' => FooPositionType::class,
    'allow_add' => true,
    'allow_delete' => true,
    'delete_empty' => true,
    'prototype' => true,
    'prototype_data' => (new FooPosition($foo)),
    'by_reference' => false,
    'disabled' => $disable,
]);

FooPositionType.php:

class FooPositionType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $foo = $builder->getData(); // this is set when displaying the form
                                    // but null during $form->handleRequest();

        $builder
            ->add('text', TextType::class, [
                'required' => false,
            ]);
    }

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

FooPosition.php:

#[ORM\Entity]
class FooPosition
{
    #[ORM\Column(type: 'integer')]
    #[ORM\Id]
    #[ORM\GeneratedValue(strategy: 'IDENTITY')]
    public int $id;

    public function __construct(
        #[ORM\ManyToOne(targetEntity: Foo::class, inversedBy: 'positions')]
        private Foo $foo
    ) {}
}

The issue is that when I save a new FooPosition, I get the error message Too few arguments to function App\Entity\FooPosition::__construct(), 0 passed in var/www/svm/vendor/symfony/form/Extension/Core/Type/FormType.php on line 160 and exactly 1 expected

If I change the FooPosition constructor to private ?Foo $foo = null, everything works fine, but I do not wish to make FooPositions constructable without a proper Foo relation. How would I go about fixing this so it works? 'prototype_data' is supposed to handle this, but for some reason it doesn't.

0 Answers
Related