Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 : Get available choices of a choice Field Type

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).

like image 436
Bonswouar Avatar asked Jul 03 '13 17:07

Bonswouar


1 Answers

You can access choses labels and their values like this:

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

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

like image 81
Hast Avatar answered Nov 07 '22 20:11

Hast