Easy Admin - Display Full Country Name in Show Action
Asked Answered
S

2

10

I have an Address entity which requires a country. In the associated form I am using Symfony's CountryType which displays a user-friendly selection of countries and stores its abbreviation in the entity (e.g. DE for Germany or CH for Switzerland).

To display the address' country in the show action of the admin panel, I am using the following line in the easy_admin.yaml:

- { property: country, label: 'address.entity.country' }

Problem:

This only displays the abbreviation and not the actual name of the country. How can I change that?

Country in Address entity:

/**
 * @ORM\Column(type="string", length=255)
 */
private $country;
Streaky answered 25/9, 2018 at 8:54 Comment(4)
can you please paste entity class of addrss?Vulgarize
Nothing special about the entity class itself as it only stores the country's abbreviation as a string. I added the country attribute above.Streaky
brother i want to see your __toString method?Vulgarize
Why would I need a toString method? I'm showing the content of the country attribute, not the address class itself.Streaky
A
5

I think the best solution would be to use the built in Symfony intl component.

composer require symfony/intl to install the component.

Then in your entity you can use Symfony\Component\Intl\Intl;.

I suggest creating a new property on your entity called countryName where the setter of that property gets called whenever you set the country code. Your setter could look something like this:

public function setCountryName (string $countryCode) 
{
    $this->countryName = Intl::getRegionBundle()->getCountryName(strtoupper($countryCode));
}

Then in your yaml file change address.entity.country to address.entity.countryName.

Aerology answered 27/9, 2018 at 14:59 Comment(2)
No need for a setter, instead it's way simpler to just create EntityName::getLocalizedCountry() that would return the Intl you added in your code snippet and use $this->country from the entity :)Nullify
But would you be able to use that function in the yaml file of easy admin?Aerology
H
0

I think now using Intl::getRegionBundle() is deprecated, the best will be to use the Countries class of the Intl component of symfony in this way :

use Symfony\Component\Intl\Countries;

public function getCountryName ():string
{
    return Countries::getName($this->getCountry());
}
Hedwighedwiga answered 24/7, 2022 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.