cakephp

cakephp find list


I want to be able to generate a list using find so that I can use in select helper. but there is a problem. I want to fetch id, name (first + last). I want first_name and last_name to be joined as name. How can I achieve it?

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

I can't use model filters and callback. How can I do it in controllers itself?


Solution

  • 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.