可能有更好的方法来获取使用该语言的所有国家/地区,但您可以为每种语言创建一组 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';
}
}