Symfony 2:避免在没有上传照片时持久保存照片实体

时间:2016-03-18 09:40:51

标签: php symfony doctrine-orm

我有一个实体 AdsList 代表广告,我已经关联了实体照片。 当我创建或更新实体 AdsList 时,即使我没有上传照片而我也不想在数据库的照片表中创建新行那会发生。我希望只有在上传照片时才更新表格。

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;

此处的格式为 AdsListType

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 

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

1 个答案:

答案 0 :(得分:0)

如果没有文件设置 我们不应该触摸图像属性

/**
 * 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实体与Photo Entity链接,而不是来自不正确的控制器。