来自现有数据库的
但它不适用于异常消息:
必须管理传递到选择字段的实体 . 也许坚持他们在实体经理?
Entity
/**
* Question
*
* @ORM\Table(name="question", indexes={@ORM\Index(name="question_category_id", columns={"question_category_id"})})
* @ORM\Entity
*/
class Question
{
//...
/**
* @var \AppBundle\Entity\QuestionCategory
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\QuestionCategory")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="question_category_id", referencedColumnName="id")
* })
*/
private $questionCategory;
public function __construct()
{
$this->questionCategory = new QuestionCategory();
}
//...
}
Form
class QuestionType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('questionCategory');
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Question'
));
}
}
Controller
class QuestionController extends Controller
{
//...
/**
* Creates a new Question entity.
* @Route("/new", name="question_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$question = new Question();
$form = $this->createForm('AppBundle\Form\QuestionType', $question);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
return $this->redirectToRoute('question_show', array('id' => $question->getId()));
}
return $this->render('question/new.html.twig', array(
'question' => $question,
'form' => $form->createView(),
));
}
//...
}
深度调试对我没有任何帮助 . 怎么解决?
4 回答
请注意,在表单类型中使用
'by_reference' => false,
且关系不是ManyToMany
时,也会引发此错误 .一个不幸的复制/粘贴让我陷入这种境地 .
根据GitHub项目中显示的代码,
Question
实体具有以下构造函数:创建
entity
表单字段时,它只能包含由doctrine管理的值,但不管理新的questionCategory
.通常,最好的解决方案是在构造函数中不填充此实体字段,但仅限于您严格需要它的那些地方 . 在构建表单时,Synfony会在提交并致电
$form->handleRequest()
后为您填写表格 .因此,在您的情况下,只需删除
Question
实体的构造函数 .之后,您还需要在
QuestionCategory
实体中实现__toString()
方法:此错误表示属性
questionCategory
是一种关系,不受 EntityManager 管理 . 要自动完成此操作,请在Doctrine Mapping中为questionCategory
属性添加 cascade-persist :Entity
这样,当您调用
$em->persist($question);
时,链接到Question
的QuestionCategory
也将自动保留 .在我的情况下,它只是因为我的错我使用
QueryManager
而不是EntityManager
在我的控制器中找到实体 .