Symfony2 submit error with entity type (many-many relationship)
I have created in Symfony2 a simple Many to Many ($ post -> $ category) relation that I want to use in my form builder thanks to the "entity" field type, with multiple = false (default) for now, although that's a lot for many.
This is part of my Post object:
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="Yeomi\PostBundle\Entity\Category", inversedBy="posts")
*/
private $categories;
/**
* Add categories
*
* @param \Yeomi\PostBundle\Entity\Category $categories
* @return Post
*/
public function addCategory(\Yeomi\PostBundle\Entity\Category $category)
{
$this->categories[] = $category;
return $this;
}
/**
* Remove categories
*
* @param \Yeomi\PostBundle\Entity\Category $categories
*/
public function removeCategory(\Yeomi\PostBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* Get categories
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
This is my PostType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
->add('content', 'textarea')
->add('published', 'checkbox')
->add("categories", "entity", array(
"class" => "YeomiPostBundle:Category",
"property" => "name",
"multiple" => false,
))
->add('published', 'checkbox')
->add('save', "submit")
;
}
And this is the error I am getting
500 Internal Server Error - NoSuchPropertyException
Neither the property "categories" nor one of the methods "addCategory()"/"removeCategory()", "setCategories()", "categories()", "__set()" or "__call()" exist and have public access in class "Yeomi\PostBundle\Entity\Post".
It works with multiple = true, but that's not what I want, would it be because the relationship is many to many, so I am forced to make this field with multiple objects?
I cleared cache, doctrine cache, I updated my getter / setter object, dont know what I might be doing wrong.
thanks for the help
source to share
Found an answer thanks to symfony2 Displaying Entity Select Tag
The problem was really related to the ManyToMany relationship (this really makes sense, because if you have a ManyToMany relationship , you want to be able to select multiple objects)
You can get this to work with multiple = false
by adding a setter for the entire property ArrayCollection
.
/**
* Set categories
* @param \Doctrine\Common\Collections\Collection $categories
*
* @return Post
*/
public function setCategories($categories)
{
if(!is_array($categories))
{
$categories = array($categories);
}
$this->categories = $categories;
return $this;
}
source to share