Symfony2:对翻译的实体表单字段进行排序/排序?

Seb*_*300 3 forms translation symfony

我正在尝试订购一个实体形式字段女巫被翻译.

我正在使用symfony翻译工具,因此我无法使用SQL语句对值进行排序.有没有办法在加载和翻译后对值进行排序?

也许使用表单事件?

$builder
    ->add('country', 'entity', 
            array(
                'class' => 'MyBundle:Country',
                'translation_domain' => 'countries',
                'property' => 'name',
                'empty_value' => '---',
            )
        )
Run Code Online (Sandbox Code Playgroud)

Seb*_*300 9

编辑

我找到了在表单类型中对字段值进行排序的解决方案.

我们必须使用在创建表单视图时调用的finishView()方法:

<?php

namespace My\Namespace\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;

class MyFormType extends AbstractType
{
    protected $translator;

    public function __construct(Translator $translator)
    {
        $this->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' => '---',
                    )
                )
        ;
    }

}
Run Code Online (Sandbox Code Playgroud)

老答复

我找到了解决问题的方法,我可以在创建视图后在控制器中对它们进行排序:

$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'));
    }
);
Run Code Online (Sandbox Code Playgroud)

也许我能以更好的方式做到这一点?最初我希望直接在我的表单生成器中执行,而不是在我使用此表单的控制器中添加额外的代码.