Search code examples
phpsymfonysymfony2-easyadmin

Symfony 3 easyadmin __toString() must not throw an exception


I'm using EasyAdmin Bundle. When I'm trying to add a new element in Entity named "Company" which have 'ManyToMany' relation with "Service" entity I'm getting an error:

Error: Method AppBundle\Entity\Service::__toString() must not throw an exception

But when I'm going to add a new element in "Service" entity, everything works fine and the field with "Company" entities is displaying correctly.

I was trying to catch the exception implementing this workaround, but It doesn't take effect.

The Service class:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Company
 *
 * @ORM\Table(name="company")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CompanyRepository")
 */
class Company
{

/**
     * @var
     * 
     * Many Companys have Many Services.
     * @ORM\ManyToMany(targetEntity="Service", inversedBy="companys")
     * @ORM\JoinTable(name="companys_services")
     */
    private $services;

    public function __construct() {
        $this->services = new ArrayCollection();
    }
public function __toString() 
    {
        return $this->name;
    }
}

And the Service class:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Service
 *
 * @ORM\Table(name="service")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ServiceRepository")
 */
class Service
{
/**
     * Many Services have Many Companys.
     * @ORM\ManyToMany(targetEntity="Company", mappedBy="services")
     */
    private $companys;

    public function __construct() 
    {
        $this->companys = new ArrayCollection();
    }

    public function __toString() 
    {
        return (string) $this->name;
    }
}

What is wrong?


Solution

  • The error message is so specific (Service::__toString() must not throw an exception) that the problem must be in the $this->name property of Service. Is it defined? Is a "normal" property or some advanced object which fails when casting it into a string?