2

I feel like it should be easier to find this stuff out. I'm trying to pass some data from a form submission to a controller, and do something based on that data. What is the most Drupal way to do this (i.e. without accessing the request object directly)?

The form in a custom module that extends FormBase has this method.

public function submitForm(array &$form, FormStateInterface $form_state) {
    $var_to_send = $form_state->getValue('val_to_get'); 
    $form_state->setRedirect('my.route', [ 'sent_var' => $var_to_send ]);
}

In this case, my.route is configured like this.

my.route:
  ...
  defaults:
    _controller: '\Drupal\custom_module\Controller\MyController::index'
    ...

I have the following method in \Drupal\custom_module\Controller\MyController.php.

public function index() {
    $params = \Drupal::request()->query->all();
    $this->myfunc($params['sent_var']);
}

This page says that what I'm doing is highly discouraged. So how should I access URL parameters in a controller?

1 Answer 1

3

In a route callback like a controller you can pull the request with a typed function parameter:

use Symfony\Component\HttpFoundation\Request;

  public function index(Request $request) {
    $query_parameters = $request->query->all();

  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.