You are here

protected function SessionExampleForm::setSessionValue in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/session_example/src/Form/SessionExampleForm.php \Drupal\session_example\Form\SessionExampleForm::setSessionValue()

Store a form value in the session.

Form values are always a string. This means an empty string is a valid value for when a user wants to remove a value from the session. We have to handle this special case for the session object.

Parameters

string $key: The key.

string $value: The value.

1 call to SessionExampleForm::setSessionValue()
SessionExampleForm::submitForm in session_example/src/Form/SessionExampleForm.php
Form submission handler.

File

session_example/src/Form/SessionExampleForm.php, line 136

Class

SessionExampleForm
Form to allow the user to store information in their session.

Namespace

Drupal\session_example\Form

Code

protected function setSessionValue($key, $value) {
  if (empty($value)) {

    // If the value is an empty string, remove the key from the session.
    $this->session
      ->remove($key);
  }
  else {
    $this->session
      ->set($key, $value);
  }
}