CakePHP form select value as table.id, select option text as table.textfield

cakephp, php, select

Solution

successfully set up the select to output the options from the user tables, but it uses the user.id as both the value and the option text.

`find('list')` will by default use the primary key as the key, and the model's `displayField` as the value.

If a model does not have an explicit `displayField` but has a field named `title` or `name` Cake will automatically pick this field, otherwise it will not guess and simply use the primary-key field - which is what's happening in the question.

You can however simply specify which fields you want in the results of your `find('list')` call. Therefore either:

Set the model displayField

class User extends AppModel {

    public $displayField = 'username';

}

and then use:

$users = $this->User->find('list');

Explicitly choose the fields

$users = $this->User->find('list', array(
    'fields' => array('id', 'username')
));

In both cases - the result will be e.g.:

array(
    1 => 'firstuser',
    ...
    76 => 'AD7six'
)

Problem

I'm new to Cake. I've gotten some things set up, relevantly a "users" and a "profiles" table, controller, model and view. In my `profiles/add` view, I'm attempting to output a `select` input with the value being the `user.id` and the option text being the `user.username`. Ultimately, the value `user.id` will be saved in `profile.user_id`. I have read through a lot of documentation, and successfully set up the `select` to output the options from the `user` tables, but it uses the `user.id` as both the value and the option text. Controller: ``` $this->set('users', $this->Profile->User->find('list')); ``` View: ``` echo $this->Form->input('user_id'); ``` It seems like this sort of thing would be routine, so feel free to answer with just a link to the documentation if I've overlooked it completely. Thanks!

Original source