2015-01-21 7 views
5

Ich versuche, eine Form mit Datei-Upload unter Symfony2 mit der hochladbare Verlängerung (stof/Lehre)Symfony2-Upload-Datei mit stof hochladbare Erweiterung

hier sind meine Einheiten

Club

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

Datei

<?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; 

... 

meine Form Typ clubType

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

filetype

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

mein 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(); 
     } 
    } 

aber wenn ich meine Form einreichen, ohne etwas Hochladen (Upload nicht zwingend notwendig ist), habe ich eine Fehlermeldung, dass die Spaltennamen in Tabelle Datei kann nicht null sein

aber ich möchte, dass der Upload optional ist, aber wenn es einen Upload gibt, Name ist obligatorisch

Wie kann ich das erreichen?

Vielen Dank im Voraus.

+1

Ich weiß nicht über diese Erweiterung, aber haben Sie versucht, 'nullable = true' hinzuzufügen? Eine andere Möglichkeit besteht darin, einen Standardwert hinzuzufügen, wenn dieser leer ist, was wahrscheinlich sowieso nützlich ist (wie ein Dummy-Logo-Bild). – FeedTheWeb

Antwort

1

In Ihrem Controller, vor dem Spülen, müssen Sie hinzufügen:

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()); 
} 

Wenn Sie eine neue Datei hochladen, getPath eine Instanz hochgeladene Datei zurückkehren, wenn nicht, ist es für bereits gespeicherte Datei oder null

ein String ist

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