I have a manyToMany
association between Post
and Category
. I am trying to submit the Post form to create a post with the selected category from the dropdown <select>
.
Form is rendering correclty using:
<div id="form-categories-widget">
<select id="shop_bundle_managementbundle_posttype_categories"
name="shop_bundle_managementbundle_posttype[categories]">
{% for key,val in form.categories.vars.choices %}
<option value="{{ val.value }}" {{ form.categories.vars.value == '' and key == 0 ? ' selected ' :(val.value == form.categories.vars.value ? ' selected ' : '') }}
>
{{ val.data.getName | trans }}
</option>
{% endfor %}
</select>
</div>
The problem:
When I click on submit button I have the following error(for which I have spent about 2 days trying to figure out):
The property "categories" in class "Shop\Bundle\ManagementBundle\Entity\Post" can be defined with the methods "addCategory()", "removeCategory()" but the new value must be an array or an instance of \Traversable, "Shop\Bundle\ManagementBundle\Entity\Category" given.
Here are my form type and entity (if ever they are useful). I thank you in advance for your invaluable time and help as usual.
Entity Post:
<?php
namespace Shop\Bundle\ManagementBundle\Entity;
class Post
{
.....
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $categories;
/**
* Add category
*
* @param \Shop\Bundle\ManagementBundle\Entity\Category $category
*
* @return Post
*/
public function addCategory(\Shop\Bundle\ManagementBundle\Entity\Category $category)
{
$this->categories[$category->getName()] = $category;
$category->addPost($this);
return $this;
}
/**
* Remove category
*
* @param \Shop\Bundle\ManagementBundle\Entity\Category $category
*/
public function removeCategory(\Shop\Bundle\ManagementBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* Get categories
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
}
PostType
class PostType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('categories', 'entity', array(
'multiple' => false, // Multiple selection allowed
'expanded' => false, // Render as checkboxes
'class' => 'ShopManagementBundle:Category',
'property' => 'name'
));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Shop\Bundle\ManagementBundle\Entity\Post'
));
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'shop_bundle_managementbundle_posttype';
}
}