diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst index d491adea2db..b6723ffc371 100644 --- a/reference/constraints/Expression.rst +++ b/reference/constraints/Expression.rst @@ -74,7 +74,7 @@ One way to accomplish this is with the Expression constraint: // src/Acme/DemoBundle/Model/BlogPost.php namespace Acme\DemoBundle\Model\BlogPost; - + use Symfony\Component\Validator\Constraints as Assert; /** @@ -91,23 +91,27 @@ One way to accomplish this is with the Expression constraint: .. code-block:: xml - - - - - - - + + + + + + + + + .. code-block:: php // src/Acme/DemoBundle/Model/BlogPost.php - namespace Acme\DemoBundle\Model\BlogPost; - + namespace Acme\DemoBundle\Model; + use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert; @@ -129,6 +133,90 @@ expression that must return true in order for validation to pass. To learn more about the expression language syntax, see :doc:`/components/expression_language/syntax`. +.. sidebar:: Mapping the Error to a Specific Field + + You can also attach the constraint to a specific property and still validate + based on the values of the entire entity. This is handy if you want to attach + the error to a specific field. In this context, ``value`` represents the value + of ``isTechnicalPost``. + + .. configuration-block:: + + .. code-block:: yaml + + # src/Acme/DemoBundle/Resources/config/validation.yml + Acme\DemoBundle\Model\BlogPost: + properties: + isTechnicalPost: + - Expression: + expression: "this.getCategory() in ['php', 'symfony'] or value == false" + message: "If this is a tech post, the category should be either php or symfony!" + + .. code-block:: php-annotations + + // src/Acme/DemoBundle/Model/BlogPost.php + namespace Acme\DemoBundle\Model; + + use Symfony\Component\Validator\Constraints as Assert; + + class BlogPost + { + // ... + + /** + * @Assert\Expression( + * "this.getCategory() in ['php', 'symfony'] or value == false", + * message="If this is a tech post, the category should be either php or symfony!" + * ) + */ + private $isTechnicalPost; + + // ... + } + + .. code-block:: xml + + + + + + + + + + + + + + + + .. code-block:: php + + // src/Acme/DemoBundle/Model/BlogPost.php + namespace Acme\DemoBundle\Model; + + use Symfony\Component\Validator\Constraints as Assert; + use Symfony\Component\Validator\Mapping\ClassMetadata; + + class BlogPost + { + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression(array( + 'expression' => 'this.getCategory() in ["php", "symfony"] or value == false', + 'message' => 'If this is a tech post, the category should be either php or symfony!', + ))); + } + + // ... + } + For more information about the expression and what variables are available to you, see the :ref:`expression ` option details below.