Let's say I want to use $_SESSION['user_variable'] with a view as a filter value. I read that in Drupal 7 I could add such a value with custom PHP code. How should I do in Drupal 8? I didn't find an easy solution so far.

Would it be better to temporarily save a user's choice that is valid for the whole session in the database and tell the view to get the value from there?

  • Regarding how to, check out this and this
    – rjl
    Commented May 13, 2017 at 15:04

2 Answers 2


In case this might be helpful for other (beginners): Using the session object in a custom controller class with dependency injection.


class mymodule_Controller extends ControllerBase {

  * The user's private $tempStore object.
  * @var \Drupal\user\PrivateTempStoreFactory
  protected $tempStore;

  public function __construct(PrivateTempStoreFactory $temp_store_factory) {
    $this->tempStore = $temp_store_factory->get('mymodule_name');

 * {@inheritdoc}
 public static function create(ContainerInterface $container) {
   return new static(

 // Now get and set values in tempstore
 public function foo() {
  $foo = "xyz";
  // Set a session object "bar" and give it value $foo
  $this->tempStore->set('bar', $foo);

  // Get the 'bar' object from the session object.
  $value = $this->tempStore->get('bar');


There is a module for this - check this out: https://www.drupal.org/project/views_extras

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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