Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony form collection not saving reference

I have entity which has multiple Photos:

/**
 * related images
 * @ORM\OneToMany(targetEntity="Photo", mappedBy="entity",cascade={"persist"})
 * @ORM\OrderBy({"uploaded_at" = "ASC"})
 */
private $photos;

Photos have ManyToOne relation with entity

    /**
 * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\Entity", inversedBy="photos")
 * @ORM\JoinColumn(name="entity_id", referencedColumnName="id", onDelete="CASCADE")
 */
private $entity;

all setters and getter are set I'm foliving symfony collection documentation: http://symfony.com/doc/current/reference/forms/types/collection.html

FormType:

             ->add('photos', 'collection', array(
             'type' => new PhotoFormType(),
             'allow_add' => true,
             'by_reference' => false,
             'allow_delete' => true,
             'prototype' => true

         ))

PhotoType:

        $builder
        ->add('title', null, ['label' => 'front.photo.title', 'required' => true])
        ->add('image', 'file', array('required' => false))
    ;

For upload I'm using vichUploadableBundle, Images are save just fine, but entity_id is not save and has null. I don't know what I did miss here.

like image 373
zajca Avatar asked Dec 11 '22 23:12

zajca


1 Answers

Following would be best solution on this issue so far investigate or research with symfony form component.

FormType:

     ->add("photos",'collection', array(
            'type' => new PhotoFormType(),
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false
))

Entity class

public function addPhoto(Photo $photo)
{
    $photo->setEntity($this);
    $this->photos->add($photo);        
}

public function removePhoto(Photo $photo)
{
    $this->photos->removeElement($photo);
}

Best practice is not to use loop to bind reference entity manually . Remember by_reference must be false. like 'by_reference' => false.

like image 142
Julfiker Avatar answered Dec 17 '22 04:12

Julfiker