Skip to content

Instantly share code, notes, and snippets.

@ChrisTaylorDeveloper
Created August 26, 2018 16:04
Show Gist options
  • Save ChrisTaylorDeveloper/d0e7b2dfeaff1b0af989b8b915f16c0d to your computer and use it in GitHub Desktop.
Save ChrisTaylorDeveloper/d0e7b2dfeaff1b0af989b8b915f16c0d to your computer and use it in GitHub Desktop.
Symfony 4 @ParamConverter annotation Exception when using ajax
<?php
use App\Entity\Post;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/post")
*/
class PostController extends Controller
{
/**
* Normally, you'd expect a $id argument to show(). Instead, by creating
* a new argument ($post) and type-hinting it with the Post class (which
* is a Doctrine entity), the ParamConverter automatically queries for
* an object whose $id property matches the {id} value. It will also
* show a 404 page if no Post can be found.
*
* https://symfony.com/doc/current/best_practices/controllers.html
*
* @Route("/{id}", name="post_show")
*/
public function show(Post $post)
{
$deleteForm = $this->createDeleteForm($post);
return $this->render('admin/post/show.html.twig', [
'post' => $post,
'delete_form' => $deleteForm->createView(),
]);
}
/**
* However, when called via ajax (including the argument $post, type hinted
* with type Post) an Exception is thrown:
*
* Object not found by the @ParamConverter annotation Exception
*
* Therefore it is necessary to query for the post in the method body.
*
* @Route("/{id}/edit/{field}", name="post_edit_field", methods="POST")
*/
public function edit(Request $request, $id, $field /*, Post $post*/): Response
{
$post = $this->getDoctrine()
->getRepository(Post::class)
->findOneBy(['id' => $id]);
// based on value of $field
$post->setField('whatever');
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($post);
$entityManager->flush();
return $this->json(array('foo' => 'bar'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment