Hi People,
i encountered some peculiarities with the $user object in my code, am hoping to seek some enlightenment from the community for a clearer understanding.
A part of my code displays a form with its own validation and submission function:
myform_form()
myform_form_validate()
myform_form_submit()
within all these 3 functions, i have been saving and updating some data inside the $user object.
within myform_form_validate(), I've the following code in.
global $user;
if ( isset($user->count) )
$count = array('count' => ($user->count+1));
user_save($user, $count);
then in myform_form_submit(), I need to read up in these newly saved data again from the user object, as follow:
global $user;
$counter = $user->count;
I eventually have a problem of $counter not displaying the latest data which i have previously saved in $user->count. For instance, if I have incremented $user->count to '2' inside myform_form_validate(), this incrementing will not have been reflected inside myform_form_submit(). the $user->count will still give 1, before incrementing. Is there something im not understanding about global $user?
I did my own debugging, and replaced global $user in myform_form_submit() with the following
global $user;
$user = user_load(array('uid' => $user->uid));
$counter = $user->count;
then it works! ... $user->count is now 2. Why is this happening? It seems that global $user is loading old values, and not reading new values from the database.
Comments
$user is cached for the
$user is cached for the logged in user, on a page load of there is a copy of $user in cache it is not reloaded.
so everytime when a user
so everytime when a user logs in, a cache is made for $user of that particular user?
The global $user object
The global $user object doesn't change within a single page request, unless something changes it. This is its advantage. In your original code you are saving the the change to $count out to the db, but you aren't modifying the global user object so that change won't be reflected until the next user_load, which will not happen on the global $user object until the next page request. Change your original code to
I see what you mean ... that
I see what you mean ... that helps a lot. Thanks for your enlightenment!
By the way ... shouldn't it be
since $count contains an array?
Lastly, am i right to say that saving into the user db can only occur after user_save()?