簡體   English   中英

使用get方法將路由URL格式傳遞給symfony2形式

[英]Passing route url format to symfony2 form with get method

不確定我是否正確編寫了主題,但無論如何。

由於您可以使用不同的參數創建特定的路由,例如:

_search:
    pattern: /page/{category}/{keyword}
    defaults: { _controller: Bundle:Default:page, category: 9, keyword: null }

從帶有GET方法的表單到該路由特定的URL格式有什么辦法嗎?

目前,網址類似於/ page?category = 2?keyword = some + keyword

因此,您可能不會注意到路由格式。

我需要怎么做才能使其通過這種特定格式工作? 我真的不知道如何重寫頁面URL以匹配特定URL的路由設置。 甚至在純PHP上也偶然發現了...

提前致謝。

這是帶有GET方法的HTML表單的默認行為。 您將需要自己構建該URL。

后端方式

  • 缺點:它向服務器發出兩個請求,而不是一個
  • 優點:由於URL是使用路由服務構建的,因此更易於維護

您的路由文件

_search:
    pattern: /page/{category}/{keyword}
    defaults: { _controller: Bundle:Default:page, category: 9, keyword: null }

_search_endpoint:
    pattern: /page
    defaults: { _controller: Bundle:Default:redirect }

您的控制器

public function redirectAction()
{
    $category = $this->get('request')->query->get('category');
    $keyword = $this->get('request')->query->get('keyword');

    // You probably want to add some extra check here and there
    // do avoid any kind of side effects or bugs.

    $url = $this->generateUrl('_search', array(
        'category' => $category,
        'keyword'  => $keyword,
    ));

    return $this->redirect($url);
}

前端方式

使用Javascript,您可以自己構建URL,然后重定向用戶。

注意:您將需要獲取自己的查詢字符串getter,您可以在此處找到Stackoverflow線程 ,下面我將在jQuery對象上使用getQueryString

(function (window, $) {
    $('#theFormId').submit(function (event) {
        var category, keyword;

        event.preventDefault();

        // You will want to put some tests here to make
        // sure the code behaves the way you are expecting

        category = $.getQueryString('category');
        keyword = $.getQueryString('keyword');

        window.location.href = '/page/' + category + '/' + keyword;
    }):
})(window, jQuery);

您可以添加第二條路線,該路線僅與/ page相匹配

然后在控制器中可以獲取默認值。 並將它們與任何通過的合並。

看看我為一些代碼示例回答的類似問題。

KendoUI Grid參數發送到symfony2應用

我也遇到了這個問題,因此設法用一個稍微不同的解決方案解決了這個問題。

您也可以像@Thomas Potaire建議的那樣重新路由,但是在同一控制器中,以以下命令開頭:

/**
 * @Route("/myroute/{myVar}", name="my_route")
 */
public function myAction(Request $request, $myVar = null)
{
    if ($request->query->get('myVar') !== null) {
        return $this->redirectToRoute('my_route', array(
            'myVar' => str_replace(' ','+',$request->query->get('myVar')) // I needed this modification here
        ));
    }
    // your code...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM