Symfony CollectionType -> EntryType -> 带参数的表单

Symfony CollectionType -> EntryType -> Form with params

我有两个表单,第一个允许我添加项目 ProjectType,第二个是允许向项目添加贡献者的表单 ProjectContactType

在第一种形式中,我得到了带有解析器的实体公司

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('name', TextType::class)
        ->add('projectContacts', CollectionType::class, [
            'label' => false,
            'entry_type' => ProjectContactType::class,
            'by_reference' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ]);
}

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

我希望能够在我的第二种形式中接收到相同的实体。

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('user', EntityType::class, [
            'placeholder' => 'Choisir un client',
            'required' => true,
            'class' => User::class,
            'choice_label' => function (User $user) {
                return $user->getFirstName() . " " . $user->getLastName();
            }
        ]);
}

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

我的目标是能够按公司实体过滤用户。

谢谢。

您应该能够像这样将 ProjectType 的公司传递给 ProjectContactType:

在 ProjectContactType 中创建所需的公司:

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

然后(在 ProjectType 中)将公司从 ProjectType 的选项传递给 ProjectContactType:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('name', TextType::class)
        ->add('projectContacts', CollectionType::class, [
            'label' => false,
            'entry_type' => ProjectContactType::class,
            'by_reference' => false,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options' => [
                'company' => $options['company'], 
            ],
        ]);
}