在 Symfony 2.1 中使用实体字段类型时,我在双向关系(一对多)方面遇到了一些问题。在创建子(产品)并选择父(类别)时,一切都是 hunky dory,它按预期创建和持久化。当创建父级(类别)并选择由 Symfony2 的表单系统生成的多个子级(产品)复选框时,就会出现问题。这不会持续。
我将把我的示例类放在下面,但是克隆我的示例项目 repo 可能更容易 - https://github.com/domudall/multiple-expanded-entity-choice-issue
类别
class Category
{
protected $id;
protected $name;
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
public function addProduct($product)
{
if (!$this->products->contains($product)) {
$this->products->add($product);
$product->setCategory($this);
}
return $this;
}
public function setProducts($products)
{
foreach ($products as $product) {
$this->addProduct($product);
}
return $this;
}
public function removeProducts()
{
if ($this->products->contains($product)) {
$this->products->remove($product);
}
return $this;
}
}
产品
class Product
{
protected $id;
protected $name;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
*/
protected $category;
public function setCategory(Category $category)
{
$this->category = $category;
$category->addProduct($this);
return $this;
}
public function getCategory()
{
return $this->category;
}
}
默认控制器
class DefaultController extends Controller
{
public function categoryCreateAction(Request $request)
{
$category = new Category();
$form = $this
->createFormBuilder($category)
->add('name', 'text', array())
->add('products', 'entity', array(
'class' => 'AcmeShopBundle:Product',
'property' => 'name',
'required' => false,
'expanded' => true,
'multiple' => true,
))
->getForm();
if ($request->getMethod() == 'POST') {
$this->save($category, $form, $request);
}
}
public function productCreateAction(Request $request)
{
$product = new Product();
$form = $this
->createFormBuilder($product)
->add('name', 'text')
->add('category', 'entity', array(
'class' => 'AcmeShopBundle:Category',
'property' => 'name',
'required' => false,
))
->getForm();
if ($request->getMethod() == 'POST') {
$this->save($product, $form, $request);
}
}
protected function save($entity, $form, $request)
{
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
}
}
任何指向我哪里出错的指针将不胜感激。
笔记
我不想使用 Doctrinecascade
选项,而是希望实体中的逻辑与数据库分开进行单元测试。