Why I can't access global variable in my observer?
-
12-12-2019 - |
Question
I have a custom module. In its controller I set a global variable as shown below
public function someAction()
{
if (<some_condition_met>) {
$id = 12;
$item = Mage::getModel('mymodel/entity')->load($id);
Mage::register('my_entity', $item); //registering global variable
$this->_redirect('customer/account/login');
return;
}
}
Now I am observing on an event controller_action_postdispatch_customer_account_loginPost
. I need to validate my global variable there. So in my observer I tried this.
public function myObserver()
{
if (<some_condition_met>) {
$item = Mage::registry('my_entity');
var_dump($item);
die();
}
}
But it outputS
NULL
Why I can't get a global variable in this observer ?
I am 100% sure that, my controller successfully registers that value. I try to pass a static value. It also doesn't work.
Side note: when we try to get a global variable that set by a controller inside a block, it will surely return data. Here I assume i am not getting an output because, I am trying to get the global variable, during another controller action takes place. I am not sure about this point. However it seems like that.
Solution
The registry is only valid for one request. If you do a $this->_redirect()
, a new request begins, so that the registry is reset. You have to use cookies if you want to store information across multiple requests.
Another possibility is to just forward to another controller, but this may not be what you want to achieve.