dongrong9053 2016-03-18 09:40
浏览 47
已采纳

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

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)
     {
        $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',
    ));
}
}

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);

    $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()
        ));
    }

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

  • 写回答

1条回答 默认 最新

  • dongzhanlu8890 2016-10-10 15:42
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘