我有一个与OneToOne
和Applicant
具有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实体的申请人/公司实体。
两件事解决了它:
传递给表单的数据应为
$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'
]);
}