简体   繁体   中英

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,
            ))
        ;
    } 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM