3

政治はさておき、国を選択する際にフォームの選択肢としてコソボを提供する必要があります。

コソボの名前countryの翻訳も提供しながら、Symfony の組み込みフォームの Choice type でこれを行う最もエレガントな方法は何ですか?

これが私がこれまでに行ったことであり、機能しますが、これは少しハックっぽいのではないかと心配しています.

<?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))
        ;
    }
}
4

2 に答える 2

2

Intlの静的メソッド (上記のように)を使用してサービスを作成し、カスタムの国を追加する必要があります。次に、そのサービスをフォーム タイプに挿入します。または(さらに良い)カスタムタイプ(「MyCountry」など)を定義し、標準タイプの代わりに使用しますcountry

于 2014-07-01T13:15:15.060 に答える