Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL parameters inside custom module

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?

like image 976
zied123456 Avatar asked Jun 07 '16 09:06

zied123456


2 Answers

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');
like image 129
Manish yadav Avatar answered Oct 10 '22 09:10

Manish yadav


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();
like image 40
B.lakshman Avatar answered Oct 10 '22 10:10

B.lakshman