Home > Net >  Symfony Entity Param Converter not grabbing the correct route item
Symfony Entity Param Converter not grabbing the correct route item

Time:09-20

I have a route that needs to grab a category and then a subcategory with a route looking like this:

    #[Route('/{slug}/{subSlug}', name: 'subcategory')]
    #[Entity('category', expr: 'repository.findOneBySlug(slug)')]
    #[Entity('subcategory', expr: 'repository.findOneBySlug(subSlug)')]
    public function subcat(Category $cat, Subcategory $sub): Response

I try to go to /mtg/dmr and I get a 404 object not found by @ParamConverter. When I look in the profiler at the Doctrine logs, the system is looking in the right tables, but for both looking for mtg instead of first mtg and then dmr. Any ideas what's going on here?

CodePudding user response:

Example from the DOC :

#[Route('/blog/{date}/{slug}/comments/{comment_slug}')]
#[ParamConverter('post', options: ['mapping' => ['date' => 'date', 'slug' => 'slug']])]
#[ParamConverter('comment', options: ['mapping' => ['comment_slug' => 'slug']])]
public function showComment(Post $post, Comment $comment)
{
}

So, in your cas you must have :

#[Route('/{slug}/{subSlug}', name: 'subcategory')]
#[ParamConverter('cat', options: ['mapping' => ['slug' => 'slug']])]
#[ParamConverter('sub', options: ['mapping' => ['subSlug' => 'slug']])]
public function (Category $cat, Subcategory $sub): Response
{
}

CodePudding user response:

The parameter names you put on the method must be the same as you put on the paramConverter names,

Document:

https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html

The apply() method is called whenever a configuration is supported. Based on the request attributes, it should set an attribute named $configuration->getName(), which stores an object of class $configuration->getClass().

And following your code the objects are set on $request->attributes as * category != $cat (your parameter) , subCategory != $sub , you will have null instead of your objects

The names must be the same

#[Route('/{slug}/{subSlug}', name: 'subcategory')]
#[Entity('category', expr: 'repository.findOneBySlug(slug)')]
#[Entity('subcategory', expr: 'repository.findOneBySlug(subSlug)')]
public function subcat(Category $category, Subcategory $subcategory): Response
  • Related