I have a entity Centros.php
defined as follow:
<?php
namespace PI\CentroBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="centros")
*/
class Centros {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="text")
*/
protected $descripcion;
public function getId() {
return $this->id;
}
public function setDescripcion($descripcion) {
$this->descripcion = $descripcion;
}
public function getDescripcion() {
return $this->descripcion;
}
}
And also has this another UnidadesHasCentros.php
with this definition:
<?php
namespace PI\UnidadBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="unidades_has_centros")
*/
class UnidadesHasCentros {
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="PI\UnidadBundle\Entity\Unidades")
* @ORM\JoinColumn(name="unidades_id", referencedColumnName="id")
*/
protected $unidades_id;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="PI\CentroBundle\Entity\Centros")
* @ORM\JoinColumn(name="centros_id", referencedColumnName="id")
*/
protected $centros_id;
public function setUnidadesId(\PI\UnidadBundle\Entity\Unidades $unidad_id) {
$this->unidades_id = $unidad_id;
}
public function getUnidadesId() {
return $this->unidades_id;
}
public function setCentroId(\PI\CentroBundle\Entity\Centros $centros_id) {
$this->centros_id = $centros_id;
}
public function getCentroId() {
return $this->centros_id;
}
}
This is my CentroType.php
form and as yours can see I have the entity unmapped:
<?php
namespace PI\CentroBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CentroType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('unidades', 'entity', array('class' => 'PIUnidadBundle:Unidades', 'property' => 'descripcion', 'required' => false, 'multiple' => true, 'expanded' => false, 'mapped' => false, 'attr' => array('class' => 'form-control')))
->add('descripcion', 'text', array('attr' => array('class' => 'form-control')));
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'PI\CentroBundle\Entity\Centros'
));
}
public function getName() {
return 'centro';
}
}
When I create a new Centro I can assign Unidades without problem as follow:
public function createAction(Request $request) {
$entity = new Centros();
$form = $this->createForm(new CentroType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
if ($request->get('unidades')) {
foreach ($request->get('unidades') as $key => $value) {
$entityUnidadesHasCentros = new UnidadesHasCentros();
$entityUnidadesHasCentros->setCentroId($entity);
$entityUnidadesHasCentros->setUnidadesId($value);
$em->persist($entityUnidadesHasCentros);
}
$em->flush();
}
}
return $this->redirect($this->generateUrl('listar-centros'));
}
But how I handle this from edit/update actions? I mean I need to get all the relation and display it in the edit form but don't know how to. If yours has a better solution let me know.
$em = $this->getDoctrine()->getManager();
$centro = $em->getRepository('PIUnidadBundle:Centros')->find($id_centro);
$form = $this->createForm(new CentroType(), $centro);
Will populate the form automatically.
To give you an idea here is part of the CRUD for my Feed class
/**
* Displays a form to edit an existing Feed entity.
*
* @Route("/{id}/edit", name="admin_feed_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('CitationRssBundle:Feed')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Feed entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Feed entity.
*
* @param Feed $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Feed $entity)
{
$form = $this->createForm(new FeedEditType(), $entity, array(
'action' => $this->generateUrl('admin_feed_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'mettre à jour', 'attr' => array('class' => 'btn-primary')));
return $form;
}
/**
* Edits an existing Feed entity.
*
* @Route("/{id}", name="admin_feed_update")
* @Method("PUT")
* @Template("CitationRssBundle:Feed:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('CitationRssBundle:Feed')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Feed entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('admin_feed_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Feed entity.
*
* @Route("/{id}", name="admin_feed_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('CitationRssBundle:Feed')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Feed entity.');
}
$em->remove($entity);
$em->flush();
$em->clear();
}
return $this->redirect($this->generateUrl('admin_feed'));
}
/**
* Creates a form to delete a Feed entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin_feed_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'supprimer', 'attr' => array('class' => 'btn-danger')))
->getForm()
;
}
Don't forget that you can also generate crud using the doctrine:generate:crud command it saves a lot of time :)
This is not what I'm asking for Tom Toms, what I need and ask is the right way to create the relationship and this is the solution:
/**
* @ORM\ManyToMany(targetEntity="PI\UnidadBundle\Entity\Unidades", inversedBy="centros", cascade={"persist"})
* @ORM\JoinTable(name="unidades_has_centros",
* joinColumns={@ORM\JoinColumn(name="centros_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="unidades_id", referencedColumnName="id")}
* )
*/
protected $unidades;
After that you'll need to create proper methods and constructor as follow:
public function __construct() {
$this->unidades = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setUnidades(\PI\UnidadBundle\Entity\Unidades $unidades) {
$this->unidades[] = $unidades;
}
public function getUnidades() {
return $this->unidades;
}
Hope that help others
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.