0

I have 2 entities that are related with a OneToOne relationship. I embeded the inverse side into the form, and everything works fine, except that the link between the relationship is not stored. So: The "Begeleider" is saved and the "CompetentieProfiel" is saved, but the column that references the "Begeleider" inside "CompetentieProfiel" table is null.

Ath the moment flush() is called, the "Begeleider" object has the "CompetentieProfiel" object as variable.

Contact:

class Contact { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; } 

Begeleider:

class Begeleider extends Contact { /** * @ORM\OneToOne(targetEntity="CompetentieProfiel", mappedBy="begeleider" ,cascade={"persist"}) */ private $competentieProfiel; } 

CompetentieProfiel:

class CompetentieProfiel { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToOne(targetEntity="Begeleider", inversedBy="competentieProfiel",cascade={"persist"}) */ protected $begeleider; } 

Form:

class BegeleiderType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('competentieProfiel', new CompetentieProfielType()); } 

Controller:

public function createAction(Request $request) { $entity = new Begeleider(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); // Return the ok status and the begeleider html. $response = new Response( json_encode( array( 'status' => 'ok', ) ) ); $response->headers->set('Content-Type', 'application/json'); return $response; } 

1 Answer 1

1

While you are associating the object from one side you are not from the other. So A is associated with B but B isn't associated with A, if that makes any sense.

From what I know the best way is to add a check in your setter to set the associating object like so.

In Aaaa

public function setBbbb(Bbbb $bbbb) { if (null === $bbbb->getAaaa() || $this !== $bbbb->getAaaa()) { $bbbb->setAaaa($this); } $this->bbbb = $bbbb; return $this; } 

In Bbbb

public function setAaaa(Aaaa $aaaa) { if (null === $aaaa->getBbbb() || $this !== $aaaa->getBbbb()) { $aaaa->setBbbb($this); } $this->aaaa = $aaaa; return $this; } 

This way when either of the sides are set then the other side is automatically set too.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.