簡體   English   中英

Symfony 2.0實體表單字段未保存

[英]Symfony 2.0 entity form field not saving

我在將實體表單字段中的選擇保存為multiple = true時遇到問題。

選擇是在調用$ form-> bindRequest($ request)時通過的,但是在調用flush時不會保留在數據庫中。

以下是相關的控制器代碼:

$news_item = new News();

$form = $this->createFormBuilder($news_item)
  ->add('products', 'entity', 
        array('class' => 'AcmeDemoBundle:Product',
      'multiple' => TRUE))
  ->getForm();

$request = $this->getRequest();

if($request->getMethod() == "POST") {
  $form->bindRequest($request);
  if($form->isValid()) {
    $this->em->persist($news_item);
    $this->em->flush();
  }
}

我已經在$ form-> isValid()之后檢查了$ news_item對象,並且count($ news_item-> getProducts())返回了正確的項目數。 $ news_item本身保存在數據庫中,但是ManyToMany關系沒有保存。

以下是供參考的實體(為簡潔起見):

/**
 * @ORM\Entity
 * @ORM\Table(name="Product")
 */
class Product {
  /*
   * @ORM\Id @ORM\Column(type="integer")
   */
  protected $id;

  /**
   * @ORM\ManyToMany(targetEntity="News", inversedBy="products")
   */
  protected $news_items = null;

  public function __construct() {
    $this->news_items = new ArrayCollection();
  }

}

/**
 * @ORM\Entity
 * @ORM\Table(name="News")
 */
class News {
  /**
   * @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue
   */
  protected $id;

  /** 
   * @ORM\ManyToMany(targetEntity="Product", mappedBy="news_items")
   */
  protected $products = null;

  public function __construct() {
    $this->products = new ArrayCollection();
  }
}

我認為您的代碼中缺少$product->addNewsItem($news_item)$news_item->addProduct($product) ,因為在雙向關聯(似乎您的情況)中,您必須更新雙方的字段。

為了避免這種情況,您可以在關聯的兩側設置級聯選項:

@ORM\ManyToMany(targetEntity="Product", mappedBy="news_items",
   cascade={"persist", "remove"})

這樣,您的代碼將起作用。 您可以在此處選擇適當的級聯選項。

我沒有遇到同樣的問題,但是我需要能夠使用類似的實體加載FixtureData。 我收到了這份文檔: http : //www.doctrine-project.org/docs/orm/2.1/en/reference/working-with-associations.html ,我相信它將解決我的問題。 我希望這也對您有用。

JS

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM