php - Lost old value file when edit form submit symfony2 -
i got edit form (project) field file upload picture. in database got column 'img' save upload picture.
but want user, if don't upload new picture, got old img.
i old img repository:
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 old name 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 upload no file ) if( $file != null ){ // if send image - field img not empty , got new picture // want delete old img - not name of old img, 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 leave field empty img - here no new file upload file = null // when submit edit form, // replace old value in database null. don't want replace old value if no new picture upload $projet->setimg( $old_img ); // set 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(), )); }
i don't understand how :/ lot help.
check piece of code below: if there no picture uploaded, old value remains unchanged:
$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(); }
Comments
Post a Comment