Search code examples
symfonysymfony4

Accept null value when passing a non existing id parameter with @ParamConverter


Is it possible to return "null" value when passing an non existing "id" in my route ?

    /**
     * @Route("/admin/product/edit/{id}", name="product_edit", methods={"POST"})
     * @ParamConverter(
     *     name="id",
     *     class="App\Entity\Product",
     *     options={"mapping": {"id": "id"}}
     * )
     * @param Product $product
     * @param Request $request
     * @return JsonResponse
     */
    public function edit(Product $product = null, Request $request)
    {
        var_dump($product);die;
        $user = $this->getUser();
        if (!$product || $product->getUser() !== $user) {
            throw new HttpException(500, "Product does not exist");
        }

        return new JsonResponse([]);
    }

It always give me the error :

App\\Entity\\Product object not found by the @ParamConverter annotation.

I want to throw an HttpException when null value returned. I also tried to change "isOptionnal" parameter to "false" in ParamConverter annotation but it's not working.


Solution

  • Remove @ParamConverter and you can use "/admin/product/edit/{id?}" See this