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).
You can access choses labels and their values like this:
$form->get('civility')->getConfig()->getOption('choices');
Read more: Symfony\Component\Form\FormConfigInterface::getOption()