Symfony 6.0.2:如何根据语言显示对应国旗表情?
问题:如何实现语言选择框旁显示对应国旗表情
我想实现选中语言时,在选项旁显示对应的国旗表情。之前参考过一个仅适用于国家选择的方案,但需要改成适配语言的功能。我尝试把代码里的Countries替换成Languages、CountryType替换成LanguageType,但这样修改还不够。目前我用的是国家码对应的偏移值0x1F1A5,想问问有没有适配语言码的实现方式?
EmojiType.php
<?php namespace App\Form\Both; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\ChoiceList\ChoiceList; use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Intl\Countries; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class EmojiType extends AbstractType { public function getParent() { return CountryType::class; } public static function getEmojiFlag(string $countryCode): string { $regionalOffset = 0x1F1A5; return mb_chr($regionalOffset + mb_ord($countryCode[0], 'UTF-8'), 'UTF-8') . mb_chr($regionalOffset + mb_ord($countryCode[1], 'UTF-8'), 'UTF-8'); } public function configureOptions(OptionsResolver $resolver) { // Define defaults options $resolver->setDefaults([ // Define the list to display 'choice_loader' => function (Options $options) { return ChoiceList::lazy($this, function () use ($options) { $choices = []; // Countries::getNames() return an array with the country code as key and the country name as value // we fetch all countries code with country name translated according to the locale. $countriesCode = Countries::getNames($options['choice_translation_locale']); foreach ($countriesCode as $countryCode => $displayed) { // we create an array with the country code as key and we concatenate the emoji // and the country name as value. $choices[$countryCode] = self::getEmojiFlag($countryCode) . ' ' . $displayed; } return array_flip($choices); }); }, // define the option to define the country by the locale 'choice_translation_locale' => null, ]); // define the allowed type $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); } }
NewLanguage.php
<?php namespace App\Form\Both; use App\Entity\Language; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; class NewLanguageType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('name') ->add('code', EmojiType::class) ->add('save', SubmitType::class) ; } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Language::class ]); } }
内容的提问来源于stack exchange,提问作者Emilie Tossan
相关产品推荐
相关产品推荐

