Reputation: 7839
I've just began using CakePHP and I have a question. I'm creating sort of a Task Manager system.
I have a 'Tasks' table, and this table has a user_id
field for assigning a task to a user.
When I baked the application, the generated form has a user_id
which was automatically linked to the users
table, but I want to show the user's username
instead of the user_id
- how would I go about doing this?
Also, I need for when the form is saved, it saves the user_id
into the field and not the username
- So it needs to display the username
for ease of use but save the user_id
.
I'm still new to this whole Model and Controller so I'm not sure how I'd manage to do this. Thanks.
Update:
Here's where I am so far. In my jobs add.ctp
I have added this code to help generate the form field:
foreach ($users as $user):
$options_array[$user['id']] = $user['username'];
endforeach;
print_r($options_array);
echo $this->Form->input('user_id', $options_array);
Unfortunately the print_r
gives me:
Array ( [2] => 2 )
And not the desired output:
Array ( [2] => Dan )
$users
is defined in the job_controller.php
as so:
$users = $this->Job->User->find('list');
$clients = $this->Job->Client->find('list');
$stages = $this->Job->Stage->find('list');
$this->set(compact('users', 'clients', 'stages'));
I'm not sure what I'm doing wrong here.
Dan
Upvotes: 2
Views: 238
Reputation: 12431
If you are only looking for the id and username, then using the list should be cool, but you have to specify the username field.
$users = $this->Job->User->find('list', array('fields' => array('User.username'));
That should return the array as such:
array (
[1] => 'username_for_id_1',
[2] => 'username_for_id_2',
... all the other records...
[114] => 'username for id_114'
)
If you need more information from the User table, then you should use the ->find('all').
$users->Job->User->find('all');
// $users is now:
// array (
// [0] => array (
// 'User' => array(
// 'id' => 1,
// 'username' => 'username',
// ... the rest of the fields
// )
// Other affiliated models will be included with the 'User' if
// you haven't set 'recursive' = -1
// )
// )
Upvotes: 2