Relations while updating entity in Symfony2 - one-

2019-08-08 04:54发布

I've a problem with updating an entity(it is inversed side) in form, while the entity is properly updated with all the data, the related to it other entities are not, i.e in database their column referencing the "main" entity remain null or the data remain untouched.

Here is the code:

class Offer
{
 /**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="DealOption", mappedBy="offer", cascade={"persist"})
 */
private $dealOptions;

/**
 * @var Event
 *
 * @ORM\OneToOne(targetEntity="Event", inversedBy="offer")
 * @ORM\JoinColumn(name="event_id", referencedColumnName="id")
 */
private $event;
}


class DealOption
{
/**
 * @var Offer
 *
 * @ORM\ManyToOne(targetEntity="Offer", inversedBy="dealOptions")
 * @ORM\JoinColumn(name="offer_id", referencedColumnName="id", onDelete="SET NULL")
 */
private $offer;
}


class Event
{
/**
 * @var Offer
 *
 * @ORM\OneToOne(targetEntity="Offer", mappedBy="event")
 * @ORM\JoinColumn(name="offer_id", referencedColumnName="id", onDelete="SET NULL")
 */
private $offer;

And the update action:

public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('AppBundle:Offer')->find($id);
    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Offer.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {

        $em->persist($entity);
        $em->flush();
        return $this->redirect($this->generateUrl('offer'));
    }

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

According to my research and reading similiar problems with documentation it should work as is, however it doesn't, i suspect some basic misunderstanding on my part of how these relations should behave, work and be defined, but to this moment no bueno and no succes. I'd be grateful for any advice.

Edit - OfferFormBuilder:

class OfferType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('dealOptions')
        ->add('title')
        ->add('event')
        ->add('division')
    ;
}

1条回答
神经病院院长
2楼-- · 2019-08-08 05:28

The null indicates that you are not cross referencing the objects properly. It's a very common mistake.

class Offer {
  public function setEvent($event) {
    $this->event = $event;
    $event->setOffer($this); // *** This is what you are probably missing.

Do the same for deals as well.

查看更多
登录 后发表回答