【问题标题】:Embedded form Symfony嵌入式表单 Symfony
【发布时间】:2019-09-26 19:37:05
【问题描述】:

我有一个与ApplicantCompanyOneToOne 关系的用户类,我想建议注册为两者之一。 为此,我制作了 3 个表格,UserType (email)ApplicantType (firstName)CompanyType (companyName)。根据 url,我将生成一个申请人类型或公司类型添加到用户类型。

传递我使用的类型

$form = $this->createForm(UserType::class, $user, ['data' => ['type' => $type]]);

所以我的UserType 检索$options 中的类型并动态添加

->add('applicant', ApplicantType::class) or ->add('company',CompanyType::class)

我收到一个错误

The form's view data is expected to be an instance of class App\Entity\User, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of App\Entity\User.

我最终要做的是,在提交后,创建并合并一个申请人/公司实体,我将附加到新创建的用户实体。

【问题讨论】:

    标签: php forms symfony doctrine


    【解决方案1】:

    两件事解决了它:

    传递给表单的数据应该是

    $form = $this->createForm(UserType::class, $user, ['typeOfUser' => $type]);
    

    而不是

    $form = $this->createForm(UserType::class, $user, ['data' => ['type' => $type]]);
    

    然后在formType中添加我们用来传递数据的key的默认值

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([ 
           'typeOfUser' => 'applicant'
        ]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多