0

我有一个Centros.php定义如下的实体:

<?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;
    }

}

并且还有另一个UnidadesHasCentros.php具有此定义的:

<?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;
    }

}

这是我的CentroType.php表格,你可以看到我没有映射实体:

<?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';
    }

}

当我创建一个新的 Centro 时,我可以毫无问题地分配 Unidades,如下所示:

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'));
}

但是我如何通过编辑/更新操作来处理这个?我的意思是我需要获取所有关系并将其显示在编辑表单中,但不知道如何操作。如果您有更好的解决方案,请告诉我。

4

2 回答 2

0
$em = $this->getDoctrine()->getManager();
$centro = $em->getRepository('PIUnidadBundle:Centros')->find($id_centro);
$form = $this->createForm(new CentroType(), $centro);

将自动填充表单。

在这里给你一个想法是我的 Feed 类的 CRUD 的一部分

/**
 * 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()
    ;
}

不要忘记,您也可以使用教条生成 crud:generate:crud 命令,它可以节省大量时间 :)

于 2013-11-13T22:19:12.403 回答
0

这不是我对 Tom Toms 的要求,我需要并要求的是建立关系的正确方法,这就是解决方案:

/**
 * @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;

之后,您需要创建正确的方法和构造函数,如下所示:

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;
}

希望能帮助别人

于 2013-11-14T12:58:21.820 回答