Php getId返回Symfony2中的空字符串
我已经为我的问题对象制作了一个积垢。在我测试它时发生了一个错误 getId()似乎返回了某种类型的空字符串 自动生成的CRUD的默认行为是在成功创建实体后将用户重定向到视图页面。但在本例中,它返回一个错误 路由“question_show”的参数“id”必须匹配“[^/]++”(“给定”)才能生成相应的URL。” 这是我的控制器代码:Php getId返回Symfony2中的空字符串,php,symfony,Php,Symfony,我已经为我的问题对象制作了一个积垢。在我测试它时发生了一个错误 getId()似乎返回了某种类型的空字符串 自动生成的CRUD的默认行为是在成功创建实体后将用户重定向到视图页面。但在本例中,它返回一个错误 路由“question_show”的参数“id”必须匹配“[^/]++”(“给定”)才能生成相应的URL。” 这是我的控制器代码: /** * Creates a new Question entity. * * @Route("/ask", name="question_create"
/**
* Creates a new Question entity.
*
* @Route("/ask", name="question_create")
* @Method("POST")
* @Template("VerySoftAskMeBundle:Question:ask.html.twig")
*/
public function createAction(Request $request) {
$entity = new Question();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('question_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
以下是查看操作:
/**
* Finds and displays a Question entity.
*
* @Route("/{id}", name="question_show")
* @Method("GET")
* @Template()
*/
public function showAction($id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('VerySoftAskMeBundle:Question')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Question entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to create a Question entity.
*
* @param Question $entity The entity
*
* @return Form The form
*/
private function createCreateForm(Question $entity) {
$form = $this->createForm(new QuestionType(), $entity, array(
'action' => $this->generateUrl('question_create'),
'method' => 'POST',
'em' => $this->getDoctrine()->getEntityManager()
));
$form->add('submit', 'submit', array('label' => 'Ask'));
return $form;
}
如何修复此问题?您的实体似乎没有持久化到数据库中。你能检查一下吗 此外,您编写的代码“$form=$this->createForm($entity);”而不是$this->createForm”,这似乎是一个输入错误 否则,我使用了下面的代码(与您的代码类似),没有问题
/**
* @Route("/new", name="item_new")
* @Template()
*
* @return array
*/
public function newAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$item = new Item();
$form = $this->createForm(new ItemType(), $item, array(
'action' => $this->generateUrl('item_new'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($item);
$em->flush();
return $this->redirect($this->generateUrl('item_list'));
}
return array('form' => $form->createView());
}
修好了。我继承了一个名为
Post
的类,它有一个$id
变量。事实证明,我忘记删除我的问题
类中的$id
变量,这就是为什么Symfony对返回哪个id感到困惑的原因。您的对象插入到DB中了吗?对象被插入了,但每次我重定向到查看页面时都会发生此错误。这不是打字错误。我真的有那种方法。