getId在Symfony2中返回空字符串

时间:2014-03-30 16:56:09

标签: php symfony

我为我的问题对象制作了一个CRUD。我测试后发生错误。

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

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

" 参数" id"路线" question_show"必须匹配" [^ /] ++" (""给出)生成相应的网址。"

这是我的控制器代码:

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您的实体似乎未持久存储在数据库中。你能检查一下吗?

此外,您的代码中似乎是一个拼写错误" $ form = $ this-> createCreateForm($ 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());
}

答案 1 :(得分:0)

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