【发布时间】:2016-02-17 07:55:37
【问题描述】:
- Generated Entities 来自现有数据库
- Generated CRUD控制器
但它不适用于异常消息:
必须管理传递给选择字段的实体。也许将它们保留在实体管理器中?
实体
/**
* 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();
}
//...
}
表格
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'
));
}
}
控制器
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(),
));
}
//...
}
深度调试对我没有任何帮助。如何解决?
【问题讨论】:
-
你在
Question实体类里做初始化吗? -
@OscarPérez,是的,只是创建 QuestionCategory 实体
-
那么这就是问题所在。您正在设置一个不受管理的
QuestionCategory。能否请您添加构造函数的代码? -
@OscarPérez,我已经创建了您可以探索的测试存储库:github.com/sectus/question.test.local
标签: php doctrine-orm symfony