Symfony2 ORM实体插入DB

时间:2015-12-12 20:22:44

标签: symfony orm doctrine-orm crud

我有这个简单的实体:

<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="CommentTypes")
 */

class CommentTypes
{
        /**
        * @ORM\Column(type="integer")
        * @ORM\Id
        * @ORM\GeneratedValue(strategy="AUTO")
        */
        protected $id;

        /** @ORM\Column(type="string", length=100) */
        protected $name;
}
?>

生成CRUD并使用它创建新记录后,我收到此错误:

    Error: Call to a member function getId() on a non-object
500 Internal Server Error - FatalErrorException 

错误出现在这段代码中 - 在此行的src / AppBundle / Controller / CommentTypesController.php中 - “return $ this-&gt; redirectToRoute('admin_commenttypes_show',array('id'=&gt; $ commenttypes-&gt ;的getId()));“

 * Creates a new CommentTypes entity.
 *
 * @Route("/new", name="admin_commenttypes_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $commentType = new CommentTypes();
    $form = $this->createForm(new CommentTypesType(), $commentType);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($commentType);
        $em->flush();

        return $this->redirectToRoute('admin_commenttypes_show', array('id' => $commenttypes->getId()));
    }

    return $this->render('commenttypes/new.html.twig', array(
        'commentType' => $commentType,
        'form' => $form->createView(),
    ));
}

1 个答案:

答案 0 :(得分:1)

我认为你拼错了行$commentType变量:

return $this->redirectToRoute('admin_commenttypes_show', array('id' => $commenttypes->getId()));

应该是:

return $this->redirectToRoute('admin_commenttypes_show', array('id' => $commentType->getId()));