简体   繁体   English

嵌入式形式 Symfony

[英]Embedded form Symfony

I have an user class that has a OneToOne relationship with Applicant and Company , I want to propose registering as one of both.我有一个用户 class 与ApplicantCompanyOneToOne关系,我想建议注册为两者之一。 In order to do that, I made 3 forms, an UserType (email) , an ApplicantType (firstName) and CompanyType (companyName) .为此,我制作了 3 个 forms、一个UserType (email) 、一个ApplicantType (firstName)CompanyType (companyName) According to url, I will either generate an ApplicantType or CompanyType to add to the UserType.根据 url,我将生成一个申请人类型或公司类型以添加到用户类型。

To pass the type I use传递我使用的类型

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

so my UserType retrieves the type in $options and dynamically adds所以我的UserType检索$options中的类型并动态添加

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

I get an error which is我收到一个错误

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.

What I want to do in the end is, after submit, create and hydrate an Applicant/Company entity that I'll attach to a newly created User entity.最后我想做的是,在提交之后,创建和水合一个申请人/公司实体,我将附加到一个新创建的用户实体。

Two things solved it:有两件事解决了它:

The data passed to the form should be传递给表单的数据应该是

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

instead of代替

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

Then in the formType add the default value for the key we use to pass the data然后在formType中添加我们用来传递数据的key的默认值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM