I have the tables:
users
(model User
) - id, person_id, username, passwordpeople
(model Person
) - id, parent_id (foreign key of the same table), last_name, first_nameaddresses
(Address
) - id, person_id, street, cityAnd, models are :
class User extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'Person'
);
}
class Person extends AppModel {
public $belongsTo = array(
'Parent' => array(
'className' => 'Person',
'foreignKey' => 'parent_id',
),
);
public $hasMany = array(
'User',
'Address',
'Subordinate' => array(
'className' => 'Person',
'foreignKey' => 'parent_id',
),
);
}
class Address extends AppModel{
public $belongsTo = array(
'Person'
);
}
Views in View/Users/
folder:
register.ctp
login.ctp
logout.ctp
profile.ctp
After registration and login, I need to show the profile data. For that, I use the following function inUsersController
:-
public function profile() {
$this->set('userProfile', $this->Auth->User());
}
I have following in profile.ctp
:
<table>
<tr>
<th>Username </th>
<th>First Name </th>
<th>Last Name </th>
<th>street</th>
<th>house_no</th>
</tr>
<?php foreach ($userProfile as $profiledata){ ?>
<tr>
<td><?php echo $profiledata['username']; ?> </td>
<td><?php echo $profiledata['Person']['first_name']; ?> </td>
<td><?php echo $profiledata['Person']['last_name']; ?> </td>
<td><?php echo $profiledata['Person']['Address']['street']; ?> </td>
<td><?php echo $profiledata['Person']['Address']['house_no']; ?> </td>
</tr>
<?php } ?>
</table>
the auth component in AppController.php
public $components = array(
'DebugKit.Toolbar',
'Session',
'Flash',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authenticate' => array('Form' => array(
'contain' => array('Person'=>'Address'),
'passwordHasher' => 'Blowfish'))
)
);
it can retrieve data from users and people tables, but not from address table.
I am getting following error:
Notice (8): Undefined index: street [APP\View\Users\profile.ctp, line 32]
Could anyone tell me what is wrong here? Do I need to create another model for profile (Profile.php
) for showing profile data?
The function
$this->Auth->User()
does not return an array of models.
Instead, it returns something similar to:
Array
(
[id] => 1
[user_name] => john.doe
[Person] => Array
(
[id] => 1
[first_name] => John
[last_name] => Doe
)
[Address] => Array
(
[id] => 1
[street] => Piccadilly Street
[house_no] => 4
)
)
Therefore, you have to remove the foreach
loop, and access the data by doing the following:
<tr>
<td><?php echo $userProfile['user_name']; ?> </td>
<td><?php echo $userProfile['Person']['first_name']; ?> </td>
<td><?php echo $userProfile['Person']['last_name']; ?> </td>
<td><?php echo $userProfile['Address']['street']; ?> </td>
<td><?php echo $userProfile['Address']['house_no']; ?> </td>
</tr>
Note that there is only one row.