Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • 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
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Reference
  4. Constraints
  5. When
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Basic Usage
  • Options
    • expression
    • constraints
    • groups
    • payload
    • values

When

Edit this page

When

6.2

The When constraint was introduced in Symfony 6.2.

This constraint allows you to apply constraints validation only if the provided expression returns true. See Basic Usage for an example.

Applies to class or property/method
Options
  • expression
  • constraints
  • groups
  • payload
  • values
Class When
Validator WhenValidator

Basic Usage

Imagine you have a class Discount with type and value properties:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Model/Discount.php
namespace App\Model;

class Discount
{
    private ?string $type;

    private ?int $value;

    // ...

    public function getType(): ?string
    {
        return $this->type;
    }

    public function getValue(): ?int
    {
        return $this->value;
    }
}

To validate the object, you have some requirements:

A) If type is percent, then value must be less than or equal 100; B) If type is absolute, then value can be anything; C) No matter the value of type, the value must be greater than 0.

One way to accomplish this is with the When constraint:

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

use Symfony\Component\Validator\Constraints as Assert;

class Discount
{
    #[Assert\GreaterThan(0)]
    #[Assert\When(
        expression: 'this.getType() == "percent"',
        constraints: [
            new Assert\LessThanOrEqual(100, message: 'The value should be between 1 and 100!')
        ],
    )]
    private ?int $value;

    // ...
}
1
2
3
4
5
6
7
8
9
10
11
# config/validator/validation.yaml
App\Model\Discount:
    properties:
        value:
            - GreaterThan: 0
            - When:
                expression: "this.getType() == 'percent'"
                constraints:
                    - LessThanOrEqual:
                        value: 100
                        message: "The value should be between 1 and 100!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 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\Model\Discount">
        <property name="value">
            <constraint name="GreaterThan">0</constraint>
            <constraint name="When">
                <option name="expression">
                    this.getType() == 'percent'
                </option>
                <option name="constraints">
                    <constraint name="LessThanOrEqual">
                        <option name="value">100</option>
                        <option name="message">The value should be between 1 and 100!</option>
                    </constraint>
                </option>
            </constraint>
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Model/Discount.php
namespace App\Model;

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

class Discount
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('value', new Assert\GreaterThan(0));
        $metadata->addPropertyConstraint('value', new Assert\When([
            'expression' => 'this.getType() == "percent"',
            'constraints' => [
                new Assert\LessThanOrEqual([
                    'value' => 100,
                    'message' => 'The value should be between 1 and 100!',
                ]),
            ],
        ]));
    }

    // ...
}

The expression option is the expression that must return true in order to trigger the validation of the attached constraints. To learn more about the expression language syntax, see The Expression Syntax.

For more information about the expression and what variables are available to you, see the expression option details below.

Options

expression

type: string

The condition written with the expression language syntax that will be evaluated. If the expression evaluates to a falsey value (i.e. using ==, not ===), validation of constraints won't be triggered.

To learn more about the expression language syntax, see The Expression Syntax.

Depending on how you use the constraint, you have access to 1 or 2 variables in your expression:

this
The object being validated (e.g. an instance of Discount).
value
The value of the property being validated (only available when the constraint is applied to a property).

The value variable can be used when you want to execute more complex validation based on its value:

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

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

class Discount
{
    #[Assert\When(
        expression: 'value == "percent"',
        constraints: [new Assert\Callback('doComplexValidation')],
    )]
    private ?string $type;
    // ...

    public function doComplexValidation(ExecutionContextInterface $context, $payload)
    {
        // ...
    }
}
1
2
3
4
5
6
7
8
# config/validator/validation.yaml
App\Model\Discount:
    properties:
        type:
            - When:
                expression: "value == 'percent'"
                constraints:
                    - Callback: doComplexValidation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- 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\Model\Discount">
        <property name="type">
            <constraint name="When">
                <option name="expression">
                    value == 'percent'
                </option>
                <option name="constraints">
                    <constraint name="Callback">
                        <option name="callback">doComplexValidation</option>
                    </constraint>
                </option>
            </constraint>
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/Model/Discount.php
namespace App\Model;

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

class Discount
{
    // ...

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('type', new Assert\When([
            'expression' => 'value == "percent"',
            'constraints' => [
                new Assert\Callback('doComplexValidation'),
            ],
        ]));
    }

    public function doComplexValidation(ExecutionContextInterface $context, $payload)
    {
        // ...
    }
}

You can also pass custom variables using the values option.

constraints

type: array

The constraints that are applied if the expression returns true.

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.

values

type: array default: []

The values of the custom variables used in the expression. Values can be of any type (numeric, boolean, strings, null, etc.)

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

    Symfony 6.2 is backed by

    Symfony 6.2 is backed by

    Online exam, become Symfony certified today

    Online exam, become Symfony certified today

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Peter Gribanov, a Symfony contributor

    Thanks Peter Gribanov for being a Symfony contributor

    1 commit • 2 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?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • 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

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

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

      Deployed on

    Follow Symfony

    Search by Algolia