在Symfony 2.1中使用实体字段类型时,我遇到了双向关系(一对多)的问题。在创建子(Product)并选择父(Category)时,所有内容都是hunky dory,它会按预期创建并保留。创建父(Category)并选择由Symfony2的表单系统生成的多个子(Product)复选框时会出现问题。 这不会持续。
我将把我的示例类放在下面,但是克隆我的示例项目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;
}
}
DefaultController
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();
}
}
}
任何指向我出错的地方都会非常感激。
注意
我不想使用Doctrine cascade
选项,而是将单元测试实体中的逻辑与db分开。
答案 0 :(得分:3)
如果您不想级联,则必须手动保留这些实体。
我使用了集合的map()
方法(下方),但您可以通过集合的foreach
方法使用array_map
或toArray()
。
尝试以下控制器代码:
protected function saveCategory($category, $form, $request)
{
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->getProducts()->map(
function($product) use ($em) {
$em->persist($product);
}
);
$em->persist($category);
$em->flush();
}
}