代码之家  ›  专栏  ›  技术社区  ›  VinZ

根据当前区域设置,按字母顺序对Symfony EntityType中的国家/地区列表进行排序

  •  1
  • VinZ  · 技术社区  · 7 年前

    为了获得一个HTML select标记,其中只包含我想要显示的国家,并通过 Symfony国际组件 ( see doc here )当我的网站的区域设置发生变化时,我创建了一个 实体,带有自定义getter getTranslatedName() 通过ISO代码检索翻译后的名称。

    然后在我的 联系人类型 实体类型 为了国家。

    它工作正常,但是当您更改区域设置时,国家不会按字母顺序排序(默认区域设置为英语)。

    /**
     * @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 回复  |  直到 7 年前
        1
  •  2
  •   jkucharovic    7 年前

    您不需要从数据库中加载国家。您可以覆盖 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);
        }
    }