Symfony 2:避免在没有上传照片时保留照片实体集合


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

我有一个代表广告的实体广告列表,并且我链接了实体照片。当我创建或更新实体 AdsList 时,即使我没有上传照片并且不希望发生这种情况,也会在数据库的照片表中创建一个新行。我希望只有在上传照片时才更新表格。

广告列表实体:

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

这是实体 照片

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;

这是表格 广告列表类型

class AdsListType extends AbstractType
{
     /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
     public function buildForm(FormBuilderInterface $builder, array $options)
     {
        $builder
            ->add('email',TextType::class)
            ->add('telephone',  IntegerType::class,array('required'=>false))
             ->add('displayPhone',CheckboxType::class,array('required'=>false,'attr'=>array('checked'=>false)))
        ->add('title',TextType::class)
        ->add('description', TextareaType::class)
        ->add('country', EntityType::class,array(
            'class' => 'obbexAdsBundle:Countries',
            'choice_label'=>'countryName',
            'multiple'=>false
        ))
        ->add('region',TextType::class)
        ->add('department',TextType::class)
        ->add('address',TextType::class, array('required' => false))
        ->add('city',TextType::class)
        ->add('zipCode',TextType::class)
        ->add('statusPro',TextType::class)
        ->add('publication',  CheckboxType::class)
        ->add('price',  IntegerType::class)
        ->add('photos',CollectionType::class, array('entry_type'=>  'obbex'AdsBundle'Form'PhotosType',
                                            'allow_add' => true,
                                            'allow_delete'=>true,
                                            'data'=>array(new Photos() ),
                                            'required' => false
                                        )
             )
        ->add('save',  SubmitType::class)
    ;
}
public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'obbex'AdsBundle'Entity'AdsList',
    ));
}
}

我想有一个过程可以避免保留照片实体,但我已经在控制器中尝试过:

public function editAdAction(Request $request,AdsList $ads){
    $em = $this->getDoctrine()->getManager();
    $form = $this->createForm(AdsListEditType::class, $ads);
    $form->handleRequest($request);
    if ($form->isValid()) {
        if($form->get('save')->isClicked()){
            //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
            }
            $em->flush();
            $id = $ads->getId();
            return $this->redirect($this->generateUrl('ad_edition',array('id'=>$id)));
        }
return $this->render('obbexAdsBundle:Default:editAd.html.twig',
        array(
            'ads'=>$ads,
            'form'=>$form->createView()
        ));
    }

但是我有以下错误

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 

有人这样做过吗? 这对我来说似乎很标准。如果没有上传照片,请不要在数据库中执行任何操作以保持其清洁

在没有文件集的情况下我们不应该触摸图像属性

/**
 * 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;
        $image->setAdlist($this);
    }
    return $this;
}

然后,如果字段文件未填充信息,则不会保留任何照片。

请注意,我通过对象 AdsList 本身而不是来自控制器将 AdsList 实体与照片实体链接,这是不正确的。