抛开政治不谈,我在选择国家时需要提供科索沃作为一种形式选择。
使用 Symfony 的内置表单选择类型country
,同时还提供科索沃名称的翻译,最优雅的方式是什么?
这是我到目前为止所做的并且它有效,但我担心这可能有点hack-ish。
<?php
namespace Acme\Bundle\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Intl\Intl;
class LocationType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Kosovo is not listed as a choice provided by the method call
// `Symfony\Component\Intl\Intl::getRegionBundle()->getCountryNames()`
// although it is mostly recognized as in independent state, including by Google Maps.
// This is because no ISO 3166-1 alpha-2 code as been assigned to that country.
// However, a temporary code 'XK' is available.
$countries = Intl::getRegionBundle()->getCountryNames();
$countries['XK'] = "Kosovo";
$builder
->add('country', 'country', array(
'choices' => $countries,
'preferred_choices' => array(
'XK', // Kosovo
'AL', // Albania
'MK', // Macedonia
'ME', // Montenegro
'GB', // United Kingdom
'US', // United States
),
))
->add('district', 'text', array('required' => false))
->add('town', 'text', array('required' => false))
;
}
}