【问题标题】:How to fix 'Object of class could not be converted to string' error when creating a form in Symfony?在 Symfony 中创建表单时如何修复“类对象无法转换为字符串”错误?
【发布时间】:2019-05-07 16:37:21
【问题描述】:

我正在使用 Symfony 制作一个非常简单的表单来为数据库添加颜色。在我的 Controller 中使用 createFormBuilder 时效果很好,但在使用 createForm 和我制作的 Type 时会抛出错误。这是我得到的错误:在渲染模板期间引发了异常(“可捕获的致命错误:类 App\Entity\Color 的对象无法转换为字符串”)。 p>

我逐行关注Symfony doc,我还尝试了这里提供给其他有同样问题的其他人的一些解决方案(例如,将__toString 方法添加到我的实体中),但没有任何效果。


实体

/**
 * @ORM\Entity(repositoryClass="App\Repository\ColorRepository")
 */
class Color
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=190, unique=true)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=190, unique=true)
     */
    private $code;

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

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

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

        return $this;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(string $code): self
    {
        $this->code = $code;

        return $this;
    }
}


控制器

public function new(Request $request)
    {
        $color = new Color();

        $form = $this->createForm(ColorType::class, $color);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
             $color = $form->getData();

             $entityManager = $this->getDoctrine()->getManager();
             $entityManager->persist($color);
             $entityManager->flush();

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

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


表格

class ColorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'couleur',
            ])
            ->add('code', TextType::class, [
                'label' => 'code couleur',
            ])
            ->add('save', SubmitType::class, ['label' => 'ajouter la couleur'])
        ;
    }

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


模板

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

{% block title %}
    Ajouter une couleur
{% endblock %}

{% block content %}
    {{ form(form) }}
{% endblock %}

我希望它使用各自的标签和提交按钮呈现两个文本输入,而不是抛出我提到的错误。我通过在我的 Controller 中评论 $color = new Color(); 并因此没有将 $color 作为参数传递给 createForm 方法来让它工作,但它不仅呈现两个文本输入和提交按钮,而且表单开头的颜色输入...(我没有要求)。

提前感谢您的帮助!

【问题讨论】:

  • 当然,您似乎从文档中复制了代码。错误似乎来自模板。尝试将您的模板缩减为 {{ form(form) }} 您提到的颜色输入有点暗示您的模板中可能有额外的东西。
  • 我的模板已经只有{{ form(form) }} ...我已经添加了我的帖子来展示我的模板的外观。
  • 非常神秘。 Symfony 版本?仔细检查所有命名空间和使用语句是否正确。并且您正在编辑正在测试的相同代码(它发生了)。只是抓住这里。

标签: php forms symfony


【解决方案1】:

所以这实际上有点有趣。

Symfony 已经有一个 ColorType。您不会期望创建自己的 ColorType 很重要,因为如果真的想知道是否使用了 ColorType,则应该使用完全限定的类名。但不,只有 ColorType 字符串用于默认表单模板。以前没遇到过。

解决方案很简单。将 ColorType 重命名为 MyColorType 之类的名称,一切都会好起来的。

如果异常跟踪的第一行包含在您的问题中,它可能会有所帮助:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class App\Entity\Color could not be converted to string").
in vendor/symfony/twig-bridge/Resources/views/Form/form_div_layout.html.twig (line 17)

也许不是,但这正是我重现测试用例时问题的关键。

【讨论】:

  • 另一种方法是添加块前缀并添加在使用自定义 ColorType 时实际始终使用的模板。 symfony 4.3 发布后可能会更容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 2014-11-21
  • 2015-02-05
相关资源
最近更新 更多