简体   繁体   English

更新表单vich上传器,无法删除或编辑文件

[英]Update form vich uploader, cannot delete or edit file

I can't delete or edit my uploaded image with VichUploaderBundle. 我无法使用VichUploaderBundle删除或编辑上传的图像。 I have an Annonce and Photo entities with OneToMany (bidirectionnal relation). 我有一个OneToMany(双向关系)的Annonce和Photo实体。 I try with an attribute setUpdatedAt to call vich prePersist but he doesn't work. 我尝试使用属性setUpdatedAt来调用vich prePersist,但是他不起作用。

Here is Annonce : 这是Annonce:

class Annonce
{
// ...
/**
 * @ORM\OneToMany(targetEntity="Immo\AnnonceBundle\Entity\Photo", mappedBy="annonce", cascade={"persist", "remove"})
 */
private $photos;

Photo entity with setter/getterImage() : 具有setter / getterImage()的照片实体:

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Photo
 * @Vich\Uploadable
 * @ORM\Table()
 */
class Photo
{   // id, etc. 
    /**
     * @Assert\File(
     *     maxSize="1M",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     * @Vich\UploadableField(mapping="uploads_image", fileNameProperty="url")
     *
     * @var File $image
     */
    protected $image;

    /**
     * @ORM\Column(type="string", length=255, name="url")
     *
     * @var string $url
     */
    protected $url;

    /**
     * @ORM\ManyToOne(targetEntity="Immo\AnnonceBundle\Entity\Annonce", inversedBy="photos")
     */
    private $annonce;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     *
     * @var \DateTime $updatedAt
     */
    protected $updatedAt;

/**
 * Set image
 *
 * @param string $image
 * @return Photo
 */
public function setImage($image)
{
    $this->image = $image;

    if ($this->image instanceof UploadedFile) {
        $this->updatedAt = new \DateTime('now');
    }

    return $this;
}

Here is my config.yml: 这是我的config.yml:

knp_gaufrette:
stream_wrapper: ~
adapters:
    uploads_adapter:
        local:
            directory: %kernel.root_dir%/../web/img/uploads
filesystems:
    uploads_image_fs:
        adapter:    uploads_adapter

vich_uploader:
    db_driver: orm
    twig: true
    gaufrette: true
    storage:   vich_uploader.storage.gaufrette
    mappings:
        uploads_image:
            delete_on_remove: true
            delete_on_update: true
            inject_on_load: true
            uri_prefix:         img/uploads
            upload_destination: uploads_image_fs
            namer: vich_uploader.namer_uniqid

My AnnonceType: 我的AnnonceType:

$builder->add('photos', 'collection', array('type' => new PhotoType(),
                                                'allow_add' => true,
                                                'allow_delete' => true,
                                                'by_reference' => false,
                                                )
                  )

PhotoType: 照排机:

$builder->add('image', 'file')

The Controller : 控制器:

public function updateAnnonceAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $annonce = $em->getRepository('ImmoAnnonceBundle:Annonce')
                      ->findCompleteAnnonceById($id);

        $form = $this->createForm(new AnnonceType, $annonce);

        $request = $this->get('request');

        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {

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

                $em->persist($annonce);
                $em->flush();

                $this->get('session')->getFlashBag()->add('success', 'ok');

                return $this->redirect($this->generateUrl('immo_admin_annonce_homepage'));

            }
        }

        return $this->render('ImmoAnnonceBundle:Admin/Annonce:update.html.twig', array('annonce' => $annonce,
                                                                       'form' => $form->createView()
                                                                                      )
                            );
    }

And my template put input file for each Photo in Annonce in html : 我的模板在html中将每张照片的输入文件放入Annonce中:

{{ form_widget(form.photos) }} // With JS to manage add/delete on each input.
// Return this :
<input type="file" required="required" name="immo_annoncebundle_annonce[photos][2][image]" id="immo_annoncebundle_annonce_photos_2_image">

在您的实体中添加“ updateAt”属性有关更多信息,请参见http://mossco.co.uk/symfony-2/vichuploaderbundle-how-to-fix-cannot-overwrite-update-uploaded-file/

I know it is an old thread, but David's answer was not working in this case since OP tries to delete the Photo object within the Annonce object once it gets updated. 我知道这是一个旧线程,但是在这种情况下,David的答案不起作用,因为OP一旦更新后便尝试删除Annonce对象中的Photo对象。

I had a similar case where i just had to check if the path (fileName) of the Photo object was null after the request handling (after performing a delete operation from the formular) and then if it is the case, i remove manually the Photo object calling entitymanager to perform the operation. 我有类似的情况,我只需要检查请求处理之后(在从公式器执行删除操作之后),Photo对象的路径(文件名)是否为空,然后,如果是这种情况,我会手动删除Photo对象调用entitymanager来执行操作。

Looking into the code of VichUploaderBundle (see the remove method of UploadHandler class) shows that an event is being dispatched after requesting the deletion, and you could also bind to this event Events::POST_REMOVE (vich_uploader.post_remove) somewhere to handle the deletion. 查看VichUploaderBundle的代码(请参见UploadHandler类的remove方法)显示,请求删除后正在调度事件,您还可以在某个地方绑定此事件Events :: POST_REMOVE(vich_uploader.post_remove)来处理删除。 This solution sounds cleaner although the first one is also working well. 尽管第一个解决方案也运行良好,但此解决方案听起来更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM