3
votes

I created a simple Many to Many ($post --> $category) relation in symfony2, which I want to use in my form builder thanks to the "entity" field type, with a multiple = false option (default) for now, eventhough it's many to many.

This is part of my Post entity :

 /**
 * @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 get

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 relation is many to many so I am forced to make it a multiple entity field ?

I've cleared cache, doctrine cache, I've regenerate my entity getter/setter, don't know what I may be doing wrong..

Thanks for your help

1
Thanksssss ! the Many to Many was the issueGabriel Henao

1 Answers

0
votes

Found the answer thanks to symfony2 Entity select tag display

The issue was indeed because of the ManyToMany relation, (this actually makes sense, because if you have a ManyToMany relation, you want to be able to select multiple entities),

You can get this to work with a multiple = false by adding a setter for the whole ArrayCollection property.

/**
 * 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;
}