具有stof可上传扩展名的Symfony2上传文件

Chu*_*ris 5 php file-upload symfony stofdoctrineextensions

我正在尝试使用可上传的扩展名(stof/doctrine)在Symfony2下设置一个带文件上传的表单

这是我的实体

俱乐部

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

文件

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

...
Run Code Online (Sandbox Code Playgroud)

我的表格类型clubType

$builder->add('logo', new FileType())
Run Code Online (Sandbox Code Playgroud)

文件类型

$builder->add('name', 'file', array(
            'required' => false,
        ))
Run Code Online (Sandbox Code Playgroud)

我的控制器

$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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是当我提交我的表单而没有上传任何内容(上传不是强制性的)时,我有一个错误,表示表文件中的列名不能为null

但我希望上传是可选的,但如果有上传,名称是必填项

我怎样才能实现这一目标?

提前致谢.

小智 1

在您的控制器中,在刷新之前,您必须添加:

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());
}
Run Code Online (Sandbox Code Playgroud)

上传新文件时,getPath 返回已上传文件的实例,如果没有,则返回已保存文件的字符串或 null

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