简体   繁体   中英

How to fix 'Object of class could not be converted to string' error when creating a form in Symfony?

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!

So this was actually a bit interesting.

Symfony already has a ColorType. You would not expect that creating your own ColorType would matter as the fully qualified class name should be used if anything really wanted to know if ColorType was being used. But no, only the ColorType string is used for the default form templates. Never encountered it before.

The solution is simple. Rename ColorType to something like MyColorType and all should be well.

And it might have helped if the first line of the exception trace had been included in your question:

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)

Maybe not but that is what keyed me to the problem when I reproduced the test case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM