繁体   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