symfonyoneupuploaderbundle

OneupUploaderBundle: Render response message in twig template


I use the OneupUploaderBundle in my project to upload files.

My question is:

How can i render the response.msg from the UploadListener in my twig template? How can I evaluate my response.

https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/response.md

//service.yml

acme.upload_listener:
    class: Acme\AcmeBundle\EventListener\UploadListener
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
      - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload }

//UploadListener.php

class UploadListener
{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function onUpload(PostPersistEvent $event)
    {
        $file = $event->getFile();
        $session = $event->getRequest()->getSession();
        $session->set('file', $file->getPathName());

        $response = $event->getResponse();

        $response['msg'] = "File stored in session";

        => show response.msg in my twig-template. But how?
    }
} 

//JS (in twig template)

$('#fileupload').fileupload({});

I have no examples found...

Thank's for your help.


Solution

  • Well, you can't do this in your Twig template. The Twig templates are rendered on page load and the file upload is done using Ajax. What you can do is altering the DOM in javascript.

    For example:

    $('#fileupload').fileupload({}).bind('fileuploaddone', function (e, data) {
        $("body").prepend('<p>File stored in session</p>');
    });
    

    You can also send some data back to the client:

    $('#fileupload').fileupload({}).bind('fileuploaddone', function (e, data) {
        if (data.result.filename != undefined) {
            $("body").prepend('<p>File ' + data.result.filename + ' stored in session</p>');
        }
    });
    

    But in order to do that, you need to create an event listener for the oneup_uploader.post_persist event that will send the filename back with the response, as explained in the documentation to which you linked.

    <?php
    
    namespace Foo\BarBundle\EventListener;
    
    use Oneup\UploaderBundle\Event\PostPersistEvent;
    
    class UploadListener
    {
        public function onUpload(PostPersistEvent $event)
        {
            $request = $event->getRequest();
            $files = $request->files->get('files');
            $response = $event->getResponse();
            $filename = $files[0]->getClientOriginalName();
            $response['filename'] = $filename;
        }
    }
    

    In your services.yaml:

    # Event listener to handle uploaded files
    foobar.upload_listener:
        class: Foo\BarBundle\EventListener\UploadListener
        tags:
            - { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onUpload }