cakephp find list

I think this can be done using the virtualFields and displayField properties in your model.

In your model, define a virtual field for the full name like this:

public $virtualFields = array(
    'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);

If you now set displayField to full_name you should be able to get a list of your users with the $this->User->find('list') method which you can use without problems with the Form-helper.

public $displayField = 'full_name';

... or:

public $displayField = 'User.full_name';

The id is fetched automatically.


Another solution is to use Cake's Set::combine to build what you need...

$users = $this->User->find('all',array('fields' => array('first_name','last_name','id')));

$user_list = Set::combine($users, '{n}.User.id', array('{0} {1}', '{n}.User.first_name', '{n}.User.last_name'));

Result will look something like:

array(
 [2] => 'First Last',
 [5] => 'Bob Jones'
)

Here's the documentation link:

http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::combine


To achieve this first go to the model and add this line

  public $virtualFields = array('full_name' => 'CONCAT(first_name, " ", last_name)');

and then go to controller file just use the name "full_name" which you put in virtual fields

$this->User->find('all',array('fields' => array('full_name','id')));

It returns name with combined fields

Tags:

Cakephp