简体   繁体   中英

Sonata admin don't save the many-to-many field

This is the common porblem. There is the form with many checkbocks. Making the checkbocks are aviable and click save, fields corresponding checkbock-labels don't save.

PersonAdmin class contains

        ...
       ->add('books', 'sonata_type_model', 
                array('by_reference' => false, 'expanded' => true, 'multiple' => true, 'label' => 'Books'))
       ...

Entity class contains

     /**
      * @ORM\ManyToMany(targetEntity="Book", mappedBy="persons", cascade={"persist"})
      * @ORM\JoinTable(name="person_book")
      */
    protected $books;

    ....

    public function __construct()
    {
        $this->books = new ArrayCollection();
    }

    public function addBook(Book $book)
    {
        $this->books[] = $book;

        return $this;
    }

and geters, seters...

I unsuccessfully searched for a solution. I have found that it is necessary to add

               'by_reference' => false, 

or

                cascade={"persist"}

but I have all of this in my code.

As mentioned before you need to save relation in both sides. But I would prefer another way: to save relation in the add actions of your entities:

//In the Person entity:
public function addBook(Book $book)
{
    $book->addPerson($this);
    $this->books[] = $book;

    return $this;
}

//In the Book entity (if you have the same problem for another side):
public function addPerson(Person $person)
{
    $person->addBook($this);
    $this->persons[] = $person;

    return $this;
}

You have to save at both sides.

Override the default editAction and createAction in a custom crud controller.

eg:

It's an example of a many to many relationship between artists and events.

($object is the current object you are editing/creating in the action)

foreach ($form['selectArtists']->getData() as $key => $value) {
                $artist = $em->getRepository('MyCompanyProjectBundle:Artist')->findOneById($value);
                $object->addArtist($artist);
                $artist->addEvent($object);
                $em->persist($artist);
            }

Use edit=>inline .

   ->add('books', 'sonata_type_collection', 
            array('by_reference' => false, 'label' => 'Books'),
            array('edit'=>'inline','inline'=>'table'))

May be help you.

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