Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Reference
  4. Constraints
  5. Callback

Callback

Edit this page

The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you're using validation with forms, this means that instead of displaying custom errors at the top of the form, you can display them next to the field they apply to.

This process works by specifying one or more callback methods, each of which will be called during the validation process. Each of those methods can do anything, including creating and assigning validation errors.

Note

A callback method itself doesn't fail or return any value. Instead, as you'll see in the example, a callback method has the ability to directly add validator "violations".

Applies to class or property/method
Class Callback
Validator CallbackValidator

Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Author
{
    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context, mixed $payload): void
    {
        // ...
    }
}
1
2
3
4
# config/validator/validation.yaml
App\Entity\Author:
    constraints:
        - Callback: validate
1
2
3
4
5
6
7
8
9
10
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="App\Entity\Author">
        <constraint name="Callback">validate</constraint>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $metadata->addConstraint(new Assert\Callback('validate'));
    }

    public function validate(ExecutionContextInterface $context, mixed $payload): void
    {
        // ...
    }
}

The Callback Method

The callback method is passed a special ExecutionContextInterface object. You can set "violations" directly on this object and determine to which field those errors should be attributed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// ...
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Author
{
    // ...
    private string $firstName;

    public function validate(ExecutionContextInterface $context, mixed $payload): void
    {
        // somehow you have an array of "fake names"
        $fakeNames = [/* ... */];

        // check if the name is actually a fake name
        if (in_array($this->getFirstName(), $fakeNames)) {
            $context->buildViolation('This name sounds totally fake!')
                ->atPath('firstName')
                ->addViolation();
        }
    }
}

Static Callbacks

You can also use the constraint with static methods. Since static methods don't have access to the object instance, they receive the object as the first argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static function validate(mixed $value, ExecutionContextInterface $context, mixed $payload): void
{
    // somehow you have an array of "fake names"
    $fakeNames = [/* ... */];

    // check if the name is actually a fake name
    if (in_array($value->getFirstName(), $fakeNames)) {
        $context->buildViolation('This name sounds totally fake!')
            ->atPath('firstName')
            ->addViolation()
        ;
    }
}

External Callbacks and Closures

If you want to execute a static callback method that is not located in the class of the validated object, you can configure the constraint to invoke an array callable as supported by PHP's call_user_func function. Suppose your validation function is Acme\Validator::validate():

1
2
3
4
5
6
7
8
9
10
11
namespace Acme;

use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Validator
{
    public static function validate(mixed $value, ExecutionContextInterface $context, mixed $payload): void
    {
        // ...
    }
}

You can then use the following configuration to invoke this validator:

1
2
3
4
5
6
7
8
9
10
// src/Entity/Author.php
namespace App\Entity;

use Acme\Validator;
use Symfony\Component\Validator\Constraints as Assert;

#[Assert\Callback([Validator::class, 'validate'])]
class Author
{
}
1
2
3
4
# config/validator/validation.yaml
App\Entity\Author:
    constraints:
        - Callback: [Acme\Validator, validate]
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="App\Entity\Author">
        <constraint name="Callback">
            <value>Acme\Validator</value>
            <value>validate</value>
        </constraint>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Entity/Author.php
namespace App\Entity;

use Acme\Validator;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $metadata->addConstraint(new Assert\Callback([
            Validator::class,
            'validate',
        ]));
    }
}

Note

The Callback constraint does not support global callback functions nor is it possible to specify a global function or a service method as a callback. To validate using a service, you should create a custom validation constraint and add that new constraint to your class.

When configuring the constraint via PHP, you can also pass a closure to the constructor of the Callback constraint:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $callback = function (mixed $value, ExecutionContextInterface $context, mixed $payload): void {
            // ...
        };

        $metadata->addConstraint(new Assert\Callback($callback));
    }
}

Caution

Using a Closure together with attribute configuration will disable the attribute cache for that class/property/method because Closure cannot be cached. For best performance, it's recommended to use a static callback method.

Options

callback

type: string, array or Closure [default option]

The callback option accepts three different formats for specifying the callback method:

  • A string containing the name of a concrete or static method;
  • An array callable with the format ['<Class>', '<method>'];
  • A closure.

Concrete callbacks receive an ExecutionContextInterface instance as the first argument and the payload option as the second argument.

Static or closure callbacks receive the validated object as the first argument, the ExecutionContextInterface instance as the second argument and the payload option as the third argument.

groups

type: array | string default: null

It defines the validation group or groups of this constraint. Read more about validation groups.

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version

    Symfony 7.1 is backed by

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Save your teams and projects before they sink

    Save your teams and projects before they sink

    Version:

    Table of Contents

    • Configuration
    • The Callback Method
    • Static Callbacks
    • External Callbacks and Closures
    • Options
      • callback
      • groups
      • payload

    Symfony footer

    Avatar of Olivier Toussaint, a Symfony contributor

    Thanks Olivier Toussaint (@cinquante) for being a Symfony contributor

    2 commits • 34 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony