Joseph Woodward
Joseph Woodward

Reputation: 9281

Can't retrieve get parameters using Request class

I have a simple blog bundle with the following route:

blog_post:
    pattern:  /blog/{year}/{month}/{filename}/
    defaults: { _controller: ProjectBlogBundle:Post:index }
    requirements:
        year: "[0-9]{4}"
        month: "[0-9]{2}"
        filename: "([^/.]+)"

which matches the url of symfony.local/blog/2012/04/hello-world/ without a problem. However for some reason I am unable to access the query parameters using the Request class as below:

use Symfony\Component\HttpFoundation\Request;

class PostController extends Controller
{
    /**
     * @Template()
     */
    public function indexAction(Request $request)
    {


    print_r($request->query->keys()); // outputs blank array
    print_r($request->request->keys()); // outputs blank array

    echo $request->get('filename'); // outputs hello-world

    ....

   }

Can anyone explain why I'm unable to access the query parameters using $request->query->get('filename');?

Thank you in advance.

Upvotes: 3

Views: 3941

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

Because $request->query only contains parameters that are passed as query strings (GET parameters only) not those defined as route parameters (which are attributes parsed from the PATH_INFO)

So, you can use both,

$request->attributes->get('parameterName');
$request->get('parameterName');

to access url parameters.

In fact, when using $request->get('XXXX'), it checks all the parameters bags ($request->query, $request->request and $request->attributes) until it founds one that fit the given name.

Upvotes: 7

Related Questions