【问题标题】:Vich UploadedFile, FOSUserBundle and EventsVich UploadedFile、FOSUserBundle 和事件
【发布时间】:2018-01-19 07:19:34
【问题描述】:

我在编辑配置文件树枝模板上添加了一个 VichImageType 字段...所以我尝试使用 vich_uploader.pre_upload 作为事件来检查图像尺寸。

在我的课堂上,我得到了图像属性,如果它们的尺寸不够大,我试图停止传播并向树枝模板闪现一条消息,但是我不知道为什么,事件不断传播并重定向到 fos_user_profile_show 显示图像设置.另外,我尝试再次重定向到 fos_user_profile_edit,但我不能使用 $event,因为“Vich\UploaderBundle\Event\Event”没有实现 setController()。如何做到这一点?

这是Listener类的方法:

namespace BackendBundle\EventListener;

use Vich\UploaderBundle\Event\Event;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;

class ComprobarDimensionesDeImagen
{

private $requestStack;
private $router;

public function __construct(RequestStack $requestStack, RouterInterface $router)
{
    $this->requestStack = $requestStack;
    $this->router = $router;
}

public function onVichUploaderPreUpload(Event $event)
{
    $object = $event->getObject();
    $mapping = $event->getMapping();

    $imagen = getimagesize($object->getImageFile());

    if (250 > $imagen[0] || 250 > imagen[1]) {
        $request = $this->requestStack->getCurrentRequest();
        $session = $request->getSession();

        $event->stopPropagation();
        $session->getFlashBag()->add('error', "Minimum dimensions: 250x250 \n");

        $url = $this->router->generate('fos_user_profile_edit');
        /*
         * Testing different methods of redirect
         * 
         * $response = new RedirectResponse($url);
         * $event->setResponse($response);
         */

        $event->setController(function() use ($request) {
            return new RedirectResponse($url);
        });            
    }
}
}

当我再次编辑配置文件时,我可以在 VichImageType 字段中看到 flash 消息和图像设置(我没想到会停止传播)。非常欢迎任何帮助。

已解决:只需在我的 Entity 类中使​​用 @Assert\Image 即可进行验证。既不需要服务也不需要监听器

【问题讨论】:

    标签: symfony fosuserbundle symfony-2.8 vichuploaderbundle


    【解决方案1】:

    ->setController 的参数必须是 callable 。在您的情况下,您作为参数传递的函数返回响应类型的对象。为了可调用,该方法应具有后缀Action。另见this post

    【讨论】:

    • 对不起,我不明白。现在我知道 $event 参数不可调用,但它是事件 vich_uploader.pre_upload 返回的对象。如何重定向到 fos_user_profile_edit 以解决该事件不断传播或引发表单异常?
    • 不,我说的是你作为 $event->setController() 的参数传递的 function() 。如文档中所述,此参数必须是可调用的,我相信您的匿名函数(或它返回的)不是。
    • 好的,谢谢。无论如何,我解决问题的方法是错误的。我只需要在链接到 Form 的实体类中使用带有 Assert 的 Image 约束,而不是我选择的复杂路径。这样Form的验证就可以了。感谢您的回复。
    • 是的,没错,最好的方法。祝你的项目好运!
    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2016-03-23
    相关资源
    最近更新 更多