So the problem is like this:

I am trying to save some data from API and I need to validate them with Symfony validation ex:

private $id;

    /**
     * @var
     * @Assert\Length(max="255")
     * @CustomAssert\OrderExternalCode()
     * @CustomAssert\OrderShipNoExternalCode()
     */
    private $code;

    private $someId;

    /**
     * @var
     * @Assert\NotBlank()
     * @Assert\Length(max="255")
     */
    private $number;

this works well but now I need to add some Assert Constrains dynamically from the controller and that is where I am stuck!

Does anyone knows how to do that or any suggestion that might help?

Currently I did an extra constraint which does extra query in the DB and I don't want to do that and I am not using FormType.

3 Answers

0
Diar Selimi On Best Solutions

So I wanted to dynamically validate the request data based on a condition in the controller.

I specified an extra group for that in the entity like so:

    /**
      * @var
      * @Assert\NotBlank(groups={"extra_check"})
      * @Assert\Length(max="255")
      */
     private $externalId;

Then in the controller I just did the condition to validate with the extra group or not.

$groups = $order->getExternalCode() != null ? ['Default'] : ['Default', 'extra_check'];
$this->validateRequest($request, null, $groups);

The Default group is the one without group specified and the other one is the group I specified in the field

0
tchap On

Using the CallbackConstraint should help I think, in your case :

use My\Custom\MyConstraint;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

// This is not tested !
class MyEntity
{
    /**
     * @Assert\Callback()
     */
    public function validateSomeId(ExecutionContextInterface $context)
    {
        $constraint = new MyConstraint(['code' => $this->code]);
        $violations = $context->getValidator()->validate($this->number, $constraint);

        foreach ($violations as $violation) {
            $context->getViolations()->add($violation);
        }
    }
}

See https://symfony.com/doc/current/reference/constraints/Callback.html

EDIT : I don't know what you're trying to validate so I just put some random params of your entity in there

1
DonCallisto On

You can use groups and use (or leave out) the extra group you're talking about.