logo

Get URL parameters/argument in custom module Drupal 8

07
July

Get URL parameters/argument in custom module Drupal 8
By: Anonymous | Published On: Wed, 07/07/2021 - 14:44

If you created URL with parameters in custom module as given example

http://localhost/drup/member/179

In example you need to access the value 179 in your code then follow these step

Use this line at top

Use \Drupal\Core\Routing;

You can use this code so its return all parameters but its return as object so again you need to load that object

You can use that code with named parameters as follows

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

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

For example you have created url as follow

mymodule.customprofile:
  path: '/member/{membernid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\mymoduleController::memberDetail'
  requirements:
    _permission: 'access content'

Then you can use the code as follow

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

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

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

For example if you have URL as following format

http://localhost/drup/page?uid=21&membernid=123

To get "uid" from the url, use..

$uid = \Drupal::request()->query->get('uid');

To get "num" from the url, use..

$membernid = \Drupal::request()->query->get('membernid');

Need Help ?