我创建了一个实体文档,其中包含包括文件属性在内的属性列表,同时添加文档进展顺利,当我更新时,我收到验证错误:
找不到该文件。
文件属性在添加时必须是必需的,但在编辑时是可选的,因为我可以只保留旧文件。
这是我的实体文档的一部分:
/**
* @ORM\Entity
* @ORM\Table(name="document")
*/
class Document
{
...
/**
* @var string
* @Assert\NotBlank()
* @Assert\File(maxSize = "5M", mimeTypes = {"application/pdf"})
* @ORM\Column(name="file", type="string", length=255, nullable=true)
*/
private $file;
/**
* @var string
* @ORM\Column(name="name", type="string", length=50)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Dtype", inversedBy="documents")
*/
private $dtype;
...
public function uploadFile($path, $type='', $oldFile=null)
{
$file = $this->getFile();
if ($file instanceof UploadedFile) {
if(!empty($type)){
$path = $path. '/' . $type;
}
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($path, $fileName);
$this->setFile($type. '/' .$fileName);
if($oldFile !== null){
$oldFilePath = $path .'/'. $oldFile;
if(file_exists($oldFilePath))
unlink($oldFilePath);
}
}else{
$this->setFile($oldFile);
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中我有:
public function editAction(Request $request, Document $document) {
$oldFile = $document->getFile();
$form = $this->createForm('AppBundle\Form\DocumentType', $document);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$document->uploadFile($this->getParameter('documents_file_dir'), $document->getDtype()->getChemin(), $oldFile);
$em = $this->getDoctrine()->getManager();
$em->persist($document);
$em->flush();
}
...
}
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
编辑
我想知道更新文档时的行为:
如果用户更新了文件,则必须使用@Assert\File 验证文件属性,
否则文件属性将不会被验证,因此我可以在创建文档时保留上传的原始文件。
使用验证组。将字段标记为仅用于创建新文档的必需文件:
/**
* ...
* @Assert\File(maxSize = "5M", mimeTypes = {"application/pdf"}, groups = {"create"})
* ...
*/
private $file;
Run Code Online (Sandbox Code Playgroud)
并为创建和编辑操作指定相关组:
public function editAction(Request $request) {
// ...
$form = $this->createForm('AppBundle\Form\DocumentType', $document, ["create"]);
// ...
public function editAction(Request $request, Document $document) {
// ...
$form = $this->createForm('AppBundle\Form\DocumentType', $document, ["edit"]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2998 次 |
| 最近记录: |