我在编辑表单上使用sonata admin bundle有一个奇怪的行为。我有一个名为工作表的字段,它接受PDF上传。文件上传正常,但只要对字段进行更新,该字段就会变空。我该如何防止这种行为?
我创建了下面的监听器,根据最新的symfony cookbook上传文件:http://symfony.com/doc/current/controller/upload_file.html
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\UNOE;
use AppBundle\Entity\COE;
use AppBundle\FileUploader;
class SheetUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for InspectionSheet entities
if($entity instanceof UNOE) {
$file = $entity->getWorksheet();
// only upload new files
if (!$file instanceof UploadedFile) {
return;
}
$fileName = $this->uploader->upload($file);
$entity->setWorksheet($fileName);
}
else {
return;
}
}
// public function postLoad(LifecycleEventArgs $args)
// {
// $entity = $args->getEntity();
//
// $fileName = $entity->getSheet();
//
// $entity->setSheet(new File($this->targetPath.'/'.$fileName));
// }
}
该字段包含在奏鸣曲管理员Admin中,如下所示:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('worksheet',FileType::class, array('label' => 'Inspection Worksheet', 'data_class' => null, 'required' => false))
}