How do I get the first and last name of a person in a select box from an associated table in cakePHP 2.4?

StackOverflow https://stackoverflow.com/questions/21803295

  •  12-10-2022
  •  | 
  •  

Pergunta

Say I have two tables, people and posts. The people has an id, first_name, and last_name in it. The posts table has an id, title, body, and person_id. Post belongsTo Person and Person hasMany Posts. Then I bake the schema. The default form for adding a posts will have a select box for picking the person who owns the post from the list of people in the database. However, only the person's first name shows up in the post. How would you get the first and last name to show up in that select box?

Person Model:

class Person extends AppModel { 
    public $displayField = 'first_name';
    public $hasMany = array( 'Post' );
...

Posts controller for the add will include this:

$people = $this->Post->Person->find('list');
$this->set(compact('people'));

And the Post view will have this:

echo $this->Form->input('person_id');

The view will automatically detect the association and populate the select box, but what do I have to do to get first_name and last_name to display in the selection?

(This applies to other situations too, where you would want multiple database columns to display in a select box, but I picked this as an example because it made the question easier to ask.)

Foi útil?

Solução

In the Person Model, use

public $displayField = 'full_name';

public $virtualFields = array(
    'full_name' => 'CONCAT(Person.first_name, " ", Person.last_name)'
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top