Symfony 2 : Get available choices of a choice Field Type
Asked Answered
M

1

11

1) Is there a symfony method ?

I've got a basic form (not mapped to the database), with some choice fields, for example :

    $builder->add('civility', 'choice',  array('choices'=> array('m' => 'M.', 'mme' => 'Mme', 'mlle' => 'Mlle')))

How can I - after the form was submited - in the action (or, even better, in the template), retrieve the label value of the option instead of the form submitted value ? (in this case, I want to be able to render "M." in the template instead of "m")

I was thinking about something like $form->get("civility")->getChoiceLabel($form->get("civility")->getData())

But I didn't find anything like this in the documentation (though there was something like that in Symfony1).

2) If Really not, what's the best way to make it ?

Thus, I was thinking about creating some methods to do that, in the Data Class used by the form, like .. :

private $choices = array("civility" => array('m' => 'M.', 'mme' => 'Mme', 'mlle' => 'Mlle'));
static public function getChoiceLabel($choice_value, $field_name)
{
    return  self::$choices[$field_name][$choice_value];
}

static public function getChoices($field_name)
{
    return self::$choices[$field_name];
}

But the problem is that we're not supposed to use static methods in the twig template (I have to make it Static to be able to use it in the form generation, the buildForm method, and not duplicate some code).

Manganese answered 3/7, 2013 at 17:1 Comment(1)
When you print $form['civility'] you cannot find the labels you are looking for? Try printing the field before and after calling createView on $formMok
M
17

You can access choses labels and their values like this:

$form->get('civility')->getConfig()->getOption('choices');

Read more: Symfony\Component\Form\FormConfigInterface::getOption()

Minima answered 3/7, 2013 at 19:20 Comment(2)
Perfect, that's exactly what I was looking for ! It's pretty hard to find in the documentation, even in the API.. How do yo usually find stuff like that ?Manganese
Autocompletion feature in my IDE (phpstorm). I just looked for all methods for that class and found what I need. And ofcourse API documentation helps me sometimes too.Minima

© 2022 - 2024 — McMap. All rights reserved.