Store user state variables in Joomla 2.5/3.0

WebTechRiser.com > Joomla 3.0 > Store user state variables in Joomla 2.5/3.0

We can use JApplication class’s setUserState method or JSession class’s Registry property to store user state variables and retrieve these variables later for further processing.

Example:

$app = JFactory::getApplication();
$app->setUserState( 'myvar', $myvarvalue );
$app->setUserState( 'com_yourcomponent.data', $yourvalue ); 

To retrieve this value, use the following code:

$app = JFactory::getApplication();
$variable = $app->getUserStateFromRequest( "com_yourcomponent.data" );

We can also store and retrieve variables in session using JFactory/getSession.

Example:

$session = JFactory::getSession();
$session->set('myvar', $myvarvalue);

It’s not a big difference and you can use whatever feels right in our context. Both methods will store the specified state in the session. The JApplication/setUserState will in fact internally use JSession/set to store the state. What JApplication/setUserState does differently is that it will store every key-value pair in a JRegistry. So it is equal to:

$session = JFactory::getSession();
$registry = $session->get('registry');
$registry->set('myvar', $myvarvalue);

So, what’s the point of using a JRegistry? It’s pretty much the functionally provided JRegistryFormat. You can use it to both parse and format the state:

$session = JFactory::getSession();
$registry = $session->get('registry');
$json = $registry->toString('JSON');
$xml = $registry->toString('XML');

It’s also worth pointing out that using JApplication/setUserState your state will end up in the “default” namespace:

$app = JFactory::getApplication();
$app->setUserState( 'myvar', $myvarvalue );
// $_SESSION['default']['registry']->set('myvar', $myvarvalue)

Source: stackoverflow.com

Has this article come helpful to you?

There are some more articles in my blog, you may feel interested to read.

If you are looking to get any property of the active menu item class in Joomla! 3, this article may assist you and give you a working example.

Also read:  How to save component parameters to the database programmatically
Category Joomla 3.0

Leave Your Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.