duande8497 2016-05-26 08:40
浏览 43
已采纳

ParamConverter可选但有效

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 ?

  • 写回答

1条回答 默认 最新

  • dongmuyan5638 2016-05-26 15:19
    关注

    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');
    }    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址