【问题标题】:Cancel the saving or the update in prePersist在 prePersist 中取消保存或更新
【发布时间】:2017-02-16 15:51:29
【问题描述】:

如果在测试后仍然存在,我想取消操作。我不知道我是如何徒劳地尝试重定向目标的。

/**
 * @param mixed $object
 */
public function prePersist($object)
{
    if (is_null($object->getFile())) {
    }
}

有什么帮助吗?

【问题讨论】:

  • AFRAID 从那里不可能,你需要使用约束验证而不是symfony.com/doc/current/validation.html
  • 我认为你应该能够抛出异常,但没有什么比这更确定...
  • 感谢@Yonel!我通过添加:* @Assert\NotNull() 到属性 private $file 解决了这个问题;

标签: symfony sonata-admin


【解决方案1】:

对你来说可能有点晚了。因为我一直在寻找同样的东西,所以这是我的解决方案。

似乎无法在 Sonatas prePersist 方法中进行任何验证。

对于像您这样的简单 NotNull 验证,我会向实体添加一个简单的验证约束,或者如果该字段未映射到表单元素本身。

如果您想在 Sonatas 保存过程中进行一些额外的验证,请覆盖 validate 方法。这个是在prePersis/preUpdate 方法之前调用的,它允许您添加验证消息。

use Sonata\CoreBundle\Validator\ErrorElement;

public function validate(ErrorElement $errorElement, $object)
{
    $errorElement->with('file')->addViolation('Hey, this is a validation message');
}

【讨论】:

  • 我已禁用字段,这不适用于禁用字段。 :(
【解决方案2】:

我也迟到了,但如果你和我一样面临同样的问题。这是我在 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(和/或postPersist)中验证或做任何您想做的事情,并取消创建并抛出异常。

不幸的是,它仍然显示成功闪存包,但将任何内容保存在您的数据库中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2011-12-08
    • 2010-11-19
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多