I'm trying to figure out how to handle forms when using inherited class types with Symfony (2.8.6).
I have created a [very] simple example case of what I'm trying to do below. There are problems with it, but it's only to illustrate my question.
- How can I supply just one form going from the controller to a twig template so that there can be a field to choose what "type" (discriminator) should be used? Should I simply create another variable, such as "type" that is hardcoded in each class?
- Once a form is submitted, how can I figure out which class should be used in the controller, in either a "new" or "edit" action? I've tried plucking it out of the ParameterBag, creating an appropriate entity and form, then using $form->handleRequest($request); ...but it doesn't seem to work when there are extra fields that might belong to another type.
If someone could even point me to a Github repo or something that shows something like this happening, I'd be very grateful. Thanks for your time.
If these are my classes:
/**
* @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 //
}
then something like these would be my form types:
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'
));
}
}