【发布时间】: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 版本?仔细检查所有命名空间和使用语句是否正确。并且您正在编辑正在测试的相同代码(它发生了)。只是抓住这里。