Get URL parameters inside custom module

zied123456 picture zied123456 · Jun 7, 2016 · Viewed 37.2k times · Source

I've created a custom block like this:

class HelloBlock extends BlockBase implements BlockPluginInterface{

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
    $result = db_query('SELECT * FROM {test}');
    return array(
      '#theme' => 'world',
      '#test' => $result
    );
  }
}

And I now want to programmatically get some parameter from the URL.

For example:

If the URL is http://localhost/drup/hello/5569 I want to get hold of the value 5569 inside my module.

I have tried arg(1) and drupal_get_query_parameters() but I got this error messages:

Call to undefined function `Drupal\hello\Plugin\Block\arg()`

and

Call to undefined function `Drupal\hello\Plugin\Block\drupal_get_query_parameters()`

How can I get the parameters?

Answer

Manish yadav picture Manish yadav · Jun 8, 2016

Use \Drupal\Core\Routing;:

$parameters = \Drupal::routeMatch()->getParameters();

The named parameters are available as

$value = \Drupal::routeMatch()->getParameter('slug_name_from_route');

Where 'slug_name_from_router' comes from your routing.yml path property

path: '/your/path/{slug_name_from_route}'

If you want the raw parameter without any upcasting you can get

$value = \Drupal::routeMatch()->getRawParameter('slug_name_from_route');