wall-e
wall-e

Reputation: 173

Drupal save global variables

I make a form in drupal to store data (for annonymous user) so when the form is validate i would like to save it to access it from all page but that does not work outside this function the variable is NULL

can you help me or have you another method to proceed ?

function myform_form_submit($form, &$form_state) {  

....
$GLOBALS ['info'] = $info;
}

Upvotes: 0

Views: 1016

Answers (1)

Devin Howard
Devin Howard

Reputation: 705

When a Drupal form is evaluated, it executes any code, including database changes. But then it redirects the user to a new page, which discards the PHP session, including $GLOBALS, among other things.

The more Drupally way is to use persistent variables, which are stored in the "variables" database table.

The variable_set function can be used here. So replace

### $GLOBALS['info'] = $info ### replace with:
variable_set('mymodule_info', $info);

and then when you access it, instead of using $GLOBALS, just use

$info = variable_get('mymodule_info', NULL);

You can use any name to specify the variable. I add NULL as a second parameter to variable_get in case the value isn't present in the database.

If the data is associated with a particular user, you might need to do something like

global $user;
variable_set('mymodule_info_uid_' . $user->uid, $info);

and then to retrieve the data use

global $user;
$info = variable_get('mymodule_info_uid_' . $user->uid, NULL);

EDIT: Ah, now I see you're dealing with anonymous users. In that case, PHP can identify anonymous users for you by giving a session id that can be used in the same way:

variable_set('mymodule_info_session_' . session_id(), $info);
variable_get('mymodule_info_session_' . session_id(), NULL);

This should be persistent for an anonymous user's browsing session.

The issue with this approach is that you'll need to come up with some way of clearing these out. You'll probably need to store a timestamp in the $info variable and have a cron job to delete expired entries from the variable table.

Upvotes: 2

Related Questions