Search code examples
phpsymfonyparameterstwigsql-delete

Symfony 5 Delete methods, Unable to guess how to get a Doctrine instance from the request information for parameter


I wanted to put in my controller a second delete button to delete comments but I got lots of error messages like the one from ParamConverter because it did not recognize the class.

So in my controller I have a ParamConverter like this:

/**
     * @Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
     * @ParamConverter("comment", class="App:Comment", options={"id": "id"})
     */
    public function deleteComment(Request $request, BlogPost $blogPost, Comment $comment, $comment_id): Response
    {
        if ($this->isCsrfTokenValid('delete' . $comment->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($comment);
            $entityManager->flush();
            return $this->redirectToRoute('/');
        }


        return $this->render('comments/_delete_form.html.twig', [
            'comment' => $comment
        ]);
    }

In my twig, I added this:

<form method="post" action="{{ path('comment_delete', {'comment_id': comment.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
    <input type="hidden" name="_method" value="DELETE">
    <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ comment.id) }}">
    <button class="btn delete">Delete</button>
</form>

But it creates an error message:

"Unable to guess how to get a Doctrine instance from the request information for parameter" comment ".


Solution

  • Usually, Symfony will try to convert the route parameters to entities automatically if you typehint them in the function signature. For example, since you don't use the BlogPost entity, you could just write:

    /**
     * @Route("/delete/{id}", name="comment_delete", methods={"DELETE"})
     */
    public function deleteComment(Comment $comment): Response
    

    You should change the parameter name in your twig function too, of course.

    If you want to be more explicit and keep the parameter name as is, for clarity, you can write:

    /**
     * @Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
     * @ParamConverter("comment", options={"id" = "comment_id"})
     */
    

    In order to map the route argument to the column name.

    The error you are receiving is because you wrote options={"id": "id"} telling the converter to look up the entity by using the id parameter in the url, and of course there's no id parameter.