Mikz
Mikz

Reputation: 700

Symfony form & entity & choice constraint confusion

I've got Doctrine entity with some choice field, let's say that it looks like this:

/**
 * @var string
 * @ORM\Column(name="color", type="string", nullable=false)
 * @Assert\Choice(choices = {"red", "green", "blue"}, message="Choose valid color")
 */
 protected $color;

And now I've got a form that's associated with my entity, let's say that specific field looks like that inside of it:

$builder->add(
    'color',
    'choice',
    array(
        'choices'  => array(
            'red'   => 'Red like roses',
            'green' => 'Green like grass',
            'blue'  => 'Blue like sky'
        ),
        'expanded' => true
    )
);

As far as I'm now, it's quite clear that possible values are duplicated inside constraint and inside the form. But let's go further, I'd like to display my entity inside of a template, so I must do something like that:

{% if entity.color == 'red' %}
Red like roses
{% elseif entity.color == 'green' %}
Green like grass
{% elseif entity.color == 'blue' %}
Blue like sky
{% endif %}

So we've now got a third place where not only values, but also labels are duplicated. I've thought of something like a service that serves as a twig extension and can be injected into the form builder but it doesn't solve duplication with constraint. Now I've got no idea how to solve it, I'd really like to have just one single place where I define things like that and most of all I'd like to keep them inside of entity as annotations but I don't know how to proceed with this.

Any ideas?

Upvotes: 1

Views: 1300

Answers (1)

greg0ire
greg0ire

Reputation: 23265

Instead of hardcoding the choices in your mapping, you should provide them with a callable. You could use my enum package for that.

Upvotes: 1

Related Questions