2013-03-08 43 views
9

我試圖建立在Symfony2的部分航線以下模式:Symfony2的路由:兩個可選參數 - 至少一個需要

www.myaweseomesite.com/payment/customer/{customernumber}/{invoicenumber} 

兩個參數都是可選的 - 所以在下列情況下必須工作:

www.myaweseomesite.com/payment/customer/{customerNumber}/{invoiceNumber} 
www.myaweseomesite.com/payment/customer/{customerNumber} 
www.myaweseomesite.com/payment/customer/{invoiceNumber} 

我根據symfony2 doc設置了我的routing.yml。

payment_route: 
pattern: /payment/customer/{customerNumber}/{invoiceNumber} 
defaults: { _controller: PaymentBundle:Index:payment, customerNumber: null, invoiceNumber: null } 
requirements: 
    _method: GET 

目前爲止效果很好。問題是,如果兩個參數都缺失或爲空,則路線不應起作用。所以

www.myaweseomesite.com/payment/customer/ 

不應該工作。 Symfony2有沒有辦法做到這一點?

+0

params是怎麼樣的?他們有長度特異性還是數字?只是信件?字母和數字?因爲如果他們都是隻有數字的任何長度,這是不可能的,因爲你不知道哪個是哪個。 – 2013-03-08 20:02:33

+0

customerNumber是一個數字,invoiceNumber是一個字符串 – marty 2013-03-08 20:04:35

回答

16

您可以在兩條路線中定義它,以確保只有一個斜線。

payment_route_1: 
    pattern: /payment/customer/{customerNumber}/{invoiceNumber} 
    defaults: { _controller: PaymentBundle:Index:payment, invoiceNumber: null } 
    requirements: 
     customerNumber: \d+ 
     invoiceNumber: \w+ 
     _method: GET 

payment_route_2: 
    pattern: /payment/customer/{invoiceNumber} 
    defaults: { _controller: PaymentBundle:Index:payment, customerNumber: null } 
    requirements: 
     invoiceNumber: \w+ 
     _method: GET 

請注意,您可能必須根據您的確切需要更改定義參數的正則表達式。你可以look at this。複雜的正則表達式必須被"包圍。 (例myvar : "[A-Z]{2,20}"

+0

好的。看起來很奇怪,但它工作:)謝謝! – marty 2013-03-08 20:14:10

+0

@marty很高興我可以幫忙!爲了提供更多的信息,第一條路線與你的2個第一類型相匹配。第二種是第三種。 (oops我忘了從第一個路由中刪除'customerNumber:null',否則它會接受沒有任何參數的路由,我已經更新以反映這一點!) – 2013-03-08 20:15:40

4

爲了詳細說明@Hugo答案,請找到配置以下注釋:

/** 
* @Route("/public/edit_post/{post_slug}", name="edit_post") 
* @Route("/public/create_post/{root_category_slug}", name="create_post", requirements={"root_category_slug" = "feedback|forum|blog|"}) 
* @ParamConverter("rootCategory", class="AppBundle:Social\PostCategory", options={"mapping" : {"root_category_slug" = "slug"}}) 
* @ParamConverter("post", class="AppBundle:Social\Post", options={"mapping" : {"post_slug" = "slug"}}) 
* @Method({"PUT", "GET"}) 
* @param Request $request 
* @param PostCategory $rootCategory 
* @param Post $post 
* @return array|\Symfony\Component\HttpFoundation\RedirectResponse 
*/ 
public function editPostAction(Request $request, PostCategory $rootCategory = null, Post $post = null) 
{ Your Stuff } 
相關問題