如果其他用户更改了此表单使用的同一实体对象,我想阻止提交。
如果我检查实体变量"已更改"之前
if ($form->isSubmitted() && $form->isValid()) {}
在Controller中,变量始终是最新的时间戳。意味着其他人已经改变了这个实体。所以我无法比较变化。
感谢您的帮助
控制器:
public function editAction(Request $request, Product $product)
{
$x = $product->getChanged();
dump($x); // I will get the latest timestamp
$form = $this->createForm(ProductType::class, $product);
$form->add('submit', 'submit', array('label' => 'Save'));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
dump($data);
// exit;
$data->setChanged(); // Set to test if life circle method preUpdate/prePersist is removed
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return $this->redirect(...);
}
return $this->render('AppBundle:Product:test.html.twig', array( // twig just contain {{ form(form) }}
'form' => $form->createView(),
));
}
实体:
/**
* ...
* @ORM\HasLifecycleCallbacks()
* ...
*/
class Product
{
/**
* @var \DateTime
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
protected $changed;
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updateTimestamp()
{
$this->setChanged();
}
/**
* Set changed
*
* @return Product
*/
public function setChanged()
{
$this->changed = new \DateTime();
return $this;
}
}