Reputation: 643
I am using latest Symfony2 and Sonata Admin to maintain my site and this is my problem:
I have two entities: Shop and Discount. One shop can have many discounts and one discount can be assigned to many shops. Therefore it should be Many to Many relation.
I would like to use sonatata`s type_model_list in ShopAdmin so I can choose from a popup window these discounts and select multiple. Is this possible?
This is part of my Shop Entity:
use Doctrine\Common\Collections\ArrayCollection;
...
/**
* @var \Doctrine\Common\Collections\ArrayCollection
* @ORM\ManyToMany(targetEntity="ShoppingFever\ShoppingFeverBundle\Entity\Discount", fetch="EAGER")
* @ORM\JoinColumn(name="discountId", referencedColumnName="id")
*/
private $discountId;
And this is the relative ShopAdmin of function configureFormFields:
$formMapper
->add('shopName',null, array('label' => 'Název obchodu'))
->add('brandName',null, array('label' => 'Název brandu'))
->add('discountId', 'sonata_type_model_list', array(
'btn_add' => 'Add discount', //Specify a custom label
'btn_list' => 'button.list', //which will be translated
'btn_delete' => false, //or hide the button.
'btn_catalogue' => 'SonataNewsBundle' //Custom translation domain for buttons
), array(
'placeholder' => 'Nothing selected',
'expanded' => true, 'multiple' => true, 'by_reference' => false
))
->add('street',null, array('label' => 'Ulice'))
->add('city',null, array('label' => 'Město'))
->add('zip',null, array('label' => 'PSČ'))
->add('gps',null, array('label' => 'GPS'))
->add('openingHours','textarea', array('label' => 'Otevírací doba'))
->add('eventId',null, array('required'=>false,'label' => 'Event'));
If I had One To Many relation (one discount to any shop), the admin works. Symfony generated the reference table for discount and shop ids to work for many to many.
This is the One To Many output and I would like this to work for Many To Many, so where now it says Swarovski, there would be several discounts.
Is it possible to do it with many to many as well?
Upvotes: 5
Views: 1893
Reputation: 12032
You can't use sonata_type_model_list
with a many-to-many relation.
What you can do is to use sonata_type_model
instead and set the option multiple
to true
:
->add('discountId', 'sonata_type_model', array(
'multiple' => true,
// other options
))
For the current version of SonataAdminBundle (as of today 2019-02-18 it is 3.x) the example should look like:
// import ModelType
use Sonata\AdminBundle\Form\Type\ModelType;
// code example
->add('discountId', ModelType::class, [
'multiple' => true,
// other options
])
This will create a dropdown list to select multiple related objects and Add new button (or Add discount if you set that trough btn_add
) to create a new related object.
Upvotes: 1