在symfony2中调用非对象错误的成员函数setCode()

I have a cotroller action like

public function updateAction()
    {
        $em = $this->getDoctrine()->getManager();
        $codesArray=array('AFGHANISTAN;AF','ÅLAND ISLANDS;AX','ALBANIA;AL');
        foreach ($codesArray as $detail)
        {
            $detailArray=explode(";",$detail);
            $country=$em->getRepository('TestBundle:Countries')
                          ->findOneBy(array('name'=>$detailArray[0]));
            $country->setCode($detailArray[1]);
        }
        $em->flush();
    }

it shows error

FatalErrorException: Error: Call to a member function setCode() on a non-object

but when i replace

$country=$em->getRepository('TestBundle:Countries')
                          ->findOneBy(array('name'=>$detailArray[0]));

with

$country=$em->getRepository('TestBundle:Countries')
                              ->find('1');

means it will update 1st record. please give me the solution for this.

Repository ( and Entity ) names are normally singular.

If your entity class is Country you get your Repository with:

 $country=$em->getRepository('TestBundle:Country')-> ...

I don't know what you're trying to do but you can get those Country codes from the symfony2 Intl component ...

use Symfony\Component\Intl\Intl;

\Locale::setDefault('en');

$countries = Intl::getRegionBundle()->getCountryNames();
// => array('AF' => 'Afghanistan', ...)

$country = Intl::getRegionBundle()->getCountryName('GB');
// => 'United Kingdom'