Does not pull up selected options in the form.

Piece of FormType

->add('categories', ChoiceType::class, [ 'choices' => $this->getCategoryTree(), 'multiple' => true, 'placeholder' => 'ΠšΠΎΡ€Π½Π΅Π²Π°Ρ катСгория', 'choice_label' => function(Category $category) { return $category->getName(); }, 'choice_attr' => function(Category $category) { return ['style' => 'padding-left:' . 15 * ($category->getStep()+1) .'px;' ]; }, 'label' => 'ΠŸΡ€ΠΈΠ²ΡΠ·ΠΊΠ° ΠΊ ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ', 'attr' => [ 'size' => 15 ], 'required' => false ]) 

Piece DataTransformer

 public function transform($categories) { if (null === $categories) { return ''; } foreach ($categories as $category) { $ids[] = $category->getId(); } return $ids; } 

display of the form in templates

 <div class="row"> <div class="col-xs-12"> {{ form_start(form) }} <div class="row"> <div class="col-xs-12"> {{ form_row(form.name) }} </div> </div> <div class="row"> <div class="col-xs-6"> {{ form_row(form.parent) }} </div> <div class="col-xs-6"> {{ form_row(form.categories) }} </div> </div> <div class="row text-right"> <div class="col-xs-12"> {% if form.vars.value.parent is not empty %} {% set parentCategory = form.vars.value.parent.id %}{% else %}{% set parentCategory = null %}{% endif %} <a href="{{ path('user_external_service_category_tree', { 'id' : app.request.attributes.get('id'), 'category': parentCategory }) }}" class="btn btn-default">ΠžΡ‚ΠΌΠ΅Π½Π°</a> {{ form_widget(form.save) }} </div> </div> {{ form_end(form) }} </div> </div> 

How to implement?

  • Someone put a minus in the question. And there is no answer. - Durrasell
  • So where do you set the selected attribute on a form? - Kostiantyn Okhotnyk
  • when using custom or standard symfony types, the selected attribute works without specifying the form and does not need to be explicitly specified. Now I will add a form to the question to make it clear - Durrasell
  • Have you tried to explicitly specify select? - Kostiantyn Okhotnyk 4:42 pm
  • what does it mean explicitly? <select> - Durrasell 5:09

1 answer 1

You must add the data field, to which you specify the array index or entity reference.

 ->add('categories', ChoiceType::class, [ 'choices' => $this->getCategoryTree(), 'multiple' => true, 'placeholder' => 'ΠšΠΎΡ€Π½Π΅Π²Π°Ρ катСгория', 'choice_label' => function(Category $category) { return $category->getName(); }, 'choice_attr' => function(Category $category) { return ['style' => 'padding-left:' . 15 * ($category->getStep()+1) .'px;' ]; }, 'label' => 'ΠŸΡ€ΠΈΠ²ΡΠ·ΠΊΠ° ΠΊ ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ', 'attr' => [ 'size' => 15 ], 'data' => 3, 'required' => false ]) 
  • This method does not work. If you set the column number for example 1, then there is an error of the data formati. If you try to stick function () {} on the date, then the select does not work, and there is also multiple = true. array type must be - Durrasell 8:32 pm