php - Alphabetically sort a country list in a Symfony EntityType depending on the current locale -
in order html select tag of countries countries want appear, , having them translated through symfony intl component (see doc here) when locale of website changes, i've created country entity, custom getter gettranslatedname()
retrieve translated name through iso code.
then in contacttype form type needs country list, have entitytype countries.
it's working fine, countries not alphabetically sorted when change locale (default locale english).
how can achieve ?
my custom getter :
/** * @return null|string */ public function getcountryname() { if (null === $this->getiso()) { return $this->getname(); } return intl::getregionbundle()->getcountryname($this->getiso()); }
my entitytype :
->add('country', entitytype::class, array( 'class' => country::class, 'query_builder' => function (entityrepository $er) { return $er->createquerybuilder('c') ->where('c.cc not null') ->orderby('c.name', 'asc'); }, 'choice_label' => 'countryname', 'choices_as_values' => true, 'data' => $options['country'], 'required' => true, 'placeholder' => 'choose list', 'label' => 'country' ))
you don't need load countries database. can override countrytype
, filter countries want select. store in entities iso code. in templates can show country name using filter.
namespace appbundle\form\extension; use symfony\component\form\extension\core\type\countrytype 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); } }
Comments
Post a Comment