Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active January 30, 2022 00:02
Show Gist options
  • Save ismail1432/e0237c65debd7e7f261d2044e4124772 to your computer and use it in GitHub Desktop.
Save ismail1432/e0237c65debd7e7f261d2044e4124772 to your computer and use it in GitHub Desktop.
<?php
namespace App\Form;
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([
// Dfine 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']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment