gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:54:50 33 4
gpt4 key购买 nike

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

使用 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com