3

I'm trying to build a form that I will implement in a Twig template. For that, I'm using some HTML elements. One of them is The ChoiceType from Symfony component. I've created an array that i pass to the add method. My wish is to display the keys in the value attribute and each value of the array in the label, thing I have failed to do

protected $lsa_types = array(
    'B' => 'Boolean',
    'D' => 'Date',
    'F' => 'Float',
    'I' => 'Integer',
    'L' => 'List',
    'S' => 'String',
    'T' => 'Text',
);

$form->add('type', ChoiceType::class, array('choices' => $this->lsa_types,
            'choice_label' => function ($value) {
                return $value;
            },
            'choice_value' => function ($key) {
                return $key;
            },
            'required' => true));
3
  • 1
    the problem here is you dont have $value | $key from the array that you are trying to pass to the closure, you might want to re-work on your array to look something like $array = [ ["key"=>"B", "value"=>"Boolean"], ["key"=>"D", "value"=>"Date"],... ]; and then you can pass to closure like, ... "choice_label" => function($data) {return $data['value']; } and so on Commented Aug 29, 2017 at 10:08
  • Try to flip your array and using "choices_as_values" => true as option of your ChoiceType Commented Aug 29, 2017 at 13:23
  • choices_as_values is deprecated since the third version of symfony Commented Aug 29, 2017 at 13:32

1 Answer 1

4

Do as @Massimiliano commented, but leave out the choices_as_values, choice_label & choice_value options:

protected $lsa_types = array(
    'B' => 'Boolean',
    'D' => 'Date',
    'F' => 'Float',
    'I' => 'Integer',
    'L' => 'List',
    'S' => 'String',
    'T' => 'Text',
);

...

$choices = array_flip($this->lsa_types);

$form
    ->add(
        'type', 
        ChoiceType::class, 
        array(
            'choices' => $choices,
            'required' => true
        )
    )
;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.