有可能是一個更好的辦法來獲取所有使用這種語言的國家,但你可以爲每種語言創建的ISO alpha-2國家代碼數組,然後在現場傳遞到自定義表單類型之一所需的選項。
public function registerAction(Request $request)
{
$builder->add('location', new LocationType(), array(
'locale' => $request->getLocale(),
));
}
自定義表單類型
<?php
namespace Your\Bundle\WebsiteBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LocationType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$preferredChoices = array(
'en' => array(
'US', // United States
'CA', // Canada
'GB', // United Kingdom
'IE', // Ireland
'AU', // Australia
'ZA', // South Africa
// etc
),
'it' => array(
'IT', // Italy
'CH', // Switzerland
),
'nl' => array(
'NL', // Netherlands
'BE', // Belgium
'SR', // Suriname
'ZA', // South Africa
),
);
$builder
->add('country', 'country', array(
'preferred_choices' => $preferredChoices[$options['locale']],
))
// ->add(more)
;
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setRequired(array(
'locale',
));
$resolver->setAllowedTypes(array(
'locale' => 'string',
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'location';
}
}
是THX是有道理的,但我一直在尋找一種方式來獲得從內置的國際化系統,陣列,而不必把它寫自己...一個選項也許是以[az] _ [AZ]格式獲取所有完整語言環境的列表,然後提取所有以我的短語言環境開始的所有內容...但我想知道是否有更好的方法... – smarques 2014-10-18 16:14:25
一種選擇是使用 $ variants = \ Symfony \ Component \ Intl \ Intl :: getLocaleBundle() - > getLocaleNames(); ,然後通過僅選擇以語言代碼開頭的元素進行過濾。 仍然是一個大陣列,所以這可能是低效的,最好是創建每個子陣列的緩存。 – smarques 2014-10-19 16:54:01