【发布时间】:2018-04-26 00:07:27
【问题描述】:
我在 Symfony 中遇到问题好几天了,在 google 上找不到任何东西。
我有两张桌子。
帐号:
AppBundle\Entity\Account:
type: entity
fields:
name:
type: string
nullable: true
length: 255
oneToMany:
towns:
targetEntity: AppBundle\Entity\Town
mappedBy: owner
cascade: ['persist']
城镇:
AppBundle\Entity\Town:
type: entity
fields:
name:
type: string
nullable: true
length: 255
manyToOne:
owner:
targetEntity: AppBundle\Entity\Account
inversedBy: towns
我有一个名称数组:
$names = ['New York','Berlin'];
我想要一个表单,用户可以在其中检查数组中的名称(复选框)。当用户检查“纽约”并提交表单时,我想要一个新实体Town 在name 字段中带有“纽约”。如果用户取消选中“纽约”,我希望删除该实体。
到目前为止,我已尝试使用 EntityType、CollectionType 和 ChoiceType。我能得到的最好的就是 ChoiceType。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('towns', ChoiceType::class,
[
'choices' =>
[
new Town('New York'),
new Town('Berlin'),
],
'choice_label' => function (Town $town, $key, $index) {
return $town->getName();
},
'choice_value' => function (Town $town) {
return $town->getName();
},
'expanded' => TRUE,
'multiple' => TRUE,
'required' => FALSE,
]
);
}
但每次用户提交任何已选中城镇的表单时,它都会添加一个新实体,并且不会删除未选中的城镇...
【问题讨论】:
-
抱歉,您有什么问题?你说“我想要一个名称字段中带有'New York'的新实体'Town'。如果用户取消选中'New York',我希望删除该实体”然后你说“但每次用户提交表单并检查任何城镇时,它都会添加一个新实体,它会删除未选中的实体“。听起来它正是你想要的......
-
在表单构建器中实例化实体很奇怪。
-
抱歉,打错了。它不会删除。如果已存在同名实体,则不应生成新实体。
-
城镇名称数组从何而来,您真的必须使用它吗?它在您问题的标题中,但您没有在表单构建器示例中使用它。
-
数组在“选择”字段中。我从两个查询创建它。