我正在尝试订购一个实体表单字段女巫被翻译。
我正在使用 symfony 翻译工具,所以我无法使用 SQL 语句对值进行排序。 有没有办法在加载和翻译后对值进行排序?
也许使用表单事件?
$builder
->add('country', 'entity',
array(
'class' => 'MyBundle:Country',
'translation_domain' => 'countries',
'property' => 'name',
'empty_value' => '---',
)
)
最佳答案
我找到了对表单类型中的字段值进行排序的解决方案。
我们必须使用创建表单 View 时调用的 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' => '---',
)
)
;
}
}
老答案
我找到了解决问题的方法,我可以在创建 View 后在 Controller 中对它们进行排序:
$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'));
}
);
也许我可以用更好的方式做到这一点? 最初我希望直接在我的表单生成器中执行,而不是在我使用此表单的 Controller 中添加额外的代码。
关于forms - Symfony2 : Sort/Order a translated entity form field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21553719/