Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Symfony2 upload file with stof uploadable extension

i'm trying to set up a form with file upload under Symfony2 with the uploadable extension (stof/doctrine)

here are my entities


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


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 form type clubType

$builder->add('logo', new 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') {

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

but when i submit my form without uploading anything (upload is not mandatory), i've an error saying that column name in table File cannot be null

but i want that the upload is optional, but if there is an upload, name is mandatory

How can i achieve that?

Thanks in advance.

like image 247
Chuck Norris Avatar asked Nov 09 '22 20:11

Chuck Norris

1 Answers

In your controller, before flushing, you have to 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 uploading a new file, getPath return an instance of uploaded file, if not, it's a string for already saved file or null

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

like image 145
wasbaiti Avatar answered Nov 15 '22 06:11