Symfony Doctrine 仓库 (findOneBy) 返回的结果不是对象。

4

我尝试理解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(),
    );
}

现在我已经获得了我的参数并尝试在Doctrine中查找对象。
/**
 * 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',
    ));
}

当我使用一个数字代替我的请求参数时,一切正常。以下错误消息仅适用于第二种情况:
“错误:在非对象上调用成员函数addComment()”
我不明白我做错了什么。
编辑:

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,
        'form'   => $form->createView(),
    );
}

$request->request->getInt('auction') 返回了什么? - Wojtek Dmyszewicz
@WojtekDmyszewicz 当我尝试点击发送按钮时出现问题。我添加了图片和更多细节。你能再检查一下吗? - IkyryguJava
@Bart 为什么不使用(int) $request->request->get('auction') 呢?你总是可以使用 $form->getData(); 来获取表单数据。 - Gavindra Kalikapersaud
Doctrine返回一个对象或者null,如果没有找到任何内容。所以我99%确定你的请求数据或提取数据的方式存在问题。尝试调试代码,查看变量的值等。 - Stepashka
调试 $auctionRequest,在这行代码 $auctionRequest = $request->request->getInt('auction'); 之后查看它的值。 - Oras
1个回答

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

这行代码将检查POST请求变量'auction',而不是GET请求。

您可以使用同一个操作来生成和处理表单提交。


谢谢,我建立了表单并发送了POST请求。运行得很好! - IkyryguJava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接