@@ -174,11 +174,12 @@ Options
174
174
``expression ``
175
175
~~~~~~~~~~~~~~
176
176
177
- **type **: ``string ``
177
+ **type **: ``string|Closure ``
178
178
179
- The condition written with the expression language syntax that will be evaluated.
180
- If the expression evaluates to a falsey value (i.e. using ``== ``, not ``=== ``),
181
- validation of constraints won't be triggered.
179
+ The condition as a closure or written with the expression language syntax
180
+ that will be evaluated. If the closure return value or the evaluated expression
181
+ is a falsey value (i.e. using ``== ``, not ``=== ``), validation of constraints won't
182
+ be triggered, and constraints of the ``otherwise `` option will, if provided.
182
183
183
184
To learn more about the expression language syntax, see
184
185
:doc: `/reference/formats/expression_language `.
@@ -200,6 +201,13 @@ in your expression:
200
201
201
202
The ``context `` variable in expressions was introduced in Symfony 7.2.
202
203
204
+ When using a closure, the first argument is the object being validated.
205
+
206
+ .. versionadded :: 7.3
207
+
208
+ The support for closure in the ``expression `` option was introduced in Symfony 7.3
209
+ and requires PHP 8.5.
210
+
203
211
The ``value `` variable can be used when you want to execute more complex
204
212
validation based on its value:
205
213
@@ -215,11 +223,20 @@ validation based on its value:
215
223
216
224
class Discount
217
225
{
226
+ // either using an expression...
218
227
#[Assert\When(
219
228
expression: 'value == "percent"',
220
229
constraints: [new Assert\Callback('doComplexValidation')],
221
230
)]
231
+ // ... or using a closure
232
+ #[Assert\When(
233
+ expression: static function (Discount $discount) {
234
+ return $discount->getType() === 'percent';
235
+ },
236
+ constraints: [new Assert\Callback('doComplexValidation')],
237
+ )]
222
238
private ?string $type;
239
+
223
240
// ...
224
241
225
242
public function doComplexValidation(ExecutionContextInterface $context, $payload): void
0 commit comments