Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46208

ParamConverter optional but valid

I'm trying to use a ParamConverter for an optional parameter

/**
 * @Route("/item", name="item_new")
 * @Route("/item/{id}", name="item")
 * @ParamConverter("item", class="AppBundle:Item")
 */
public function stepStockReceptionAction(Item $item = null)
{
    return new Response($item ? $item->getName() : 'New item');
}

My $item is now optional but if I give an invalid item id, it is simply considered null

GET /item/42 # <-- Non existant item

Gives

New item

How can I have the default 404 error if the item does not exist ?

Upvotes: 2

Views: 2132

Answers (1)

Denis Alimov
Denis Alimov

Reputation: 2901

as said in documentation

Several things happen under the hood:

The converter tries to get a SensioBlogBundle:Post object from the request attributes (request attributes comes from route placeholders -- here id);

If no Post object is found, a 404 Response is generated;

So no matter how you define Route and ParamConverter it will take id from request and try to find Item with this id. So you have 2 choices

  1. split into two methods, one for create, one to other work with existing Item
  2. use something like:

/**
 * @Route("/item/{id}", defaults={"id"=null}, name="work_with_item")
 */
public function stepStockReceptionAction(Request $request)
{
    $item = $this->getDoctrine()->getRepository('AppBundle:Project')->find($request->query->get('id')); 

    return new Response($item ?  $item->getName() : 'New item');
}    

Upvotes: 3

Related Questions