Alfonso Fernandez-Ocampo Alfonso Fernandez-Ocampo - 1 year ago 71
PHP Question

Symfony 2: Avoid persisting photo entity collection when no photo is uploaded

I have an entity AdsList which represents ads and I have linked entity Photos.
When I create or update the entity AdsList a new row is created in the Photos table in the database even when I do not upload a photo and I don't want that to happen. I wish the table to be updated ONLY if there is a photo uploaded.

The AdsList entity:

namespace obbex\AdsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

use obbex\AdsBundle\Entity\Photos;

* AdsList
* @ORM\Table()
* @ORM\Entity
* @ORM\Entity(repositoryClass="obbex\AdsBundle\Entity\AdsListRepository")
* @ORM\HasLifecycleCallbacks()
class AdsList
... several properties
* @ORM\OneToMany(targetEntity="obbex\AdsBundle\Entity\Photos",mappedBy="adslist", cascade={"persist","remove"})
* @ORM\JoinColumn(nullable=true)
protected $photos;

... more getters and setters

And this is the entity Photos

namespace obbex\AdsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;

* Photos
* @ORM\Table()
* @ORM\Entity(repositoryClass="obbex\AdsBundle\Entity\PhotosRepository")
* @ORM\HasLifecycleCallbacks
class Photos
* @ORM\ManyToOne(targetEntity="obbex\AdsBundle\Entity\AdsList", inversedBy="photos")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="adslist_id", referencedColumnName="id",onDelete="CASCADE")
* })
protected $adslist;

And here is the form AdsListType

class AdsListType extends AbstractType
* @param FormBuilderInterface $builder
* @param array $options
public function buildForm(FormBuilderInterface $builder, array $options)
->add('telephone', IntegerType::class,array('required'=>false))
->add('description', TextareaType::class)
->add('country', EntityType::class,array(
'class' => 'obbexAdsBundle:Countries',
->add('address',TextType::class, array('required' => false))
->add('publication', CheckboxType::class)
->add('price', IntegerType::class)
->add('photos',CollectionType::class, array('entry_type'=> 'obbex\AdsBundle\Form\PhotosType',
'allow_add' => true,
'data'=>array(new Photos() ),
'required' => false
->add('save', SubmitType::class)

public function configureOptions(OptionsResolver $resolver) {
'data_class' => 'obbex\AdsBundle\Entity\AdsList',

I guess that there is a procedure in order to avoid persisting the Photos entity but I've tried in the controller:

public function editAdAction(Request $request,AdsList $ads){

$em = $this->getDoctrine()->getManager();

$form = $this->createForm(AdsListEditType::class, $ads);

if ($form->isValid()) {
//this condition in case no photo is uploaded
if($form->get('photos')->getData()[0]->getFile() === null){
$photos = $ads->getPhotos();
//what do here? or maybe the problem is somewhere else
//I've tried $em->refresh($photo); but it throws the error I gave
$id = $ads->getId();
return $this->redirect($this->generateUrl('ad_edition',array('id'=>$id)));
return $this->render('obbexAdsBundle:Default:editAd.html.twig',

But I have the following error

Entity obbex\AdsBundle\Entity\Photos@000000000b2d669200007fb2152337c5
is not managed. An entity is managed if its fetched from the database or
registered as new through EntityManager#persist

Has anyone done this? it seems pretty standard to me. In case no photo is uploaded don't do anything in the database to keep it clean

Answer Source

In the case there is no file set We should not touch the image property

 * Add image
 * @param \obbex\AdsBundle\Entity\Photo $image
 * @return Painting
public function addImage(\Art\GeneralBundle\Entity\Photo $photo)
    if($photos->getFile() !== NULL){
        $this->photos[] = $photo;


    return $this;

and then no photo will be persisted if the field file is not filled with information.

Note that I linked the AdsList entity with the Photo Entity via the object AdsList itself not from the controller which was incorrect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download