形式:
$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
) {}
}
问题是当我保存新的 FooPosition 时,我收到错误消息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
如果我将 FooPosition 构造函数更改为private ?Foo $foo = null
,一切正常,但我不希望在没有适当 Foo 关系的情况下使 FooPositions 可构造。我将如何解决此问题以使其正常工作?'prototype_data' 应该处理这个问题,但由于某种原因它没有。