【问题标题】:Doctrine2 verify if attribute not persisted are modifiedDoctrine2 验证是否修改了未持久化的属性
【发布时间】:2015-03-18 21:07:05
【问题描述】:

我正在构建一个用于上传许多照片的包。

我使用表格来显示我的照片表格。

我的问题是,当我点击“修改器”时,如果我没有更改“Activé”或“Titre”,则什么也做不了。

public function ajaxEditPhotoAction(Request $request, $id) {
    $error = null;
    $em = $this->getDoctrine()->getManager();

    $repository = $em->getRepository("FDMFileUploaderBundle:Photo");
    $photo = $repository->find($id);
    $form = $this->get('form.factory')->create(new PhotoType(), $photo);

    if ($request->isMethod('POST')) {
        $form->bind($request);
        if ($form->isValid()) {
            $em->flush();
        }
        else {
            $error = "Mauvaise donnée";
        }
    }
    else {
        $error = "Wrong Method";
    }

    return $this->render('FDMFileUploaderBundle:Default:editPhoto.html.twig', array(
        "error" => $error
        )
    );
}

如果我在isValid() 之后有这行,那可以,但是当“Activé”或“Titre”更改时,我的照片会上传两次。

$photo->upload();

如果我的实体中持久存在的属性没有更改,我如何强制上传?

我查看了学说注释,但没有找到解决方案。

Ajax 提交

var data = new FormData(this);
$.ajax({
    type: "POST",
    url: url,
    data: data,
    contentType: false,
    cache: false,
    processData:false,
    success: function(data) {
        alert("Success");
    },
    error: function(xhr, textStatus, errorThrown) {
        alert("Error "+xhr+textStatus+errorThrown);
    }
});

【问题讨论】:

    标签: php ajax symfony doctrine-orm


    【解决方案1】:

    您可以检查您的$request 里面是否有文件。这样就可以了。

    if ($form->isValid() || $request->files->count() > 0) {
            $photo->upload();
            $em->flush();
        }
    

    由 Olive007 编辑:

    感谢您的帮助,我找到了解决方案:

    $nbFile = $request->files->count();
    
    if ($form->isValid()) {
        $uow = $em->getUnitOfWork();
        $uow->computeChangeSets();
        if ($nbFile == 1 && !$uow->isScheduledForUpdate($photo)) {
            // title and enabled aren't modified but file is
            $photo->upload();
        }
        else {
            $em->flush();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多