使用 get 方法将路由 url 格式传递给 symfony2 表单 [英] Passing route url format to symfony2 form with get method

查看:19
本文介绍了使用 get 方法将路由 url 格式传递给 symfony2 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定我是否正确地写了主题,但无论如何.

Not sure if I properly wrote the subject but anyway.

因为您可以创建具有不同参数的特定路由,例如:

Since you can create specific routes with different parameters for eg:

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

有没有办法从带有 GET 方法的表单获得该路由特定的 url 格式?

is there any way from a form with GET method to get to that route specific url format?

目前的网址就像/page?category=2?keyword=some+keyword

At the moment the url is like /page?category=2?keyword=some+keyword

因此不会传递到您可能注意到的路由格式.

As such is not passing to the route format as you may noticed.

我需要做什么才能让它通过这种特定格式工作?我真的不知道如何重写页面 url 以匹配特定 url 的路由设置.即使在普通的 php 中也偶然发现了这个......

What do I need to do to get it working through this specific format? I really have no idea how to rewrite the page url to match the route settings for the specific url. Even in plain php was stumbled on this ...

提前致谢.

推荐答案

这是带有 GET 方法的 HTML 表单的默认行为.您需要自己构建该 URL.

It's the default behavior of HTML forms with GET method. You will need to build that URL yourself.

  • 缺点:它向服务器发出两个请求而不是一个
  • 优点:更易于维护,因为 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,然后重定向用户.

Frontend way

Using Javascript, you can build the URL yourself and redirect the user afterwards.

  • 缺点:您无权访问路由服务(尽管您可以使用 FOSJsRoutingBundle 包)
  • 优点:您可以节省一个请求

注意:您需要获得自己的查询字符串 getter,您可以找到 此处为 Stackoverflow 线程,下面我将在 jQuery 对象上使用 getQueryString.

Note: You will need to get your own query string getter you can find a Stackoverflow thread here, below I'll use getQueryString on the jQuery object.

(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);

这篇关于使用 get 方法将路由 url 格式传递给 symfony2 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆