我正在尝试使用Symfony(2.8.6)中的继承类类型处理表单。
下面是我的一个非常简单的例子,虽然其中存在问题,但只是为了说明我的问题。
- 我应该如何提供只有一个表单来从控制器传递到Twig模板,以便有一个选择“类型”(鉴别器)的字段?我应该简单地创建另一个变量,例如“type”,在每个类中硬编码吗?
- 一旦提交了表单,如何在控制器中确定应该使用哪个类,在“新建”或“编辑”操作中?我已经尝试从ParameterBag中获取它,创建一个合适的实体和表单,然后使用$ form->handleRequest($request); …但当其他类型可能拥有额外字段时,似乎不起作用。
如果有人能指向 Github 存储库或其他展示此类情况发生的内容,我会非常感激。感谢你的时间。
如果这些是我的类:
/**
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap("truck" = "Truck", "Car" = "Car", "suv" = "SUV")
*/
abstract class Vechicle {
private $make;
private $model;
private $numberOfDoors;
// getters and setters //
}
class Truck extends Vehicle {
private $offRoadPackage;
private $bedSize;
// getters and setters //
}
class Car extends Vehicle {
private $bodyType;
}
class SUV extends Vehicle {
// no additional fields //
}
那么这些可能是我的表单类型:
class VehicleType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('make')
->add('model')
->add('numberOfDoors');
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Vehicle'
));
}
}
class TruckType extends VehicleType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder
->add('offRoadPackage')
->add('bedSize');
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Truck'
));
}
}
class CarType extends VehicleType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder
->add('bodyType')
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Car'
));
}
}
class SUVType extends VehicleType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\SUV'
));
}
}