2014-03-30 29 views
0

我为我的问题对象做了一个CRUD。一旦我测试过,就会发生错误。getId在Symfony2中返回空字符串

似乎getId()返回某种空字符串。

自动生成的CRUD的默认行为是在成功创建实体后将用户重定向到视图页面。但在这种情况下,它返回一个错误

参数 ”ID“ 为路线 ”question_show“ 必须匹配 ”[^ /] ++“(” “给出),以产生一个对应的URL。

这里是我的控制器代码:

/** 
* 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; 
} 

我该如何解决这个问题?

+0

是你的对象插入到数据库? – ponciste

+0

插入对象,但每次我重定向到视图页面时都会发生此错误。 – schizoskmrkxx

回答

0

看起来你的实体并没有在数据库中持久化。你能检查一下吗?

而且,它似乎是在你的代码一个错字你写“$形式= $这个 - > createCreateForm($实体);”,而不是$这个 - >的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()); 
} 
+0

这不是一个错字。我真的有这种方法。 – schizoskmrkxx

0

修正了它。我继承了一个名为Post的类,它有一个$id变量。事实证明,我忘记删除我的Question类中的$id变量,这就是为什么Symfony会对要返回的id感到困惑的原因。