Reputation: 589
I'm trying to access the email address for a user that's signed in and I can do so successfully in all of my Controllers except for one.
Here is the error I'm getting
Notice (8): Undefined index: User [APP/View/Layouts/default.ctp, line 37]
And here is the corresponding line of code (remember, this works in all of my other controllers).
<center><font color="black"><td><?php echo $user['User']['email']; ?></td></text></center>
Here is the DemosController
<?php
// app/Controller/DemosController.php
class DemosController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add','logout');
$user = $this->Demo->read(null, $this->Auth->user('id')); //this throws the error
//$user = $this->Demo->User->read(null, $this->Auth->user('id')); //Fatal error: Call to a member function read() on a non-object in
$this->set('user', $user);
}
//display the knockout table
public function index($article = null) {
}
}
I do not need a table in the database for this Controller. It's simply to display a table for demo purposes. Can I just let it reference user?
class Demo extends AppModel {
public $name = 'User';
}
Why can I access this in all of my controllers except this one? Is the Model/table situation causing the error? If so, is there a way to disable the use of a table?
Upvotes: 1
Views: 6411
Reputation: 29007
You don't have to pass information of the currently logged-in user to the view via a 'viewVar'.
To access properties of the currently logged-in user outside of the controller, use the 'static' interface of the AuthComponent
Inside your views or layouts, output the information like this;
<p>The current users email is: <?php echo AuthComponent::user('email') ?></p>
<p>The current users id is: <?php echo AuthComponent::user('id') ?></p>
<p>And all properties of the user are:</p>
<pre><?php print_r(AuthComponent::user());?></pre>
See: Accessing the logged in user
You can remove these lines from your beforeFilter()
;
$user = $this->Demo->read(null, $this->Auth->user('id')); //this throws the error
//$user = $this->Demo->User->read(null, $this->Auth->user('id')); //Fatal error: Call to a member function read() on a non-object in
$this->set('user', $user);
Upvotes: 1
Reputation: 1975
You have a couple problems going here:
First, when not using a table, you set a model's $useTable
property to false.
Secondly, without a table, no database call will work (just plug in sample data to the table anyway, who would know if its a demo?)
It still bears mentioning that $this->Model->read()
is for updating records. Changing the line to the following will allow the set call to function properly:
$this->Demo->find('first', array(
'conditions' => array(
'Demo.field' => $this->Auth->user('id')
)));
Upvotes: 2