Search code examples
symfonyannotationsassertsymfony-3.2

Symfony - Use parameters in Entity assert annotations


I'm trying to set the same phone regex everywhere on my website, using a pattern defined in the app/config/parameters.yml

parameters:    
    phone_regex: /^[+][3][3]\d{9}$/

How can i retrieve this patern in my entities assert annotations ?

/**
 * @var string
 * @Assert\NotBlank(message = "notBlank")
 * @Assert\Regex(
 *     pattern="%phone_regex%",
 *     message="phone"
 * )
 * @ORM\Column(name="contact_phone", type="string", length=255)
 */
private $contactPhone;

The code above does not work, it generates html without the regex

<input type="text" id="client_contactPhone" name="client[contactPhone]" required="required" maxlength="255" pattern=".*phone_regex.*" class="form-control">

Solution

  • Joe has a good solution, but my question is - why have this as a parameter at all? Is this something you would ever plan on overriding in the future? I'm guessing not. Instead, you could simply make a class w/constant that holds the information you need:

    class Phone
    {
        const VALID_REGEX = '/^[+][3][3]\d{9}$/';
    }
    

    Then, for your annotations:

    /**
     * @var string
     * @Assert\NotBlank(message = "notBlank")
     * @Assert\Regex(
     *     pattern=Phone::VALID_REGEX,
     *     message="phone"
     * )
     * @ORM\Column(name="contact_phone", type="string", length=255)
     */
    private $contactPhone;
    

    This way you're still using the Regex validator and not reinventing the wheel with another custom validation type.

    The other main benefit is that you can use this everywhere in your code without actually having to inject the parameter to a service, or anything else. Plus it's easy to access class constants from Twig.