Symfony2 : Sort / Order a translated entity form field?

后端 未结 3 855
刺人心
刺人心 2021-01-14 11:00

I am trying to order an entity form field witch is translated.

I am using the symfony translation tool, so i can\'t order values with a SQL statement. Is there a way

3条回答
  •  [愿得一人]
    2021-01-14 11:09

    I found the solution to sort my field values in my Form Type.

    We have to use the finishView() method which is called when the form view is created :

    translator = $translator;
        }
    
        public function finishView(FormView $view, FormInterface $form, array $options)
        {
            // Order translated countries
            $collator = new \Collator($this->translator->getLocale());
            usort(
                $view->children['country']->vars['choices'], 
                function ($a, $b) use ($collator) {
                    return $collator->compare(
                        $this->translator->trans($a->label, array(), 'countries'), 
                        $this->translator->trans($b->label, array(), 'countries')
                    );
                }
            );
        }
    
        // ...
    
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('country', 'entity', 
                        array(
                            'class' => 'MyBundle:Country',
                            'translation_domain' => 'countries',
                            'property' => 'name',
                            'empty_value' => '---',
                        )
                    )
            ;
        }
    
    }
    

    OLD ANSWER

    I found a solution for my problem, I can sort them in my controller after creating the view :

    $fview = $form->createView();
    usort(
        $fview->children['country']->vars['choices'], 
        function($a, $b) use ($translator){
            return strcoll($translator->trans($a->label, array(), 'countries'), $translator->trans($b->label, array(), 'countries'));
        }
    );
    

    Maybe I can do that in a better way ? Originally I wished to do directly in my form builder instead of adding extra code in controllers where I use this form.

提交回复
热议问题