Question

i'm currently using Sonata Admin Bundle using Symfony 2.1.0-DEV and Doctrine 2.2.x and i'm having problems with Many-To-Many entities associations:

class MyProduct extends Product {

    /**
     * @ORM\ManyToMany(targetEntity="Price")
     */
    private $prices;

    public function __construct() {
        $this->prices = new \Doctrine\Common\Collections\ArrayCollection()
    }

    public function getPrices() {
        return $this->prices;
    }

    public function setPrices($prices) {
        $this->prices = $prices;
    }
}

// Admin Class

class GenericAdmin extends Admin {

    ...

    public function configureFormFields(FormMapper $formMapper)
        {
            $formMapper
                ->with('General')
                ->add('prices', 'sonata_type_model')
                ->end()
            ;
        }
    }

    ...

}

Now if try to add a price to the many-to many association from Sonata's CRUD create/edit form panel the update doesn't work.

Any hints on this issue? Thanks!

Was it helpful?

Solution

Update with solution

I've found the answer to my problem: for making things to work with many-to-many relationships you need to pass *by_reference* equal to false (see here for more details).

The updated working version is:

class MyProduct extends Product {

    /**
     * @ORM\ManyToMany(targetEntity="Price")
     */
    private $prices;

    public function __construct() {
        $this->prices = new \Doctrine\Common\Collections\ArrayCollection()
    }

    public function getPrices() {
        return $this->prices;
    }

    public function setPrices($prices) {
        $this->prices = $prices;
    }

    public function addPrice($price) {
        $this->prices[]= $price;
    }

    public function removePrice($price) {
        $this->prices->removeElement($price);
    }
}

// Admin Class

class GenericAdmin extends Admin {

    ...

    public function configureFormFields(FormMapper $formMapper)
        {
            $formMapper
                ->with('General')
                ->add('prices', 'sonata_type_model', array('by_reference' => false))
                ->end()
            ;
        }
    }

    ...

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top