30

I have a class like this:

class Student {

const GENDER_MALE = "male", GENDER_FEMALE = "female";
/**
 * @var string $gender
 *
 * @ORM\Column(name="gender", type="string", length=50,nullable=false)
 * @Assert\NotBlank(message="Gender cannot be blank",groups={"new"})
 * @Assert\Choice(choices = {"male", "female"}, message = "Choose a valid gender.", groups={"new"})
 */
private $gender;

I have to hard code the values "male" and "female". Is it possible to do something like this ?

choices = {self::GENDER_MALE, self::GENDER_FEMALE}

2
  • 3
    Use callback option instead, and in method you can return array of your constants. Commented Jun 5, 2015 at 15:24
  • looks like a good alternative. thanks
    – sonam
    Commented Jun 5, 2015 at 15:33

1 Answer 1

41

This is a feature of Doctrine2 Annotation Reader (Constants).

You solution:

class Student
{
    const GENDER_MALE = "male", GENDER_FEMALE = "female";

    /**
     * @var string $gender
     *
     * @ORM\Column(name="gender", type="string", length=50,nullable=false)
     * @Assert\NotBlank(message="Gender cannot be blank",groups={"new"})
     * @Assert\Choice(
     *      choices = {
     *          Student::GENDER_FEMALE: "Female",
     *          Student::GENDER_MALE: "Male"
     *      },
     *      message = "Choose a valid gender.", groups={"new"}
     * )
     */
    private $gender;
}
8
  • In your example it should be noted that you need to add the use statement if you link to other classes. Commented Dec 3, 2016 at 14:44
  • Have you tried your example @ZhukV? I just tried a use statement and an external class and unfortunately the constants are not used. Maybe the Doctrine annotations won't work with @Assert? It seems to work with Expressions though: stackoverflow.com/a/34479472/1937050 Commented Dec 3, 2016 at 14:52
  • @webDEVILopers, please not merge doctrine annotation and symfony expression language. These components have difference logic and processes for read/process annotation. Doctrine annotation only read annotation from method/property/class AND ONLY! Symfony constraints can work with any logic with constraint system.
    – ZhukV
    Commented Dec 4, 2016 at 21:26
  • Thanks @ZhukV! Indeed the following version works: gist.github.com/webdevilopers/… Commented Dec 6, 2016 at 12:23
  • i'm trying to use assert\choice with multiple=false and expanded=false as i use them in a normal FormType.. multiple is working fine but expanded throws an exception, i checked the documentation and there's no expanded option.. any idea if i'm missing something? Commented Feb 2, 2017 at 12:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.