如何修复Symfony 5错误:Object of class Proxies\__CG__\App\Entity could not be converted to string

2021年11月29日20:17:38 发表评论 893 次浏览

了解导致 Symfony 5 异常“Object of class Proxies__CG__\App\Entity could not be converted to string”的原因以及如何修复它。

如何修复Symfony 5错误:Object of class Proxies\__CG__\App\Entity could not be converted to string
Object of class Entity could not be converted to string解决办法

Symfony 很棒,这是肯定的。它包含许多工具,你可以使用这些工具来缩短项目的开发时间,自动执行非常重要的工作,例如从现有表格生成表格,因此你无需从头开始将它们编写为学说实体。如果你不完全理解 Symfony 命令的作用,使用上述工具当然可能会导致一些异常出现在你的项目中。

在出现“Object of class Proxies\__CG__\App\Entity could not be convert to string”的情况下,很可能是你从数据库中自动生成了学说实体,因此实体没有魔法__toString方法。如何修复错误Object of class Entity could not be converted to string?在本文中,我将向你解释如何轻松防止出现此异常。

错误示例

为了像你现在使用的那样复制此错误,我们将使用一个非常基本的示例。我们确实有 2 个具有多对一关系的表:

如何修复Symfony 5错误:Object of class Proxies\__CG__\App\Entity could not be converted to string

当用户在数据库中注册一个新人时,需要提供用户居住的状态,很简单。此信息转换为条令实体后,对于Person.php实体分别如下所示:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Person
 *
 * @ORM\Table(name="person")
 * @ORM\Entity
 */
class Person
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string|null
     *
     * @ORM\Column(name="first_name", type="string", length=255, nullable=true, options={"default"="NULL"})
     */
    private $firstName;

    /**
     * @var string|null
     *
     * @ORM\Column(name="last_name", type="string", length=255, nullable=true, options={"default"="NULL"})
     */
    private $lastName;

    /**
     * @var \States
     *
     * @ORM\ManyToOne(targetEntity="States")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="states_id", referencedColumnName="id")
     * })
     */
    private $state;

    public function getId(): ?string
    {
        return $this->id;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setLastName(?string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(?string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getState(): ?State
    {
        return $this->state;
    }

    public function setState(?State $state): self
    {
        $this->state = $state;

        return $this;
    }
}

State.php实体:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Table(name="state")
 * @ORM\Entity
 */
class State
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;

    public function getId(): ?string
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->nombre;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}

在我们的例子中,它们是使用doctrine:mapping:import(使用逆向工程)自动创建的。然后,我们通过generate:doctrine:crud. 这将生成视图,用户应该能够在其中查看数据库中的所有项目以及用于创建和编辑 Person 实体的表单:

<?php

namespace App\Controller;

use App\Entity\Person;
use App\Form\PersonType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/person")
 */
class PersonController extends AbstractController
{
    /**
     * @Route("/", name="person_index", methods={"GET"})
     */
    public function index(): Response
    {
        // .. //
    }

    /**
     * @Route("/new", name="person_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $persona = new person();
        $form = $this->createForm(PersonType::class, $persona);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($persona);
            $entityManager->flush();

            return $this->redirectToRoute('person_index');
        }

        return $this->render('person/new.html.twig', [
            'persona' => $persona,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="person_show", methods={"GET"})
     */
    public function show(person $persona): Response
    {
        // .. //
    }

    /**
     * @Route("/{id}/edit", name="person_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, person $persona): Response
    {
        // .. //
    }

    /**
     * @Route("/{id}", name="person_delete", methods={"DELETE"})
     */
    public function delete(Request $request, person $persona): Response
    {
        // .. //
    }
}

现在,如果用户访问编辑或新路由,则会出现异常。

Object of class Entity could not be converted to string解决办法

出现此错误的唯一原因是实体中没有魔术__toString方法State

<?php

class MyEntity
{
    public function __toString() {
        return $this->somePropertyOrPlainString;
    }
}

修复错误Object of class Entity could not be converted to string:即使我们处于 Person 形式。基本上,因为当表单被渲染时,Symfony 不知道应该在选择字段上显示什么导致错误,所以在这种情况下,因为选择(state_id)应该允许用户选择在数据库,当列表中的实体被打印为字符串时,我们应该返回实体的 name 属性,在魔术方法中返回其值:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Table(name="state")
 * @ORM\Entity
 */
class State
{
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $nombre;

    // Register Magic Method to Print the name of the State e.g California
    public function __toString() {
        return $this->name;
    }
}

允许表单毫无例外地呈现状态列表:

如何修复Symfony 5错误:Object of class Proxies\__CG__\App\Entity could not be converted to string

快乐编码❤️!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: