Shopware 6 - Tips, tricks and how to's

How to access POST and GET parameters in Shopware 6

There are many situations, when you might need to access the values, sent by POST or GET method to your Shopware store, for example when you send them from a javascript plugin. And although you can always use the default PHP way, Shopware 6 has some methods of its own.

Access parameters in a controller

In a controller, you can easily access the POST and GET parameters by passing the corresponding argument to the method, that should handle the request. In the following example, there is a method from a controller. We take all parameters, that are passed to it and return them in JSON format:

As you can see, the request is passed to your method in the form of an instance of class Symfony\Component\HttpFoundation\Request, along with the Context, that you will need for many other tasks inside your controller, for example to search in repositories etc.

The Request contains all the parameters from POST and GET methods in its property, aptly named request as well. You can retrieve them all with the all method or individually with the get method. You can also check for a specific parameter using the has method and set your own value to it, using the set method. All of them are in the example below:

You can limit the acceptable methods to just POST (data is sent from a form, for example) or GET (data is sent send as parameters from the URL), or allow both. In Shopware 6 (and Symfony framework, which it is based upon), this is done in the annotation just above the method declaration:

The Request object does not have to contain just your parameters. You can also use it to get the files, that were uploaded through the form, for example. You can then access them like this:

Access parameters in a subscriber (or elsewhere)

In Shopware 6, most of the time, you will use controllers to work with the data from a user-submitted form, but sometimes, you might need to access them from elsewhere in your code. This is more common for GET requests, that pass the parameters via the URL. Here is an example, how to get the parameter ‘test’ from inside a subscriber in the product detail page, when it was passed like this: www.some-store.xyz/some-product/?test=some-value.

In the end, it boils down to injecting the RequestStack and getting the current request from it. It contains all the parameters and you just need to use the get method to obtain their values. This works not just for subscribers, but in any class.