Search code examples
symfonysymfony-formssonata-admin

add entity inside other with many to one relation in sonata


I'm using Symfony and sonata bundle, and I have 2 Entities, related with a ManyToOne/OneToMany relation as follows:

One Category can have many SubCategory entities. For that, in Sonata's FormMapper, when I add a new category I want to add a button to display a popup to to create more than one SubCategory .. so how can I override the Twig of Sonata to do that?

CategoryAdmin

class CategoryAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name')
            ->add('subcats', 'entity', array(
                'class'=> 'ProductBundle\Entity\SubCategory',
                'multiple' => true,
            ))
        ;
    } 
}

Solution

  • You can use your one template by adding:

    $formMapper
        ->add('name')
        ->add('subcats', 'entity', array(
            'class'=> 'ProductBundle\Entity\SubCategory',
            'multiple' => true,
            'attr' => array('template'=> 'your\path\to\twig')
        ))
     ;
    

    and this twig should extends from base_edit_form.html.twig

    {% extends 'SonataAdminBundle:CRUD:base_edit_form.html.twig' %}
        {% block field %}
    
            <div>
                // put your code here
            </div>
    
        {% endblock %}
    

    Or you have an other solution that can fix your problem, you can use the Sonata_Type_Model

      ->add('subcats','sonata_type_model', array(
          'multiple' => true, 
          'by_reference' => false
      ))
    

    This solution will give you that you like, a button to add and remove to create your SubCategory