Question

I have hit a very weird speed bump and would like extra mind to figure out this logic

I have 3 Entities, Country which stores country details, Language which has language info and finally CountryLanguage which houses country names in different languages.

Now my problem is, I want to display countries names on a dropdown in a particular language say english only using the __toString function.

Please see code below in my Country entity file from which i'm getting this error: Country::__toString() must return a string value

public function __toString()
{
    $names = $this->getLanguages();
    foreach($names as $name)
    {
        if($name->getLanguage()->getId() == 1 /*id for english */)
        {

    return $name->getCountryName();
        }            
    } 
}

I'd be really grateful for your time in helping me solve this

Was it helpful?

Solution

Just to show you more effective way:

$names = $this->getLanguages();

if($names && count($names) > 0)
{
    foreach($names as $name)
    {
        if($name->getLanguage()->getId() == 1)
        {
            return $name->getCountryName();
        }            
    }
}else
{
    return '';
} 

OTHER TIPS

Ok, got this to work like this but i'm not sure it's the cleanest answer and will be open to being corrected.

public function __toString()
{
    $names = $this->getLanguages();
    $country = '';
    foreach($names as $name)
    {
        if($name->getLanguage()->getId() == 1)
        {
            $country = $name->getCountryName();
        }            
    } 
    return $country;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top