按字母顺序对Symfony EntityType中的国家/地区列表进行排序,具体取决于当前的区域设置

时间:2017-07-28 12:38:23

标签: php symfony doctrine

为了获得仅包含我想要显示的国家/地区的HTML选择标记,并通过 Symfony Intl组件see doc here)翻译它们的语言环境我的网站发生了变化,我创建了一个国家/地区实体,并使用自定义getter getTranslatedName()通过其ISO代码检索翻译后的名称。

然后在我需要获取国家/地区列表的 ContactType 表单类型中,我为这些国家/地区设置了 EntityType

它运行正常,但是当您更改区域设置时,这些国家/地区不按字母顺序排序(默认区域设置为英语)。

我怎样才能做到这一点?

我的自定义吸气剂:

/**
 * @return null|string
 */
public function getCountryName()
{
    if (null === $this->getIso()) {
        return $this->getName();
    }
    return Intl::getRegionBundle()->getCountryName($this->getIso());
}

我的实体类型:

->add('country', EntityType::class, array(
    'class' => Country::class,
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('c')
            ->where('c.cc IS NOT NULL')
            ->orderBy('c.name', 'ASC');
    },
    'choice_label' => 'countryName',
    'choices_as_values' => true,
    'data' => $options['country'],
    'required' => true,
    'placeholder' => 'Choose from the list',
    'label'  => 'Country'
))

1 个答案:

答案 0 :(得分:1)

您不需要从数据库加载国家/地区。您可以覆盖CountryType并过滤您要选择的国家/地区。然后只在您的实体中存储ISO代码。在模板中,您可以显示国家/地区名称using some filter

namespace AppBundle\Form\Extension;

use Symfony\Component\Form\Extension\Core\Type\CountryType as BaseCountryType;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Intl\Intl;

class CountryType extends BaseCountryType
{
    /**
     * {@inheritdoc}
     */
    public function loadChoiceList($value = null)
    {
        if (null !== $this->choiceList) {
            return $this->choiceList;
        }

        $countryNames = array_filter(Intl::getRegionBundle()->getCountryNames(), function ($name, $isoCode) {
            return in_array($isoCode, ['US', 'CA', 'RU']);
        });

        return $this->choiceList = new ArrayChoiceList(array_flip($countryNames), $value);
    }
}