[英]Symfony2 : Sort / Order a translated entity form field?
我正在嘗試訂購實體表單字段女巫被翻譯。
我正在使用 symfony 翻譯工具,所以我無法使用 SQL 語句對值進行排序。 有沒有辦法在加載和翻譯后對值進行排序?
也許使用表單事件?
$builder
->add('country', 'entity',
array(
'class' => 'MyBundle:Country',
'translation_domain' => 'countries',
'property' => 'name',
'empty_value' => '---',
)
)
我找到了在表單類型中對字段值進行排序的解決方案。
我們必須使用在創建表單視圖時調用的 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' => '---',
)
)
;
}
}
舊答案
我找到了解決我的問題的方法,我可以在創建視圖后在我的控制器中對它們進行排序:
$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'));
}
);
也許我可以用更好的方式做到這一點? 最初我希望直接在我的表單構建器中執行,而不是在我使用此表單的控制器中添加額外的代碼。
我認為這是不可能的。 您需要使用PHP
排序,但如果您使用 Symfony Form Type,我建議在頁面加載后使用JavaScript
對其進行排序。
如果您的國家/地區位於數組中,只需使用帶有SORT_STRING
標志的sort()
函數SORT_STRING
。 在我看來,你會做一些體操來擁有它。 檢查這個文檔: http : //php.net/manual/fr/function.sort.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.