php 无法将类App\Entity\User的Symfony6窗体呈现对象转换为字符串

ocebsuys  于 2023-06-20  发布在  PHP
关注(0)|答案(3)|浏览(116)

我试图呈现Team实体的形式,该实体连接到具有ManyToOne关系的User。参见下面的实体类:

<?php

namespace App\Entity;

class Team
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'teams')]
    #[ORM\JoinColumn(nullable: false)]
    private ?User $owner = null;
...

下面是User实体类代码:

<?php

namespace App\Entity;

Class User {

    #[ORM\OneToMany(mappedBy: 'owner', targetEntity: Team::class)]
    private Collection $teams;
....

下面是我渲染表单视图的控制器类代码:

<?php

namespace App\Controller;

class TeamController extends AbstractController
{
    #[Route('/new', name: 'app_team_new', methods: ['GET', 'POST'])]
    public function new(Request $request, TeamRepository $teamRepository): Response
    {
        $team = new Team();
        $form = $this->createForm(TeamType::class, $team);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $teamRepository->save($team, true);

            return $this->redirectToRoute('app_team_index', [], Response::HTTP_SEE_OTHER);
        }

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

下面是TeamType表单类

<?php

namespace App\Form;

class TeamType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name')
            ->add('intro')
            ->add('country')
            ->add('balance')
            ->add('created_at')
            ->add('updated_at')
            ->add('owner')
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Team::class,
        ]);
    }
}
...

最后,team/new.html.twig

{% extends 'layouts/base.html.twig' %}

{% block title %}
    New Team
{% endblock %}

{% block body %}
    <main class="container form-signin w-100 m-auto">
        <h1>Add Team</h1>

        {{ form_start(form) }}
        {{ form_widget(form) }}
        <button class="btn">{{ button_label|default('Save') }}</button>
        {{ form_end(form) }}

        <a href="{{ path('app_team_index') }}" class="btn btn-link bi bi-arrow-left text-decoration-none">
            &nbsp; Back to all teams</a>
    </main>
{% endblock %}

我得到一个错误,Object of class App\Entity\User could not be converted to string正好靠近'form' => $form,行。
可能的问题是什么?

8nuwlpux

8nuwlpux1#

我找到解决办法了。如果要将实体用作表单字段,则需要在表单类型中指定class和choice_label选项。class选项告诉Symfony哪个实体类用于字段,choice_label选项告诉Symfony哪个属性或方法用作每个选项的标签。要解决这个问题,您需要为User字段配置表单类型,如下所示:

<?php

namespace App\Form;

use App\Entity\Team;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class TeamType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name')
            ->add('intro')
            ->add('country')
            ->add('balance')
            ->add('created_at')
            ->add('updated_at')
            ->add('owner', EntityType::class, [
                'class' => User::class,
                'choice_label' => 'full_name', // or any other property or method that returns a string
            ]);
        ;
    }
...

希望这对某人有帮助。

h43kikqp

h43kikqp2#

当学说试图显示关系时,在您的例子中是Team和User类。根据关系的不同,Doctrine试图将这些类转换为字符串,以便以HTML形式显示具有选项选择值的Select。你应该实现__toString方法

class User
{
  //...
  public function __toString()
  {
    return (string) $this->getUserIdentifier();
  }
}

class Team
{
  //...
  public function __toString()
  {
    return (string) $this->name;
  }
}
3lxsmp7m

3lxsmp7m3#

如果表单仅用于向当前用户添加新团队,则不应在表单中包含所有者字段。相反,请手动将所有者设置为Controller中的当前用户。
因此,从FormType中省略->add('owner', /*...*/);调用,并将处理程序编辑为如下内容(根据特定Entity方法的逻辑进行调整):

public function new(Request $request, TeamRepository $teamRepository): Response
    {
        $team = new Team();
        $user = $this->getUser();
        $user->addTeam($team);
        $team->setOwner($user);

        /* create form and handle Request */
    }

作为在处理程序中设置所有者的替代方法,特别是因为所有者不可为空,您可以在Team构造函数中设置所有者。然后通过传递当前User创建一个Team。

相关问题