Question

I am using Symfony2 for a PHP project, but I have a question about Entity inheritance.

I have a database model that requires to make the difference between different types of employees.

Here is an extract of the modelisation :

Employee

  • civility
  • name
  • firstname
  • hired_at

Secretary extends Employee

  • employee [Employee entity]
  • roles [another entity]

Seller extends Employee

  • employee [Employee entity]
  • section [another entity]

I have to separate it because I have another entity, called Message, that each employees can send to other ones.

Message

  • author [Employee entity]
  • recipient [Employee entity]
  • title
  • content
  • sent_at

In my application, I would like to be able to create a new "Secretary" for instance, and set up its "Employee" properties in the same form, rather than creating the Employee entity then link it to the new Secretary one...

What is the proper way to do it with Symfony2 ?

I know that I could add the properties to the form and set the entities manually, but I really think there should be a cleaner way to do that...

Is it possible to use the FormBuilder ?

Was it helpful?

Solution

Quite easy in fact, I did not know it was possible to add another FormType as a field type in Symfony2.

The working way, just in case :

namespace MyAdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SecretaryType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('employee', new EmployeeType(), array('label' => 'Employee', 'required' => true))
            ->add('password', 'password', array('label' => 'Password', 'required' => true))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MyCoreBundle\Entity\Secretary'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'my_adminbundle_secretary';
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top