在Symfony 2.1中使用实体字段类型时,我遇到了一些双向关系(一对多)的麻烦。当创建子对象(Product)并选择父对象(Category)时,一切都很正常,它按预期的方式创建和保存。当创建父(类别)和选择由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;
}
}
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();
}
}
}
如果你能指出我的错误,我将不胜感激。
注意
我不想使用原则cascade
选项,宁愿在实体中的逻辑单元测试从数据库分开。
如果不想层叠,就必须手动持久化这些实体。
我使用集合的map()
方法(如下),但您可以通过集合的toArray()
方法使用foreach
或array_map
。
试试下面的控制器代码:
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();
}
}