微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – Symfony doctrine repository(findOneBy)结果不是对象

我尝试理解Doctrine方面的一些奇怪的行为,例如:

我有一个简单的表单,并在最终创建表单的请求中发送参数.

/**
 * displays a form to create a new Comment entity.
 *
 * @Route("/saveComment/",name="comment_new")
 * @Method("POST")
 * @Template()
 */
public function newAction(Request $request)
{
    $entity = new Comment();
    $form  = $this->createCreateForm($entity,$request);

    return array(
        'entity' => $entity,'form'   => $form->createView(),);
}

现在我得到我的参数并尝试在学说中找到对象.

/**
 * Creates a form to create a Comment entity.
 *
 * @param Comment $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Comment $entity,Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $commentForUserRequest = $request->request->get('commentForUser');
    $commentForUser = $em->getRepository('ApplicationSonataUserBundle:User')->findOneBy(array('username' => $commentForUserRequest ));

    $auctionRequest = $request->request->getInt('auction');

    $auction = $em->getRepository('AppBundle:Auction')->find(1);  // **ALL FINE**
    $auction = $em->getRepository('AppBundle:Auction')->find($auctionRequest); //**PROBLEM**

    $auction->addComment($entity);
    $entity->setAuction($auction);

    $form = $this->createForm(new CommentType(),$entity,array(
                'action' => $this->generateUrl('comment_create'),'method' => 'POST',));
}

当我给出一个数字而不是我的请求参数时,一切正常.
仅针对第二种情况发生以下错误消息:

Error: Call to a member function addComment() on a non-object

我不明白我做错了什么.

编辑:

Comment form

When I try sumbint

并且comment_create

/**
 * Creates a new Comment entity.
 *
 * @Route("/comment/",name="comment_create")
 * @Method("POST")
 * @Template("AppBundle:Comment:new.html.twig")
 */
public function createAction(Request $request)
{

    $entity = new Comment();

    $form = $this->createCreateForm($entity,$request);
    $form->handleRequest($request);

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

        return $this->redirect($this->generateUrl('comment_show',array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,);
}

解决方法

$request->request->getInt('auction');

该行将检查POST(NOT GET)请求变量’auction’.

您可以使用相同的操作来生成以及处理表单提交.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐