2016-09-22 62 views
0

我得到了一個帶有字段文件的編輯表單(項目)來上傳圖片。 在我的數據庫中,我有一列'img'來保存我的上傳圖片。編輯表單提交時丟失的舊值文件symfony2

但我想要的用戶,如果他不上傳新圖片,他得到了老img。

我得到的是舊IMG與倉庫:

public function editAction(Request $request, Projet $projet) 
{ 

    $editForm = $this->createForm('BBW\ProjetsBundle\Form\ProjetType', $projet); 
    $editForm->handleRequest($request); 
    $em = $this->getDoctrine()->getManager(); 

    $repository = $em->getRepository('BBWProjetsBundle:Projet'); 
    $old = $repository->findOneById($projet->getId()); // Données BDD Actuel 

    $old_img = $old->getImg(); 
    var_dump($old_img); // Got the old name for img in database - Ex: img.png 


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

     var_dump($old_img); // Got null img .. 

     $file = $projet->getImg(); // New File upload - Here got null img (when i upload no file) 
     if($file != null){ // If i send an image - So the field img is not empty and got the new picture 
      // Want delete the old img - But not as i get the name of the old img, it doesn't remove 
      $fs = new Filesystem(); 
      $fs->remove($this->getParameter('uploads_dir_projets') . '/' . $old_img); // old_img = null :(
      $fileName = md5(uniqid()).'.'.$file->guessExtension(); 
      $file->move(// Move new file, etc .. 
       $this->getParameter('uploads_dir_projets'), 
       $fileName 
      ); 
      $projet->setImg($fileName); 
     }else{ 
      // In case i leave the field empty img - Here no new file is upload so file = null 
      // But When i submit the edit form, 
      // it replace the old value in database with null. I don't want it replace the old value if no new picture is upload 
      $projet->setImg($old_img); // Normally set the same name img 
     } 

     //$em->persist($projet); 
     //$em->flush(); 

     //$request->getSession()->getFlashBag()->add('success', 'Projet modifié avec succès'); 

     //return $this->redirectToRoute('bbw_projet_home'); 
    } 

    return $this->render('BBWProjetsBundle:projet:edit.html.twig', array(
     'projet' => $projet, 
     'edit_form' => $editForm->createView(), 
    )); 
} 

我不明白怎麼做:/ 非常感謝幫助。

回答

0

檢查一塊下面的代碼:如果沒有要上傳的圖片,舊值保持不變:

$projet = $editForm->getData(); 

if (isset($projet['file']) && $projet['file'] instanceof UploadedFile) { 

    if ($projet['file']->getError() == 0) { 
     $fileName = md5(uniqid()).'.'.$file->guessExtension(); 
     // Move file... 

     $projet->setImg($fileName); 
    } else { 
     // Report/track error 
    } 

    $em->persist($projet); 
    $em->flush(); 
} 
+0

您好,感謝您的幫助。我嘗試,但我得到數據庫中的列img不能爲空。也許我需要改變我的列參數? – OcB974

+0

顯然。如果圖片上傳是可選的,則該字段應該接受空值。 –