5

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.

1
  • 1
    I dont know about that extension, but have you tried adding nullable=true ? Another option is to add a default value when it is empty, which is probably useful anyway (like a dummy 'logo' image). Commented Jan 21, 2015 at 16:01

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.