symfony - 操作 Symfony Intl 提供的国家列表和表单选择类型

标签 symfony internationalization locale intl

撇开政治不谈,我需要在选择国家/地区时提供科索沃作为表单选择。

使用 Symfony 的内置表单选择类型 country,同时还提供 Kosovo 名称的翻译,最优雅的方法是什么?

这是我到目前为止所做的并且它有效,但我担心这可能有点 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))
        ;
    }
}

最佳答案

您应该创建您的服务,使用 Intl 的静态方法(如上)并添加您的自定义国家/地区。 然后,将该服务注入(inject)您的表单类型。或者(甚至更好)定义您的自定义类型(类似于“MyCountry”)并使用它代替标准的 country 类型。

关于symfony - 操作 Symfony Intl 提供的国家列表和表单选择类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20816790/

相关文章:

ruby-on-rails - 本地 yaml key 的 i18n 同步

unicode - Python 3 UnicodeEncodeError : 'ascii' codec can't encode characters

php - FOSUserBundle 和 REST Api 调用 : How to use custom FormType?

Symfony2 和 Doctrine2 - 记录变更历史

mysql - Unicode CSV 文件中未显示孟加拉语文本

c++ - clang++ C++0x std::locale

java - ResourceBundle 仅理解 "en"区域设置

jquery - jquery 中的 Twig 无法读取 jquery 变量

symfony - JMSerializer 按属性条件排除实体

带有变量的 Django blocktrans