1

I'd like a block plugin to display content dependent on a GET request. Inside my block plugin I have

class BlogPage extends BlockBase {
    public function build() {
        $query = \Drupal::entityQuery('node')
            ->condition('type', 'blog_post')
            ->sort('created', 'DESC')
            ->range(0, $range);
        return $query;
    }
}

I'd like to make $range retrieve info from a GET request. For example I'd like 127.0.0.1/page?range=5 to make $range = 5. I've tried

$range = Request::get('range');

But that does not work. Is there a way to return the values in a GET request from inside the block plugin?

4

You need to get the current request object first:

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

Or

$range = \Drupal::request()->get('range');
  • and it'll need a cache flush ;) drush cr or manually via admin/config/development/performance – izus Jul 15 '16 at 21:15
  • If you setup your cache tags right it shouldn't need to rebuild caches. A rebuild isn't going to be all that useful anyway since build() will not be called most of the time if the cache is still considered valid. – acrosman Jul 16 '16 at 16:30
  • Whenever I attempt this I get Fatal error: Class 'Drupal\mymodule\Plugin\Block\Drupal' not found in /Library/WebServer/Documents/aaep/web/modules/custom/mymodule/src/Plugin/Block/MyPlugin.php on line 46 – Matt Oct 14 '16 at 15:15
  • 2
    Turns out I needed a \ before the Drupal::request(); – Matt Oct 14 '16 at 15:18
  • I added that to the example since that's true in most contexts. – acrosman Oct 14 '16 at 15:37

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.