10

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?

leymannx
  • 5,138
  • 5
  • 45
  • 48
zied123456
  • 255
  • 1
  • 4
  • 17

8 Answers8

21

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');
anoopjohn
  • 518
  • 4
  • 18
Manish yadav
  • 339
  • 1
  • 2
18

I used to get the parameter value from URL (localhost/check/myform?mob=89886665)

$param = \Drupal::request()->query->all();

And applied in my select Query

 $query = \Drupal::database()->select('profile_register', 'p1');
 $query->fields('p1');
 $query->condition('p1.mobileno', $edituseprof);
 $query->condition('publishstatus', 'no');
 $result = $query->execute()->fetchAll();

But on multiple parameter value, i am now successful(Ex: http://10.163.14.41/multisite/check/myform?mob=89886665&id=1)

 $query = \Drupal::database()->select('profile_register', 'p1');
 $query->fields('p1');
 $query->condition('p1.mobileno', $edituseprof['mob']);
 $query->condition('p1.ids', $edituseprof['id']);
 $query->condition('publishstatus', 'no');
 $result = $query->execute()->fetchAll();
B.lakshman
  • 401
  • 1
  • 6
  • 19
7

arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
print_r($arg); exit(); 

The output would be parameters in url except basepath or (baseurl),

Array
(
   [0] => 
   [1] => node
   [2] => add
)
  • 1
    https://www.drupal.org/node/2274705 says `$path = \Drupal::service('path.current')->getPath();`. But I don't see much of a difference actually. – leymannx Aug 09 '18 at 10:24
  • Given that we are able to get named parameters values from request match, we shouldn't use arg and explode. The problem is that we will run into a lot of difficulty if we have to change URL structures later and insert additional path components. – anoopjohn Apr 21 '22 at 18:54
6

To get query parameter form the url, you can us the following. If you have the url for example,

domainname.com/page?uid=123&num=452

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

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

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

$num = \Drupal::request()->query->get('num');
Tanvir Ahmad
  • 273
  • 1
  • 4
  • 9
5
$route_match = \Drupal::service('current_route_match');
$abc = $route_match->getParameter('node'); //node is refrence to what you have written in you routing file i.e: 

in something.routing.yml
entity.node.somepath:
  path: '/some/{node}/path'

I have used {node} as arg(1). And I can access it by using *->getParameter('node');

Hope this will work.

Monal Soft
  • 320
  • 1
  • 2
  • 5
4

If your url is like this below example

http://localhost/drupal/node/6666

Then you have to get the full url path by

$current_path = \Drupal::request()->getPathInfo();

then explode the path to get the arguments array.

$path_args = explode('/', $current_path);

Another example if value passed by a key in url like below where id contains the value

http://localhost/drupal?id=123

You can get the id by given drupal request

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

Here's the example of accessing URL parameters and passing them to a TWIG template, I am considering you have already created your module and required files and suppose "/test?fn=admin" is your URL

  1. In Your .module file implement hook_theme and define variables and template name (Make sure you replace "_" with "-" when creating the template file)

     function my_module_theme () {   
             return [
              'your_template_name' => [               
                 'variables' => [
                     'first_name'    => NULL,
                  ],   
             ]; 
           }
    

Now create your controller and put below code in it.

 namespace Drupal\my_module\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Symfony\Component\HttpFoundation\Request;


 class MyModule extends ControllerBase {

   public function content(Request $request) {

     return [
       '#theme' => 'my_template',
       '#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
     ];
   }

 }

Now in your TWIG file which should be "my-template.html.twig" you can access this parameter as,

 <h3>First Name: {{ first_name }}</h3>

And its done. Hope this helps.

Umesh Patil
  • 4,668
  • 32
  • 24
0

The Drupal docs are great on this: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes

  1. define your path variable in yaml

    example.name:
      path: '/example/{name}'
      ...
    
  2. Add the variable in your method and use it

    <?php
    class ExampleController {  
      // ...
      public function content($name) {
        // Name is a string value.
        // Do something with $name.
      }
    }
    ?>