Home > Net >  Symfony: include MappedSuperClass form inside another Form Type
Symfony: include MappedSuperClass form inside another Form Type

Time:07-01

in Symfony 6, I have a MappedSuperclass Entity called Person with personal data (name, surnames, etc.).

#[ORM\MappedSuperclass]
class Person
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\Column(type: 'string', length: 180)]
    private $name;

    #[ORM\Column(type: 'string', length: 255)]
    private $surnames;
}

And I have a number of entities extending from that one, Owner, Client and Visitor with their own properties, for example:

#[ORM\Entity()]
class Owner extends Person
{
    #[ORM\OneToOne(inversedBy: 'owner', targetEntity: User::class, cascade: ['persist', 'remove'])]
    private $user;

    #[ORM\Column(type: 'boolean')]
    private $isExternal = false;
}

My question is, can I create a Person FormType only once and somehow embed it inside the OwnerFormType, ClientFormType and VisitorFormType?

I know I could create a FormType for Person and access it separately from Owner or Client data, save those fields and then complete Owner or Client in another form, but that leads to problems with required fields, alias it's not an elegant solution.

CodePudding user response:

First you have to create a form PersonType. Then you create your forms OwnerType,VisitorType etc... In The builder of the subclasses you can create the PersonType form.

$builder
        ->add('user')
        ->add('isExternal')
        ->add('person', PersonType::class, ['data_class' => Owner::class]);
  • Related