我有一个关于用多对多关系的实体填充我的表单的问题。
首先我的代码:
产品实体:
<?php
namespace My\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Zend\Form\Annotation;
use My\Entity\Brand;
/**
* @ORM\Entity(repositoryClass="My\EntityRepository\Product")
* @ORM\Table(name="product")
* @Annotation\Hydrator("Zend\Stdlib\Hydrator\ArraySerializable")
* @Annotation\Name("Product")
*/
class Product{
/**
* @ORM\id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
* @Annotation\Attributes({"type":"hidden"})
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="productGroup")
* @Annotation\Type("Zend\Form\Element\Select")
* @Annotation\Options({"label":"Productgroup: "})
*/
protected $productGroups;
/**
* @ORM\Column(nullable=false)
* @Annotation\Attributes({"type":"text"})
* @Annotation\Options({"label":"Product name:"})
*/
protected $productName;
/**
* @Annotation\Attributes({"type":"textarea"})
* @Annotation\Options({"label":"Product description: "})
* @ORM\Column
*/
protected $description;
public function __construct() {
$this->memos = new ArrayCollection();
$this->productGroups = new ArrayCollection();
}
/**
* Sets the product tags
* @param ArrayCollection $tags
*/
public function setTags(\Doctrine\Common\Collections\ArrayCollection $tags) {
$this->productGroups = $tags;
}
/**
* This function unsets a product group
*/
public function unsetProductsGroups() {
unset($this->productGroups);
}
}
然后我有我的行动
public function newAction()
{
$em = $this->getEntityManager();
$request = $this->getRequest();
$product = new Product();
$builder = new AnnotationBuilder($em);
$form = $builder->createForm($product);
if ($request->isPost() && $this->request->getPost()) {
$repo = $this->getEntityManager()->getRepository('My\Entity\Product');
$repo->addProduct($this->getRequest()->getPost());
$this->flashMessenger()->addMessage('The product was added.');
return $this->redirect()->toRoute('zfcadmin');
} else {
$config = $this->getModuleConfig();
if (isset($config['my_form_extra'])) {
foreach ($config['my_form_extra'] as $field) {
$form->add($field);
}
}
$form->setHydrator(new DoctrineHydrator($em, 'My\Entity\Product'));
$form->bind($product);
return new ViewModel(array('form' => $form));
}
}
我的观点
<div class="well">
<?php
$form = $this->form;
$form->setAttribute('method','post');
echo $this->form()->openTag($form);
echo $this->formSelect($form->get('productGroups'));
echo $this->form()->closeTag($form);
?>
</div>
这个空选择框的输出。即使在我的编辑表单中,设置相同但下拉列表为空并且肯定有相关项目。
注意:我只显示了与此问题相关的信息。
我想知道如何通过显示相关项目来解决这个问题。最好只使用注释。
谢谢。