在Symfony 2.1中使用實體字段類型時,我遇到了雙向關係(一對多)的問題。創建子項(產品)並選擇父項(類別)時,所有內容都是hunky dory,它是按預期創建並保持的。創建父級(Category)並選擇由Symfony2的表單系統生成的多個子級(Product)複選框時會出現問題。 這不會持續。Symfony2.1實體字段類型多個展開不保存
我要把我下面的示例類,但它可能會更容易克隆我的示例項目回購 - 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
選擇,寧願在實體單元測試的邏輯從數據庫中分離出來。
的'mappedBy'側是不可變的。您將不得不手動持續產品對象。 – arghav 2013-03-27 16:29:29