在 prePersist 中取消保存或更新
Cancel the saving or the update in prePersist
我想取消这个操作,如果在之后还坚持test.and我不知道我是怎么尝试重定向目标的,但是没有成功。
/**
* @param mixed $object
*/
public function prePersist($object)
{
if (is_null($object->getFile())) {
}
}
有什么帮助吗?
这对你来说可能有点晚了。由于我一直在寻找同样的东西,所以这是我的解决方案。
似乎无法在 Sonatas prePersist 方法中进行任何验证。
对于像您这样的简单 NotNull 验证,我会向实体添加一个简单的验证约束,或者如果字段未映射到表单元素本身。
如果您想在奏鸣曲保存过程中进行一些额外的验证,请覆盖 validate
方法。此方法在 prePersis
/preUpdate
方法之前调用,它允许您添加验证消息。
use Sonata\CoreBundle\Validator\ErrorElement;
public function validate(ErrorElement $errorElement, $object)
{
$errorElement->with('file')->addViolation('Hey, this is a validation message');
}
我也来晚了,但如果你和我一样面临同样的问题。这是我对 Doctrine
的处理
use ACME\Exceptions\CustomException;
public function prePersist($object)
{
// Do some stuff with your entity $object
if (//Something) {
$this->getRequest()->getSession()->getFlashBag()->add(
'error',
'Something wrong happens');
throw new CustomException('Something wrong happens');
}
}
/** Overwrite create methode to catch custom error */
public function create($object)
{
try {
$this->em->beginTransaction();
$res = parent::create($object);
$this->em->getConnection()->commit();
return $res;
} catch (CustomException $e) {
$this->em->getConnection()->rollBack();
return null;
}
}
通过这种方式,您可以在 prePersist
(and/or postPersist
) 中验证或执行任何您想要的操作,并取消创建并抛出异常。
不幸的是,它仍然显示成功闪存包,但在您的数据库中保留任何内容。
我想取消这个操作,如果在之后还坚持test.and我不知道我是怎么尝试重定向目标的,但是没有成功。
/**
* @param mixed $object
*/
public function prePersist($object)
{
if (is_null($object->getFile())) {
}
}
有什么帮助吗?
这对你来说可能有点晚了。由于我一直在寻找同样的东西,所以这是我的解决方案。
似乎无法在 Sonatas prePersist 方法中进行任何验证。
对于像您这样的简单 NotNull 验证,我会向实体添加一个简单的验证约束,或者如果字段未映射到表单元素本身。
如果您想在奏鸣曲保存过程中进行一些额外的验证,请覆盖 validate
方法。此方法在 prePersis
/preUpdate
方法之前调用,它允许您添加验证消息。
use Sonata\CoreBundle\Validator\ErrorElement;
public function validate(ErrorElement $errorElement, $object)
{
$errorElement->with('file')->addViolation('Hey, this is a validation message');
}
我也来晚了,但如果你和我一样面临同样的问题。这是我对 Doctrine
的处理 use ACME\Exceptions\CustomException;
public function prePersist($object)
{
// Do some stuff with your entity $object
if (//Something) {
$this->getRequest()->getSession()->getFlashBag()->add(
'error',
'Something wrong happens');
throw new CustomException('Something wrong happens');
}
}
/** Overwrite create methode to catch custom error */
public function create($object)
{
try {
$this->em->beginTransaction();
$res = parent::create($object);
$this->em->getConnection()->commit();
return $res;
} catch (CustomException $e) {
$this->em->getConnection()->rollBack();
return null;
}
}
通过这种方式,您可以在 prePersist
(and/or postPersist
) 中验证或执行任何您想要的操作,并取消创建并抛出异常。
不幸的是,它仍然显示成功闪存包,但在您的数据库中保留任何内容。