Vichuploaderbundle: fileNameProperty with slug

Created on 17 Aug 2017  路  14Comments  路  Source: dustin10/VichUploaderBundle

Hi everybody,

I am trying to upload a video from a simple form. My aim is to make the video file be named with the slug of the Entity that I am persisting.

So the entity looks like this:

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @var File
 * 
 * @Vich\UploadableField(mapping="participant_video",
 *                       fileNameProperty="videoName")
 */
private $videoFile;


public function setUpdatedAt($updatedAt)
{
    $this->updatedAt = $updatedAt;

    return $this;
}

public function getUpdatedAt()
{
    return $this->updatedAt;
}

public function setVideoFile(UploadedFile $video = null)
{
    $this->videoFile = $video;

    if ($video) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime();
    }

    return $this;
}

public function getVideoFile()
{
    return $this->videoFile;
}

public function setVideoName($videoName)
{
    $this->videoName = $videoName;

    return $this;
}

public function getVideoName()
{
    return $this->videoName;
}

and my form is like this:

use Vich\UploaderBundle\Form\Type\VichFileType;

$builder->add('firstName')
        ->add('videoFile', VichFileType::class, array(
            'required' => true,
            'allow_delete' => false));

My config.yml looks like this:

vich_uploader:
    db_driver: orm # or mongodb or propel or phpcr
    mappings:
        participant_video:
            uri_prefix: /participant/video
            upload_destination: '%kernel.root_dir%/../web/video'
            directory_namer: vich.video.namer
            # namer: vich.video.namer
            namer: vich_uploader.namer_uniqid

And to finish my controller:

/**
 * @Route("/{slug}/participant/register", name="register_participant")
 * @Security("has_role('ROLE_USER')")
 */
public function addAction(Request $request, Event $event)
{
    $participant = new Participant();
    $participant->setEvent($event);

    $form = $this->createForm(ParticipantType::class, $participant);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($participant); // the exception is set here
        $em->flush();

        return $this->redirectToRoute('participant_view', array(
            'slug' => $participant->getSlug()));
    }
    $title = 'Register a new user for "' . $event->getName() . '".';
    return $this->render('participant/form.html.twig', array(
        'title' => $title,
        'event' => $event,
        'form' => $form->createView()));
}

The problems is that when I submit the form, this error happens: The file "" does not exist.

So I am guessing that the slug is not generated yet and so the variable is empty. Am I right?

The stacktrace when I submit the form:

Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException:
The file "" does not exist

  at vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php:123
  at Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser->guess('')
     (vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/File/File.php:79)
  at Symfony\Component\HttpFoundation\File\File->getMimeType()
     (vendor/vich/uploader-bundle/Storage/AbstractStorage.php:65)
  at Vich\UploaderBundle\Storage\AbstractStorage->upload(object(Participant), object(PropertyMapping))
     (vendor/vich/uploader-bundle/Handler/UploadHandler.php:64)
  at Vich\UploaderBundle\Handler\UploadHandler->upload(object(Participant), 'videoFile')
     (vendor/vich/uploader-bundle/EventListener/Doctrine/UploadListener.php:41)
  at Vich\UploaderBundle\EventListener\Doctrine\UploadListener->prePersist(object(LifecycleEventArgs))
     (vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php:63)
  at Symfony\Bridge\Doctrine\ContainerAwareEventManager->dispatchEvent('prePersist', object(LifecycleEventArgs))
     (vendor/doctrine/orm/lib/Doctrine/ORM/Event/ListenersInvoker.php:117)
  at Doctrine\ORM\Event\ListenersInvoker->invoke(object(ClassMetadata), 'prePersist', object(Participant), object(LifecycleEventArgs), 4)
     (vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:892)
  at Doctrine\ORM\UnitOfWork->persistNew(object(ClassMetadata), object(Participant))
     (vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1679)
  at Doctrine\ORM\UnitOfWork->doPersist(object(Participant), array('000000003dd0353100000000455af055' => object(Participant)))
     (vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1635)
  at Doctrine\ORM\UnitOfWork->persist(object(Participant))
     (vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:579)
  at Doctrine\ORM\EntityManager->persist(object(Participant))
     (src/AppBundle/Controller/ParticipantController.php:36)
  at AppBundle\Controller\ParticipantController->addAction(object(Request), object(Event))
  at call_user_func_array(array(object(ParticipantController), 'addAction'), array(object(Request), object(Event)))
     (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:153)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:68)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php:171)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (web/app_dev.php:29)
  at require('/home/paul/Dev/registration_app/web/app_dev.php')
     (vendor/symfony/symfony/src/Symfony/Bundle/WebServerBundle/Resources/router.php:42)
Support

Most helpful comment

That was my error, the problems came from the PHP variables in php.ini: post_max_size and upload_max_filesize which were to low. Sorry for the time taken :/

All 14 comments

Is the sluggable working, without file upload?

Yes it is working well.

is this happening only for a new entity (e.g. create), or also for an old one (e.g. update)?

It's the same for the update, I have added some code in the issue.

You can't use the slug field as fileNameProperty. You need a different, dedicated field for that. Then you need to use a namer, as described in docs.

I finally think the problem comes from somewhere else, I tried a lot of things (with custom namers, without custom namers etc.) but the error at the end is always the same: The file "" is not found.

I have updated my issue to the new configuration and printed the stack trace. I begin to be desperate --'. It is probably something stupid from an include or something.

It looks like there's a problem with the path of your uploaded file. Did you clear the cache?

Yes I did, and I tried without the directory namer and it still doesn't work. I verified the path in the config.yml and the folder video exists in the web folder.

You can try to add some dump() in the files of your stack trace, to try to find the point where the uploaded file is lost

If I insert a dump($participant); just after the $form->handleRequest($request); This same error is thrown.

at ServerLogHandler->handle(array('message' => 'Uncaught PHP Exception Symfony\\Component\\HttpFoundation\\File\\Exception\\FileNotFoundException: "The file "" does not exist" at /home/paul/Dev/registration_app/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php line 123', 'context' => array('exception' => object(FileNotFoundException)), 'level' => 500, 'level_name' => 'CRITICAL', 'channel' => 'request', 'datetime' => object(DateTime), 'extra' => array()))in Logger.php (line 337)

It's too late there

I have tested just before and there is not problem until the persist(). So I suppose it means that the handleRequest is missing to attribuate a variable. Is it correct?

I don't know. You need to go deeper and dump() inside your stack (not in the controller)

That was my error, the problems came from the PHP variables in php.ini: post_max_size and upload_max_filesize which were to low. Sorry for the time taken :/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

WassabiVl picture WassabiVl  路  3Comments

cipherchien picture cipherchien  路  3Comments

ngilain picture ngilain  路  5Comments

webkmua picture webkmua  路  4Comments

benIT picture benIT  路  3Comments