2017-09-13 57 views
1

我正在阅读一段时间这个,但没有找到适合我的东西。 这是实体Symfony文件字段空编辑

/** 
* @ORM\Column(type="string") 
* 
* @Assert\NotBlank(message="Molimo unesite PDF ili Word fajl.") 
* @Assert\File(mimeTypes={ "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}) 
*/ 
private $body; 

这是形式

// Problem with empty field on edit persist! Form expect FileType but db sends string!!! 
      ->add('body', FileType::class, [ 
       //'data_class' => null,// <-- If I change it nothing happened. 
       'label' => 'Word ili pdf dokument', 
       'invalid_message' =>'Id posta nije validan', 
       'attr' => [ 
        'class' => 'form-group', 
     ]]) 

一切都非常简单并提出以下文档。我有实体,其中包含几个属性之一的文件($ body)。文件被设置为保存在web/uploads/post /中。当我去编辑页面时,我得到这个错误:

“窗体的视图数据预计是类Symfony \ Component \ HttpFoundation \ File \ File的一个实例,但是是一个(n)字符串。这通过将“data_class”选项设置为null或通过添加将字符串转换为Symfony \ Component \ HttpFoundation \ File \ File实例的视图转换器来实现。

如果我设置data_status =>空字段为空。

我需要的是一些链接到这个工作的例子,数据转换器可能?

+0

其实任何建议都是值得欢迎的! –

+0

您能否给我们提供一些关于您面临的问题的更多信息? – Toastrackenigma

+0

我做了一些修改。如果有任何需要的信息,我准备写。 –

回答

0

你可以通过在editAction中创建一个新的File()来解决这个问题。像这样:

/** 
* @Route("/edit/{yourEntity}", name="entity_edit") 
* 
* @return Response 
*/ 
public function editAction(Request $request, YourEntity yourEntity) 
{ 
    $body = new File($this->getParameter('your_files_directory') . '/' . $yourEntity->getBody()); 
    $yourEntity->setBody($body); 
    // rest of your editAction 
} 
+0

谢谢!在我实现你的代码之后。我仍然有空的文件空间,但在我从表单中删除该字段后,编辑时没有任何限制。不好,我知道,但我确实需要更改文件的名称。再次感谢! –

0

好的,解决了。 @ASOlivieri的答案很好,只需稍作修改即可。在他的答案中的代码将记住带有文件名的路径。所以如果你想再次编辑它会抛出没有发现的exeption。您必须再次 - > setBody,才能与原始文件名相同。在冲水前设置()

public function editAction(Request $request, Post $post) { 
    $fileName = $post->getBody(); 
    $file = new File($this->getParameter('post_directory') . '/' . $post->getBody()); 
    $post->setBody($file); 

    $deleteForm = $this->createDeleteForm($post); 
    $editForm = $this->createForm('AppBundle\Form\PostEditType', $post); 
    $editForm->handleRequest($request); 


    if ($editForm->isSubmitted() && $editForm->isValid()) { 

     $post->setBody($fileName); 
     $this->getDoctrine()->getManager()->flush(); 

希望这有助于!

+0

很高兴你知道了! – ASOlivieri