【发布时间】:2017-01-09 06:34:53
【问题描述】:
我在Post 和Category 之间有一个manyToMany 关联。我正在尝试提交帖子表单以从下拉列表<select> 中创建具有所选类别的帖子。
表单正在使用:
<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>
问题:
当我点击提交按钮时,出现以下错误(为此我花了大约 2 天的时间试图弄清楚):
类中的属性“类别” "Shop\Bundle\ManagementBundle\Entity\Post" 可以用 方法“addCategory()”、“removeCategory()”,但新值必须是 \Traversable 的数组或实例, “Shop\Bundle\ManagementBundle\Entity\Category”给出。
这是我的表单类型和实体(如果它们有用的话)。提前感谢您宝贵的时间和一如既往的帮助。
实体帖子:
<?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';
}
}
【问题讨论】:
标签: php forms symfony doctrine-orm many-to-many