简体   繁体   中英

Accessing database info in header - cakePHP

I have a header (saved in View/Elements/header.ctp ) in my application that is fixed. The only thing that changes is the greeting to the user. It loads "Hi, Pete" or "Hi, Dave" etc. depending on who is logged in.

This greeting is in the header because it shows on every page.

What I want to know is, is it possible for me to get the name of the user from the database?

This is my database setup

The user's name is stored in a table called HrEmployees . The user's login details are stored in Users . Users has a field, employee_id , that is linked to the id of the employee in HrEmployees . So I need to take the id of the user and retrieve his name.

Question

Is this possible to do in the header? And if so, how would I do it? If there is any other info needed, let me know and I will post it.

Yes, it's possible. It depends on the specifics of your Auth setup, but basically, you first have to make sure that Cake's Auth componenet gets the linked HrEmployees record for a logged in User, and then just set the logged in users name in a view variable in the beforeFilter method of your AppController, so it's available in all your views.

The first part, making sure Auth includes the linked HrEmployee might look something like this:

$this->Auth->authenticate = array(
    'Form' => array(
        'userModel' => 'User',
        'contain' => array(
            'HrEmployee'=>array(
                'fields' => array( 'id', 'name' )
            )
        )
    )
);

More info about Authentication here: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

And the next part, setting your view variable, should be done in the beforeFilter() method of AppController.php, and might look something like this:

$this->set('loggedInUsersName', $this->Auth->user('HrEmployee.name'));

Then, you can just refer to $loggedInUsersName in any of your view files, and it should contain the right value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM