IkyryguJava
IkyryguJava

Reputation: 83

Symfony doctrine repository (findOneBy) result is not object

I try understand some weird behavior on the Doctrine side, for example:

I have a simple form and send parameters in a request at the end create form.

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

Now I get my parameters and try to find the object in 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',
    ));
}

When I give one number instead of my request parameter, everything works fine. The following error message only occurs for the second case:

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

I don't understand what I'm doing wrong.

Edit:

Comment form

When I try sumbint

And 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(),
    );
}

Upvotes: 4

Views: 2241

Answers (1)

sonam
sonam

Reputation: 3770

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

This line will check the POST (NOT GET) request variable 'auction'.

You could use same action for generating as well as handling form submit.

Upvotes: 1

Related Questions