如何在symfony中使用多种表单类型创建一个带有数据类的单一表单
问题描述:
首先,让我承认我是symfony表单中的业余人员。任何帮助将非常感激。我不能分享实际的代码,因此我使用一些示例代码来演示用例。如何在symfony中使用多种表单类型创建一个带有数据类的单一表单
下面给出的是用例,
我有一个叫testEntity
class testEntity {
private $property1;
private $property2;
private $property3;
//with setters and getters
}
我有一个名为formType1表单类型,
class formType1 extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('property2')
->add('property3)
;
}
public function buildView() {
// Code that create view vars
}
}
实体,而且我有一个表格型for testEntity,
class testEntityType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('property1)
....
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => testEntity::class
]);
}
}
formType1是一种带有数据类的表单类型,并带有自己的模板,并将自己使用。我想要做的是在testEntityType中重用formType1,因为formType1具有映射到testEntity属性的字段,因此在提交时我可以使用表单数据获取testEntity对象,并且还可以在我的最终形式中获取formType1的视图。
控制器动作有这个,
$testEntity = new testEntity();
$form = $this->createForm(PostType::class, $testEntity);
,这样的情况下,表单提交,我得到的数据$ testEntity从形式
道歉提前,如果我没有陷害的问题不够好被理解。
通过这样得到这个工作,
class testEntityType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('property1')
->add('formType1', formType1::class, [
'mapped' => false,
'data' => $options['data']
])
....
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => testEntity::class
]);
}
}
传递经过选择和SETT mapped
数据false
。
答
实际上,您的formType1
只是一种自定义类型。 所以你唯一需要做的就是导入你想要使用的类型,并将它添加到你的构建器中,就像你将使用非自定义类型(ChoiceType,TextType等)一样。
use YourBundle\Type\formType1;
class testEntityType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('property1')
->add('formType1', formType1::class, [
'data_class' => testEntity::class, //line edited
])
....
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => testEntity::class
]);
}
}
PS:小心你的类
感谢您的快速回复的命名约定。如果我们在更新中使用'formType1'作为子窗体的名称,则会在'testEntity'中错误地指出没有像'getFormType1()'这样的方法或像'formType1'这样的属性。 –
您是否可以使用此表单更新您的控制器操作问题?如果您在构建器中添加'data_class',会发生什么情况(请参阅编辑) –
使用控制器操作中的代码更新了问题。同样,通过在构建器中传递data_class,它仍会给出相同的错误,如下所示:属性“formType1”和方法“getFormType1()”,“formType1()”,“isFormType1()” ,“hasFormType1()”,“__get()”存在并且在类“Entity \ testEntity”中具有公共访问权限' 当我们传递data_class时,表单预计会有一个名称映射到数据类'formType1'不映射到'testEntity'的任何属性。 –