I'm making a really simple form with Symfony to add a color to the database. It's working great when using createFormBuilder
in my Controller, but throws an error when using createForm
with the Type
I made. This is the error I get: 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").
I followed Symfony doc line by line, I also tried some solutions given here to others who had kind of the same problem (adding the __toString
method to my Entity, for example), but nothing works.
Entity
/**
* @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;
}
}
Controller
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(),
]);
}
Form
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,
]);
}
}
Template
{% extends 'layout/base.html.twig' %}
{% block title %}
Ajouter une couleur
{% endblock %}
{% block content %}
{{ form(form) }}
{% endblock %}
I expect it to render two text inputs with their respective label and a submit button, instead it throws the error I mentioned. I got it to work at some point by commenting $color = new Color();
in my Controller and thus not passing $color
as an argument to the createForm
method, but it was rendering not only the two text inputs and the submit button, but also a color input at the beginning of the form... (which I didn't ask for).
Thanks in advance for your help!
{{ form(form) }}
... I've added my post to show how my template looks. – Chloé