4

In drupal 8 $_GET not work . When I use \Drupal::request()->query->get('id') in my module ,it just work for first time . For example I create this code :

<?php

namespace Drupal\newday\Controller;

use Drupal\Core\Controller\ControllerBase;

class NewdayController extends ControllerBase {

    public function new() {

$day= [
    "#markup" => \Drupal::request()->query->get('id'),
];

        return $day;
    }
}

For first time ( id=1 ) it's work but for seconde time ( id=2 ) it's not work and still shows id=1

1
8

The request is being cached, you need to tell the system to vary by the query arg:

$day = [
    '#markup' => \Drupal::request()->query->get('id'),
    '#cache' => [
        'contexts' => ['url.query_args:id'],
    ],
];

You need to rebuild cache after altering the render array to see the effects.

If you're not familiar with it already, Cacheability of render arrays is worth a read.

4
  • Tanks . And when I want use with a string how do I that . For example : $id = \Drupal::request()->query->get('id') ?? – RobinSon Mar 22 '17 at 0:09
  • Exactly right. I assume it's Symfony that empties out $_GET and $_POST (probably $_REQUEST too), it's common for frameworks to do that – Clive Mar 22 '17 at 0:11
  • I do that but not work . I want use $id in: unset($_SESSION['test'][$id]); – RobinSon Mar 22 '17 at 0:13
  • 1
    I'm not sure what you mean, if you have id=foo in the URL, \Drupal::request()->query->get('id') will return foo. Otherwise you wouldn't see it printed to the page after all – Clive Mar 22 '17 at 0:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.