Doctrine2 验证未持久化的属性是否被修改

Doctrine2 verify if attribute not persisted are modified

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

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

我的问题是,当我点击 "Modifier" 时,没有任何反应 如果我没有更改 "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);
    }
});

您可以检查您的 $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();
    }
}