Get URL parameters inside custom module
Asked Answered
P

8

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?

Peddada answered 7/6, 2016 at 9:26 Comment(0)
A
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');
Alice answered 8/6, 2016 at 2:26 Comment(0)
D
20

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();
Democratic answered 6/1, 2017 at 10:24 Comment(0)
C
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
)
Clichy answered 28/7, 2016 at 5:50 Comment(2)
drupal.org/node/2274705 says $path = \Drupal::service('path.current')->getPath();. But I don't see much of a difference actually.Instead
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.Myiasis
R
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');
Recursion answered 12/10, 2018 at 12:17 Comment(0)
P
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.

Parenteral answered 8/6, 2016 at 11:50 Comment(0)
J
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');
Jaffna answered 12/10, 2018 at 13:20 Comment(0)
N
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.

Nelsen answered 27/11, 2019 at 12:3 Comment(0)
H
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.
      }
    }
    ?>
    
Heth answered 15/9, 2017 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.