0
votes

I've annotated a Symfony3 controller method with a route that should take an optional parameter in the last position. If I attempt to generate the route without the last parameter, I either get a route that looks like what I want but doesn't work (fos-js-routing) or I fail to generate a route (twig). I'm hoping there's just a typo in my @Route annotation, but I can't see it. Here's the code.

The route does work if both parameters are supplied.

controller method:

    /**
     * @Route("/new/{format_id}/{room_id}", name="ci_item_new", requirements={"format_id"="\d+"}, options={"expose"=true})
     * @ParamConverter("format", options={"id" = "format_id"})
     * @ParamConverter("room", options={"id" = "room_id"})
     * @param Request $request
     * @param SupplyFormat
     * @param Room|null
     * @return array
     */
    public function newAction(Request $request, SupplyFormat $format, Room $room = null)
    {
        $item = new Item();
        $item->setFormat($format);
        if($room) $item->setRoom($room);
...
    }

fos:js-routing call:

Routing.generate('ci_item_new', {'format_id': data.format.id})

route generated:

https://example.com/web/app_dev.php/item/new/2205 <- observed == expected

error message when trying url

No route found for "GET /item/new/2205" (from "https://example.com/web/app_dev.php/supply/show/1)


twig routing call:

{{ path('ci_item_new', {'format_id': supply.formats[0]}) }}

no route generated

error message

An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("room_id") to generate a URL for route "ci_item_new".").


Any ideas why my @Route annotation doesn't work? I've read this and this and a pile of others without finding what I need.

1

1 Answers

0
votes

You should include the parameters in your function parameters as well, and use the same name and then you don't need the @ParamConverter. Also, you need to specify the defaults to avoid the optional paramters not being passed. So this would be your changes:

/**
 * @Route("/new/{format_id}/{room_id}",
 *      defaults={"format_id" = 0, "room_id" = 0},
 *      name="ci_item_new",
 *      requirements={"format_id"="\d+"})
 * @param Request $request
 * @param SupplyFormat
 * @param Room|null
 * @return array
 */
public function newAction($format_id, $room_id, Request $request)
{
    $item = new Item();
    $item->setFormat($format_id);
    if($room_id) $item->setRoom($room_id);
...
}

I think that should work for you, but I haven't tried it.

Obviously, you'll need to check the parameters if they are 0 and so on...