i'm trying to set up a form with file upload under Symfony2 with the uploadable 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 form type clubType
$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 (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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With