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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With