我正在学习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)
describe answer;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| question_id | int(11) | YES | MUL | NULL | |
| answer | varchar(255) | NO | | NULL | |
| valid | tinyint(1) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
我希望我能很好地构建我的问题,这是我关于堆栈溢出的第一个问题。
谢谢您的帮助。
我很钦佩Symfony如何记录所有内容,你的情况也不例外。请参阅Entity Type的文档。
它有一个字段选项choice_label
:
这是应该用于在HTML元素中将实体显示为文本的属性。
如果留空,则实体对象将被强制转换为字符串,因此必须具有
__toString()
方法。您还可以传递回调函数以进行更多控制。
所以,你没有指定choice_label
,你没有实现__toString
,因此错误。
你应该做什么:
$builder
->add('question', EntityType::class,
[
'class' => Question::class,
'choice_label' => 'questionName',
])
或者在__toString()
实施Entity\Question
。