【问题标题】:Symfony CollectionType -> EntryType -> Form with paramsSymfony CollectionType -> EntryType -> 带参数的表单
【发布时间】:2022-01-01 19:48:37
【问题描述】:

我有两个表单,第一个允许我添加项目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,
        ]);
}

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

谢谢。

【问题讨论】:

    标签: php symfony bundle


    【解决方案1】:

    您应该能够像这样将 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'], 
                ],
            ]);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多