0

I'm on Symfony 2.8. In my Work entity I've got:

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\WorkClaim", mappedBy="claimedWork", cascade={"persist"})
 */
private $claims;

/**
 * @param WorkClaim $claim
 */
public function addClaim(WorkClaim $claim)
{
    $claim->setClaimedWork($this);
    $this->claims->add($claim);
}

/**
 * @param WorkClaim $claim
 */
public function removeClaim(WorkClaim $claim) { /* to be done */ }

(and getter/setter and of course $this->claims = new ArrayCollection(); in the Constructor)

In my WorkClaim entity:

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Work", inversedBy="claims")
 */
private $claimedWork;

(and getter/setter)

My WorkType class has this in the form builder:

->add('claims', CollectionType::class, array(
    'entry_type' => WorkClaimType::class,
    'allow_add' => true,
    'by_reference' => false,
))

WorkClaimType has just some typical fields (EntityType to choose country, two DateType fields and NumberType).

No matter what I do, the addClaim() is called, but the new WorkClaim entities are added with NULL claimed_work_id. What did I miss?

Do I really have to persist every WorkClaim separately in Work controller on createAction()? And if so, how to correctly iterate through them? Trying to call getClaims() on form data gives me no records.

WRonX
  • 161
  • 3
  • 15
  • You need to cross link your entities at the object level: http://stackoverflow.com/questions/34197674/symfony-3-0-nested-entities-not-saving/34204093#34204093 – Cerad Dec 17 '15 at 15:59
  • @Cerad: isn't that handled already? I've got $claim->setClaimedWork($this); inside addClaim()... – WRonX Dec 17 '15 at 16:34
  • That isn't handled already - you're just adding PHP objects to other objects at that point. You must either explicitly persist them in Doctrine, or set the Doctrine entities to cascade persist (so you don't have to do it explicitly). – Jason Roman Dec 17 '15 at 17:32
  • OK, but I've got both, cascade={"persist"} in Work entity and call to SetClaimedWork in AddClaim(). I just don't see what I miss here. – WRonX Dec 17 '15 at 18:57
  • So your claims are actually getting persisted? It's just that the work id is null in the database? Strange. Make sure you don't have any files lurking under Resources/config/doctrine. – Cerad Dec 18 '15 at 13:14
  • And verify the WorkClaim::setClaimedWork($work) is properly implemented. – Cerad Dec 18 '15 at 13:18
  • OK, I really don't know what to say. It works now. And to be honest, I don't remember changing anything. Suddenly the id is not null in the DB now... – WRonX Dec 21 '15 at 08:16

0 Answers0