How we can pass multiple value in an session variable

$session = \Drupal::request()->getSession();
$session->set('session_anme', $variable_name ++);

if I add value 1 and 2 and 3

The value should ne added

Currently it get the last value only but i want all values that i passed in the session

function module_name_preprocess_commerce_order_receipt__purchase_order_gateway(&$variables){
  $variables['#cache']['contexts'][] = 'session';
  $session = \Drupal::request()->getSession();
  $print_session = $session->get('unit_price');
  foreach ($print_session as $print_session1) {
    $message = '<pre><code>' . print_r($print_session1, TRUE) . '</code></pre>';

but still get last value

New contributor
developer is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Welcome to Drupal Answers! Can you describe your use case / what you want to achieve?
    – berliner
    Jan 14 at 8:41

Use an array:

$session = \Drupal::request()->getSession();
$allowed_temp_files = $session->get('anonymous_allowed_file_ids', []);
$allowed_temp_files[$file->id()] = $file->id();
$session->set('anonymous_allowed_file_ids', $allowed_temp_files);

Example from /core/modules/file/file.module

  • Thanks ! print_r($session->get('anonymous_allowed_file_ids')); outpurL Array ( [0] => 300 ) Array ( [0] => 290 ) and I now I want to get the value both array in hool_preprocess_hook how I can get it in hool_preprocess_hook basically i want use it in twig file the values that i pass in array
    – developer
    Jan 14 at 8:31
  • You have to loop over the array producing HTML, either in the hook or in the twig file. Don't forget to add a cache context for the session: $variables['#cache']['contexts'][] = 'session';
    – 4k4
    Jan 14 at 9:01
  • I am using loop but still getting last record only, please the question I edit it
    – developer
    Jan 14 at 9:43

Your Answer

developer is a new contributor. Be nice, and check out our Code of Conduct.

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.