I have got a question regarding populating my form with entities form a many to many relation.
First my code:
Product Entity:
<?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);
}
}
Then I have My Action
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));
}
}
And my View
<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>
The output of this an empty select box. Even in my edit form where the setup is the same but the dropdown is empty and there are surely related items.
Note: I have only shown the information related to this question.
I would like to know how I can solve this problem whith showing related items. Prefferably only using annotations.
Thanks.