猿问

Symfony-可捕获的致命错误:无法将类App \ Entity \ Question

我正在学习Symfony,遇到了这个问题。


可捕获的致命错误:无法将类App \ Entity \ Question的对象转换为字符串


我的目标是通过表单添加到数据库中。


我想我使用的EntityType错误,这是我的表格:


public function buildForm(FormBuilderInterface $builder, array $options)

        {

            $builder

                ->add('question', EntityType::class,

                    [

                        'class' => Question::class

                    ]

                )

                ->add(

                    'answer',

                    TextType::class

                )

                ->add(

                    'valid',

                    ChoiceType::class,

                    [

                        'choices' => [

                            'true' => 1,

                            'false' => 0

                        ]

                    ]

                )

                ->add(

                    'save',

                    SubmitType::class

                )

            ;

        }

这是我的控制器,我在其中构建表单:


 $entityManager = $this->getDoctrine()->getManager();


$answer = new Answer();


        $form = $this->createForm(ExamDatabaseInteractionType::class, $answer);

        $form->handleRequest($request);


        if ($form->isSubmitted()) {

            $entityManager->persist($answer);

            $entityManager->flush();


        }



        return [

            'form' => $form->createView()

        ];


我猜数据库结构在这里也很重要:


describe question;

+----------+--------------+------+-----+---------+----------------+

| Field    | Type         | Null | Key | Default | Extra          |

+----------+--------------+------+-----+---------+----------------+

| id       | int(11)      | NO   | PRI | NULL    | auto_increment |

| question | varchar(255) | NO   |     | NULL    |                |

+----------+--------------+------+-----+---------+----------------+

2 rows in set (0.01 sec)

我希望我的问题结构合理,这是我关于堆栈溢出的第一个问题。


FFIVE
浏览 167回答 1
1回答

qq_笑_17

我很欣赏Symfony如何很好地记录所有内容,您的情况也不例外。有关实体类型,请参阅文档。它具有一个字段选项choice_label:这是用于在HTML元素中将实体显示为文本的属性。如果保留为空白,则实体对象将被强制转换为字符串,因此必须具有一个__toString()方法。您还可以传递回调函数以进行更多控制。因此,您没有指定choice_label,并且没有__toString实现,因此出现了错误。您应该做什么:$builder    ->add('question', EntityType::class,    [        'class' => Question::class,        'choice_label' => 'questionName',    ])或__toString()在中实施Entity\Question。
随时随地看视频慕课网APP
我要回答