Download Symfony2 file with downloadable stof extension

I am trying to customize a file upload form under Symfony2 with a downloadable extension (stof / doctrine)

here are my entities

club

<?php ... class Club { ... /** * @ORM\ManyToOne(targetEntity="my\TestBundle\Entity\File", cascade={"persist"}) * @ORM\JoinColumn(nullable=true) */ private $logo; ... } 

file

 <?php ... use Gedmo\Mapping\Annotation as Gedmo; use Doctrine\ORM\Mapping as ORM; ... /** * File * * @ORM\Table() * @ORM\Entity(repositoryClass="my\TestBundle\Entity\FileRepository") * @ORM\HasLifecycleCallbacks() * @Gedmo\Uploadable(pathMethod="getPath", callback="myCallbackMethod", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true) */ class File { ... /** * @var string * * @ORM\Column(name="name", type="string", length=255) * @Gedmo\UploadableFileName */ private $name; ... 

my clubType form type

 $builder->add('logo', new FileType()) 

Filetype

 $builder->add('name', 'file', array( 'required' => false, )) 

my controller

 $form = $this->createForm('my_testbundle_club', $club); $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->submit($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($club); $em->flush(); } } 

but when I submit my form without uploading anything (uploading is optional), I have an error saying that the column name in the File table cannot be null

but I want the download to be optional, but if there is a download, the name is required

How can i achieve this?

Thanks in advance.

+5
source share
1 answer

In your controller, before flushing, you must add:

 if ($club->getLogo()->getPath() instanceof \Symfony\Component\HttpFoundation\File\UploadedFile) { $uploadManager = $this->get('stof_doctrine_extensions.uploadable.manager'); $uploadManager->markEntityToUpload($club->getLogo(), $club->getLogo()->getPath()); } 

When a new file is uploaded, getPath returns an instance of the downloaded file; if not, this is a string for an already saved file or null

see https://github.com/stof/StofDoctrineExtensionsBundle/blob/master/Resources/doc/index.rst#using-uploadable-extension

+1
source

Source: https://habr.com/ru/post/1211634/


All Articles