Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Stashing stuff in $_SESSION in your form's _submit handler in Drupal

Parent Feed: 

Today I was trying to figure out why in the name of all that good in the world why I couldn't use $_SESSION in my form's _submit handler.

As it turns out, I actually CAN put stuff into $_SESSION, it's just that when you want to pull something OUT of $_SESSION later, that's not where it is.

Instead, it's on the $user object in Drupal, in $user->session. After some studying, it seems this is a pipe-delimited and semi-colon delimited list of variable names and their serialized values.

Here's a function to pull stuff off of $user->session:

<?php
/**
* private function to return whether or not the person wants auto-play
*
* @return
*   either "yes" or "no" or "" (empty string)
*   yes - if the person has set their session var to autoplay
*   no - if they have set their session var to NOT autoplay
*   (empty string) - if they have not set their session var
*/
function _get_autoplay_from_session() {
 
$swftools_user_autoplay = '';
  global
$user;
 
 
$the_session = $user->session;
 
$the_session = explode('|', $the_session);
 
$swftools_user_autoplay = '';
  for (
$i = 0; $i < count($the_session); $i+=2) {
    if (
$the_session[$i] == 'swftools_user_autoplay') {
     
$swftools_user_autoplay = unserialize($the_session[++$i]);
      break;
    }
  }
 
  return
$swftools_user_autoplay;
}
?>

You'll notice that this pulls out a particular variable, but it can be easily modified and/or genericized to have you pass in the variable you're looking for.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web