Pregunta

I have a problem with establishing a bidirectional One-To-One relationship between two entities. I have an entity "Campaign" that CAN reference another entity "DonationData". A donation data that is created is always linked to a campaign. I want a bidirectional relationship because I want to be able to find the related campaign from a DonationData entity.

This is my code for the Campaign Entity :

<?php
/**
 * @ORM\Entity
 * ...
 */
class Campaign
{
...
/**
 * @ORM\OneToOne(targetEntity="DonationData", mappedBy="campaign", cascade={"persist", "remove"})
 */
protected $donationData;

...

/**
 * Set donationData
 *
 * @param DonationData $donationData
 * @return Campaign
 */
public function setDonationData(DonationData $donationData = null)
{
    $this->donationData = $donationData;

    return $this;
}

...

?>

And the related code for my DonationData entity :

<?php
/**
 * @ORM\Entity
 * ...
 */
class DonationData
{
...
/**
 * @ORM\OneToOne(targetEntity="Campaign")
 * @ORM\JoinColumns({
 *     @ORM\JoinColumn(name="campaign_id", referencedColumnName="id")
 * })
 */
protected $campaign;

...

/**
 * Set campaign
 * @param Campaign $campaign
 *
 * @return DonationData
 */
public function setCampaign($campaign)
{
    $this->campaign = $campaign;

    return $this;
}


...
?>

The piece of code where I'm adding my DonationData form in my Campaign Form (CampaignType.php)

<?php
...
->add('donationData', new DonationDataType(), array(
    'label' => false
))
...
?>

And in the CampaignController.php side, when I'm handling the creation operations, I didn't change anything : I'm just persisting the related entity binded from the request, and then flushing the Entity Manager :

<?php
...
$em->persist($campaign);
$em->flush();
...
?>

My problem is when I want to persist a Campaign entity form that has an embedded DonationData form inside. I successfully persist both the Campaign and the DonationData entities, but there is only the donation_data_id reference in the Campaign entry that is persisted. When I look in database to the persisted DonationData, the campaign_id is always set to NULL.

Do you see any explanation for that?

Thank you.

¿Fue útil?

Solución

In class DonationData, field $campaign you don't specify the inversedBy property, should be

@ORM\JoinColumn(name="campaign_id", referencedColumnName="id", inversedBy="donationData")

and did you set the cascade_validation default option in the parent form?

as in http://symfony.com/doc/current/reference/forms/types/form.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top