0

I use symfony 2.8 and I have some entity and I need validate this entity by some condition I create constrait ContainsInvValidator and call validate service in action and validate entity but when debugged I did not entered in ContainsInvValidator how to correct use custom validate ?

this is my 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();
    }
}
}

and ContainsInv:

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

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

add config:

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

and my entity class for which I create custom validator

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

and then in my action

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

and in variables errors I have

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

))

1 Answer 1

2

Your approach is valid for a property of a class. However if you want to validate the whole class (and not a single property), you have to overwrite the getTargets method in your ContainsInv Constraint class.

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

See also Class Constraint Validator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.