1
我在多對多關聯中有2個實體。Symfony2 - 創建關聯的表單出錯(多對多)
/**
* @ORM\Table()
* @ORM\Entity()
*/
class Clown
{
...
/**
* @ORM\ManyToMany(targetEntity="Appuntamento", inversedBy="partecipanti")
* @ORM\JoinTable(name="partecipa")
*/
private $appuntamenti;
public function __construct() {
$this->appuntamenti = new ArrayCollection();
}
...
public function addAppuntamenti(Appuntamento $app)
{
$this->appuntamenti[] = $app;
}
public function getAppuntamenti()
{
return $this->appuntamenti;
}
}
/**
* @ORM\Table()
* @ORM\Entity()
*/
class Appuntamento
{
/**
* @ORM\ManyToMany(targetEntity="Clown", mappedBy="appuntamenti")
*/
private $partecipanti;
public function __construct() {
$this->partecipanti = new ArrayCollection();
}
...
public function addPartecipanti(Clown $partecipante)
{
$partecipante->addAppuntamenti($this);
$this->partecipanti[] = $partecipante;
}
public function getPartecipanti()
{
return $this->partecipanti;
}
}
然後,我創建的形式,允許設置一個Appuntamento的與會者(又名「partecipanti」)。
namespace Clown\DiaryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class PartecipantiType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title')
->add('partecipanti', 'entity', array(
'class' => 'ClownDiaryBundle:Clown',
'property' => 'drname',
'multiple' => true,
'expanded' => true,
))
;
}
public function getName()
{
return 'clown_diarybundle_partecipantitype';
}
}
現在我在控制器中創建操作,一個顯示錶單,一個更新實體。
/**
* @Route("/{id}/partecipanti", name="admin_appuntamento_partecipanti")
* @Template()
*/
public function partecipantiAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ClownDiaryBundle:Appuntamento')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Appuntamento entity.');
}
$partecipantiForm = $this->createForm(new PartecipantiType(), $entity);
return array(
'entity' => $entity,
'partecipanti_form' => $partecipantiForm->createView(),
);
}
/**
* @Route("/{id}/update_partecipanti", name="admin_appuntamento_update_partecipanti")
* @Method("post")
* @Template("ClownDiaryBundle:Appuntamento:partecipanti.html.twig")
*/
public function updatePartecipantiAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ClownDiaryBundle:Appuntamento')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Appuntamento entity.');
}
$partecipantiForm = $this->createForm(new PartecipantiType(), $entity);
$request = $this->getRequest();
$partecipantiForm->bindRequest($request);
if ($partecipantiForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('admin_appuntamento_show', array('id' => $id)));
}
return array(
'entity' => $entity,
'partecipanti_form' => $partecipantiForm->createView(),
);
}
但是當我在第二個動作後,我努力堅持的目標,沒有任何關聯(小丑和Appuntamento之間)已創建。 我忘記了什麼嗎?
它的工作改變了擁有和反側。感謝Cyprian! –