Reputation: 1179
In my view i am trying to display the current logged in users information and have figured i can do this by using
echo "Welcome back " .$this->Session->read('Auth.User.username'). "
This displays the username and i can use the same approach to display the other fields in that database row, however some of the other fields can update at anytime but does not update on the users page until they logout and login again.
Is this correct way to do it? or can this be done a better way and somehow put some code in the beforeFilter() in AppController to continue to update the variables on each page load?
Upvotes: 0
Views: 4884
Reputation: 4517
I prefer to get the real time data instead of the session data
var $uses = array('User');
function beforeFilter(){
$id = $this->Auth->user('id'); //Using the session's user id is fine because it doesn't change/update
$user_data = $this->User->findById($id);
$user_fname = $user_data['User']['fname'];
$this->set('fname', $user_fname);
}
//In your view
echo 'Welcome Back '. $fname . '!';
Upvotes: 0
Reputation: 41595
If the database is updated from outside CakePHP and without calling any controller action it seems the only solution for this is making a query on every loaded page to get the current value.
For this, you should use the beforeFilter
method on the AppController:
function beforeFilter(){
$user = $this->User->field('name', array('User.id' => $this->Session->read('Auth.User.id')));
$this->Session->write('Auth.User', $user);
}
Otherwise, you can make use of JavaScript and AJAX to get the data from time to time.
Upvotes: 1
Reputation: 29121
What if you just made an afterSave()
on the User model, and in it, set $this->Session->write('Auth.User') = $user;
This is non-tested, but seems like it should work - then your session would always be up to date on any changes.
Edit:
Per your comment, if the data is being pulled from a third-party source that you don't have access to, and you need to make sure it's updated on EVERY page load, then yes, the AppController's beforeFilter() is just fine.
If, however you only need it on certain pages, or certain elements, you can call the update then, or via a requestAction of an element.
Upvotes: 0