嵌入式Symfony格式

问题描述 投票:0回答:1

我有一个与OneToOneApplicant具有Company关系的用户类,我想建议注册为两者之一。为了做到这一点,我做了3个表格,一个UserType (email),一个ApplicantType (firstName)CompanyType (companyName)。根据url,我将生成一个ApplicantType或CompanyType以添加到UserType。

通过我使用的类型

$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.

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

php forms symfony doctrine
1个回答
0
投票

两件事解决了它:

传递给表单的数据应为

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

而不是

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

然后在formType中添加用于传递数据的键的默认值

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([ 
       'typeOfUser' => 'applicant'
    ]);
}
© www.soinside.com 2019 - 2024. All rights reserved.