tags:

views:

46

answers:

3
+1  Q: 

cakephp find list

Hi 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 too fetch id,name(first + last). so how can I achieve it. 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 Please suggest me how can I do it in controllers itself.

EDIT

I am using cakephp 1.2

+7  A: 

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

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

var $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.

var $displayField = 'full_name';

The id is fetched automatically.

Tim
A: 

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/view/662/combine

Dooltaz
thanks did the job perfectly
Web Developer
virtualFields as said below is the way it should be done. keeps that controller skinny.
dogmatic69
VirtualFields may not necessarily be the solution. The question is, do you want to change the structure of the returned data globally to accomodate one controller/action? If not, using Set::combine is probably a better solution. If you need full_name globally, add the virtual field.
Dooltaz
A: 

+1 on Tim's answer, however, if you need an alternative, teknoid wrote a nice article about this a long time ago:

http://nuts-and-bolts-of-cakephp.com/2008/09/04/findlist-with-three-or-combined-fields/

dr Hannibal Lecter