处理Symfony Intl提供的国家/地区列表和表单选择类型 [英] Manipulate the list of countries provided by Symfony Intl and the form choice type

查看:92
本文介绍了处理Symfony Intl提供的国家/地区列表和表单选择类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了政治之外,在选择国家/地区时,我还需要提供科索沃作为表格选择.

Politics aside, I need to provide Kosovo as a form choice when selecting a country.

使用Symfony的内置表单选择类型country进行此操作的最优雅的方法是什么,同时还提供科索沃名称的翻译?

What's the most elegant way of doing this with Symfony's built-in form choice type country, while also providing translations for the Kosovo name?

到目前为止,这是我所做的并且可以正常工作,但是我担心这可能有点hacking.

Here's what I've done so far and it works but I'm concerned this might be a bit 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的静态方法(如上)并添加自定义国家/地区. 然后,将该服务注入您的表单类型.或者(甚至更好),定义您的自定义类型(例如"MyCountry")并使用它代替标准的country.

You should create your service, in wich you use Intl's static method (like above) and add your custom countries. Then, inject that service into your form type. Or (even better), define your custom type (something like "MyCountry") and use it instead of standard country one.

这篇关于处理Symfony Intl提供的国家/地区列表和表单选择类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆