Skip to content

Commit 402390d

Browse files
joshi.rohit100paul-m
authored andcommitted
Issue #2502303 by Mile23, joshi.rohit100, Torenware, pp, znerol: Add a session example
1 parent 6e81c0c commit 402390d

File tree

9 files changed

+486
-0
lines changed

9 files changed

+486
-0
lines changed

examples.module

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ function examples_toolbar() {
5858
'pager_example' => 'pager_example.page',
5959
'phpunit_example' => 'phpunit_example_description',
6060
'plugin_type_example' => 'plugin_type_example.description',
61+
'session_example' => 'session_example.form',
6162
'simpletest_example' => 'simpletest_example_description',
6263
'tabledrag_example' => 'tabledrag_example.description',
6364
'stream_wrapper_example' => 'stream_wrapper_example.description',
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
name: 'Session example'
2+
type: module
3+
description: 'An example of how to use session in Drupal 8.'
4+
package: Example modules
5+
core: 8.x
6+
dependencies:
7+
- examples:examples
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Define the menu links for this module
2+
3+
session_example.form:
4+
title: 'Session Example'
5+
route_name: session_example.form
6+
description: 'Setting Form'
7+
weight: 10
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# The Edit and View tabs for the session example pages.
2+
session_example.form:
3+
route_name: session_example.form
4+
base_route: session_example.form
5+
title: Edit
6+
session_example.view:
7+
route_name: session_example.view
8+
base_route: session_example.form
9+
title: View
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
/**
4+
* @file
5+
* Session example module demonstrates manipulating user sessions.
6+
*/
7+
8+
/**
9+
* @defgroup session_example Example: Session
10+
* @ingroup examples
11+
* @{
12+
* Demonstrating how to manipulate sessions in Drupal 8.
13+
*
14+
* You can read the API documentation here:
15+
* https://api.drupal.org/api/drupal/core%21core.api.php/group/session/
16+
*
17+
* Drupal's session management is inherited from Symfony. We use the
18+
* Symfony\Component\HttpFoundation\Session\SessionInterface object which we can
19+
* get from the Request object.
20+
*
21+
* This object allows us to get and set values from the user session.
22+
*
23+
* We can use the session to store information per visitor.
24+
*
25+
* In this example, we will have the user fill out a form with some personal
26+
* information, and then be able to display that information on another page.
27+
*
28+
* To learn more, one could examine the Stream Wrapper Example. It uses the
29+
* session API to implement a session: file scheme.
30+
*
31+
* @see stream_wrapper_example
32+
* @see https://api.drupal.org/api/drupal/core%21core.api.php/group/session/
33+
*/
34+
35+
/**
36+
* @} End of "defgroup session_example".
37+
*/
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
session_example.form:
2+
path: '/examples/session_example'
3+
defaults:
4+
_form: '\Drupal\session_example\Form\SessionExampleForm'
5+
_title: 'Session Example'
6+
requirements:
7+
_permission: 'access content'
8+
session_example.view:
9+
path: '/examples/session_example/view'
10+
defaults:
11+
_controller: '\Drupal\session_example\Controller\SessionExampleController::showSession'
12+
_title: 'Session Example: Current Values'
13+
requirements:
14+
_permission: 'access content'
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
namespace Drupal\session_example\Controller;
4+
5+
use Drupal\Core\Controller\ControllerBase;
6+
use Symfony\Component\HttpFoundation\Request;
7+
8+
/**
9+
* Controller for a page to display the session information.
10+
*
11+
* @ingroup session_example
12+
*/
13+
class SessionExampleController extends ControllerBase {
14+
15+
/**
16+
* Display the example session information.
17+
*
18+
* By default, controller methods receive a Request object as a parameter, so
19+
* we can use one here.
20+
*
21+
* @param \Symfony\Component\HttpFoundation\Request $request
22+
* The request object.
23+
*
24+
* @return string
25+
* A renderable array containing the user information from the session.
26+
*/
27+
public function showSession(Request $request) {
28+
// Get the session from the request object.
29+
$session = $request->getSession();
30+
31+
// Make a table of the session information.
32+
$row = [];
33+
foreach (['name', 'email', 'quest', 'color'] as $item) {
34+
$key = "session_example.$item";
35+
// Get the session value, with a default of 'No name' etc. for each type
36+
// of information we have.
37+
$row[0][$item] = $session->get($key, $this->t('No @type', ['@type' => $item]));
38+
}
39+
40+
return [
41+
// Since this page will be cached, we have to manage the caching. We'll
42+
// use a cache tag and manage it within the session helper. We use the
43+
// session ID to guarantee a unique tag per session. The submission form
44+
// will manage invalidating this tag.
45+
'#cache' => [
46+
'tags' => ['session_example:' . $session->getId()],
47+
],
48+
'description' => [
49+
'#type' => 'item',
50+
'#title' => $this->t('Saved Session Keys'),
51+
'#markup' => $this->t('The example form lets you set some session keys. This page lists their current values.'),
52+
],
53+
'session_status' => [
54+
'#type' => 'table',
55+
'#header' => [
56+
$this->t('Name'),
57+
$this->t('Email'),
58+
$this->t('Quest'),
59+
$this->t('Color'),
60+
],
61+
'#rows' => $row,
62+
],
63+
];
64+
}
65+
66+
}
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
<?php
2+
3+
namespace Drupal\session_example\Form;
4+
5+
use Drupal\Core\Form\FormBase;
6+
use Drupal\Core\Form\FormStateInterface;
7+
use Drupal\Core\Link;
8+
use Symfony\Component\DependencyInjection\ContainerInterface;
9+
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
10+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
11+
12+
/**
13+
* Form to allow the user to store information in their session.
14+
*
15+
* In this object we'll inject the session service. In the submission form we
16+
* got the session from a Request object supplied by the routing system. Either
17+
* of these work, because they're the same object. But we use injection here
18+
* because the buildForm() method does not have an easy way to derive the
19+
* Request object or the session.
20+
*
21+
* @ingroup session_example
22+
*/
23+
class SessionExampleForm extends FormBase {
24+
25+
/**
26+
* The session object.
27+
*
28+
* We will use this to store information that the user submits, so that it
29+
* persists across requests.
30+
*
31+
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface
32+
*/
33+
protected $session;
34+
35+
/**
36+
* The cache tag invalidator service.
37+
*
38+
* @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
39+
*/
40+
protected $cache_tag_invalidator;
41+
42+
/**
43+
* Constructs a new SessionExampleForm object.
44+
*
45+
* @param \Symfony\Component\HttpFoundation\Session\SessionInterface
46+
* The session object.
47+
*/
48+
public function __construct(SessionInterface $session, CacheTagsInvalidatorInterface $invalidator) {
49+
$this->session = $session;
50+
$this->cache_tag_invalidator = $invalidator;
51+
}
52+
53+
/**
54+
* {@inheritdoc}
55+
*/
56+
public static function create(ContainerInterface $container) {
57+
return new static(
58+
$container->get('session'),
59+
$container->get('cache_tags.invalidator')
60+
);
61+
}
62+
63+
/**
64+
* {@inheritdoc}
65+
*/
66+
public function getFormId() {
67+
return 'session_example_form';
68+
}
69+
70+
/**
71+
* {@inheritdoc}
72+
*/
73+
public function buildForm(array $form, FormStateInterface $form_state) {
74+
$form['description'] = [
75+
'#type' => 'item',
76+
'#title' => $this->t('Session Data Form'),
77+
'#markup' => $this->t('In this example form, data that you enter into the form will be saved into your session data, which persists until you log out of Drupal.'),
78+
];
79+
$form['name'] = [
80+
'#type' => 'textfield',
81+
'#title' => $this->t('Name'),
82+
'#placeholder' => $this->t('Your name.'),
83+
'#default_value' => $this->session->get('session_example.name', ''),
84+
];
85+
$form['email'] = [
86+
'#type' => 'textfield',
87+
'#title' => $this->t('Email'),
88+
'#placeholder' => $this->t('Your email address.'),
89+
'#default_value' => $this->session->get('session_example.email', ''),
90+
];
91+
$form['quest'] = [
92+
'#type' => 'textfield',
93+
'#title' => $this->t('Quest'),
94+
'#placeholder' => $this->t('What is your quest?'),
95+
'#default_value' => $this->session->get('session_example.quest', ''),
96+
];
97+
$form['color'] = [
98+
'#type' => 'select',
99+
'#title' => $this->t('Favorite Color'),
100+
'#options' => [
101+
'' => $this->t('--'),
102+
'red' => $this->t('Red'),
103+
'blue' => $this->t('Blue'),
104+
'yellow' => $this->t('Yellow'),
105+
'argggh' => $this->t('Argggghhh!!'),
106+
],
107+
'#default_value' => $this->session->get('session_example.color', ''),
108+
'#description' => $this->t('What is your favorite color?'),
109+
];
110+
$form['save'] = [
111+
'#type' => 'submit',
112+
'#value' => $this->t('Save'),
113+
];
114+
$form['reset'] = [
115+
'#type' => 'submit',
116+
'#value' => $this->t('Clear Session'),
117+
'#submit' => ['::submitClearSession'],
118+
];
119+
return $form;
120+
}
121+
122+
/**
123+
* Store a form value in the session.
124+
*
125+
* Form values are always a string. This means an empty string is a valid
126+
* value for when a user wants to remove a value from the session. We have to
127+
* handle this special case for the session object.
128+
*
129+
* @param string $key
130+
* The key.
131+
* @param string $value
132+
* The value.
133+
*/
134+
protected function setSessionValue($key, $value) {
135+
if (empty($value)) {
136+
// If the value is an empty string, remove the key from the session.
137+
$this->session->remove($key);
138+
}
139+
else {
140+
$this->session->set($key, $value);
141+
}
142+
}
143+
144+
/**
145+
* {@inheritdoc}
146+
*/
147+
public function submitForm(array &$form, FormStateInterface $form_state) {
148+
// We get the submitted form information and store it in the session. We use
149+
// key names which include our module name in order to avoid namespace
150+
// collision.
151+
$this->setSessionValue('session_example.name', $form_state->getValue('name'));
152+
$this->setSessionValue('session_example.email', $form_state->getValue('email'));
153+
$this->setSessionValue('session_example.quest', $form_state->getValue('quest'));
154+
$this->setSessionValue('session_example.color', $form_state->getValue('color'));
155+
// Tell the user what happened here, and that they can look at another page
156+
// to see the result.
157+
$this->messenger()->addMessage($this->t('The session has been saved successfully. @link', [
158+
'@link' => Link::createFromRoute('Check here.', 'session_example.view')->toString()
159+
]));
160+
// Since we might have changed the session information, we will invalidate
161+
// the cache tag for this session.
162+
$this->invalidateCacheTag();
163+
}
164+
165+
/**
166+
* Remove all the session information.
167+
*/
168+
public function submitClearSession(array &$form, FormStateInterface $form_state) {
169+
$items = [
170+
'session_example.name',
171+
'session_example.email',
172+
'session_example.quest',
173+
'session_example.color',
174+
];
175+
foreach ($items as $item) {
176+
$this->session->remove($item);
177+
}
178+
$this->messenger()->addMessage($this->t('Session is cleared.'));
179+
// Since we might have changed the session information, we will invalidate
180+
// the cache tag for this session.
181+
$this->invalidateCacheTag();
182+
}
183+
184+
/**
185+
* Invalidate the cache tag for this session.
186+
*
187+
* The form will use this method to invalidate the cache tag when the user
188+
* updates their information in the submit handlers.
189+
*/
190+
protected function invalidateCacheTag() {
191+
$this->cache_tag_invalidator->invalidateTags(['session_example:' . $this->session->getId()]);
192+
}
193+
194+
}

0 commit comments

Comments
 (0)