簡體   English   中英

Symfony自定義Constrait驗證實體

[英]Symfony custom Constrait Validate for entity

我使用symfony 2.8,但我有一些實體,我需要通過某種條件來驗證該實體,然后創建constrait ContainsInvValidator並在操作中調用validate服務並驗證實體,但是在調試時我沒有輸入ContainsInvValidator如何正確使用自定義驗證?

這是我的ContainsInvValidator

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContainsInvValidator extends ConstraintValidator
{
public function validate($entity, Constraint $constraint)
{
    if (!$entity->getInvoiceNumber()) {
        $this->context->buildViolation($constraint->message)
            ->atPath('foo')
            ->addViolation();
    }

    if (!$entity->getReference()) {
        $this->context->buildViolation($constraint->message)
            ->atPath('foo')
            ->addViolation();
    }

    if (!$entity->getInvoiceDate()) {
        $this->context->buildViolation($constraint->message)
            ->atPath('foo')
            ->addViolation();
    }
}
}

ContainsInv

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class ContainsInv extends Constraint
{
    public $message = 'The string "{{ string }}" no valid.';
}

添加配置:

services:
app.contains_test_check_validator:
    class: AppBundle\Validator\Constraints\ContainsInv
    tags:
        - { name: validator.constraint_validator }

和我為其創建自定義驗證器的實體類

/**
 * InboundInvoice
 * @ContainsInv(groups={"test_check"})
  */
class InboundInvoice
{

然后在我的行動中

    public function handleInvoiceStatusAction(Request $request, InboundInvoice $invoice)
{
    $resultHandling = $invoice->changedStatus();
    $errors = $this->get('validator')->validate($invoice, [], ['test_check']);

在變量errors我有

‌Symfony\Component\Validator\ConstraintViolationList::__set_state(array(
   'violations' => 
  array (
  ),

))

您的方法對類的屬性有效。 但是,如果要驗證整個類(而不是單個屬性),則必須覆蓋ContainsInv Constraint類中的getTargets方法。

public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

另請參見類約束驗證器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM