我有文件上传的实体好,我有这样的问题 - 如果我只更新图像,而不更改任何字段,图像将不会更新。但是,如果我再更改一个字段,例如价格和更改图像,则会上传新图像。
editAction:
public function editAction(Request $request, Good $good)
{
$deleteForm = $this->createDeleteForm($good);
$editForm = $this->createForm('Shop\ShopBundle\Form\GoodType', $good);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
//return $this->redirectToRoute('app_good_edit', array('id' => $good->getId()));
}
return $this->render('ShopShopBundle:good:edit.html.twig', array(
'good' => $good,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
好实体:
/**
* @var string
*/
private $logo;
/**
* @var File
*/
public $file;
protected function getUploadDir()
{
//return 'uploads/images/'.$this->getId();
return 'uploads/images/';
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return null === $this->logo ? null : $this->getUploadDir().'/'.$this->logo;
}
public function getAbsolutePath()
{
return null === $this->logo ? null : $this->getUploadRootDir().'/'.$this->logo;
}
/**
* @ORM\PrePersist
*/
public function preUpload()
{
if (null !== $this->file) {
$this->logo = uniqid().'.'.$this->file->guessExtension();
}
}
/**
* @ORM\PostPersist
*/
public function upload()
{
if (null === $this->file) {
return;
}
$this->file->move($this->getUploadRootDir(), $this->logo);
unset($this->file);
}
/**
* @ORM\PostRemove
*/
public function removeUpload()
{
if ($this->logo) {
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
Good.orm.yml
lifecycleCallbacks:
prePersist: [ preUpload, setCreatedAtValue]
preUpdate: [ preUpload, setUpdatedAtValue ]
postPersist: [ upload ]
postUpdate: [ upload ]
postRemove: [ removeUpload ]
我认为表单看不到我的图片更新,但我不知道为什么。也许是因为我的表中没有字段文件un db并且仅将其用作虚拟文件。 Symfony 2.8
答案 0 :(得分:1)
问题在于,在您描述的案例中,学说不会执行任何更新,也不会执行任何生命周期事件。
$file
不是一个doctrine托管属性,因此对于doctrine来说,设置它的对象和没有它的实体是相同的(考虑到这是唯一的区别)意味着不需要更新。
寻求解决方案: 您可以在ControllerAction中执行上传的文件(检查,移动它,设置徽标属性),而不是生命周期事件,或者如果您有像#34; updatedAt"并在设置文件属性时设置新的时间戳,从而导致对象被标记为已更改。