How about a little trick to extend the find(’list’) functionality?..
Let’s say we need to display a list of users, but instead of just User.id and User.name we need to have User.id, as well as User.name and User.email combined. Unfortunately find(’list’) doesn’t have that type of functionality out-of-the-box. Well, that’s OK, we’ll make our own…
CODE:
-
function find($type, $options = array()) {
-
switch ($type) {
-
case 'superlist':
-
if(!isset($options['fields']) || count($options['fields']) <3) {
-
return parent::find('list', $options);
-
}
-
-
if(!isset($options['separator'])) {
-
$options['separator'] = ' ';
-
}
-
-
$options['recursive'] = -1;
-
$list = parent::find('all', $options);
-
-
for($i = 1; $i <= 2; $i++) {
-
$field[$i] = str_replace($this->alias.'.', '', $options['fields'][$i]);
-
}
-
-
return Set::combine($list, '{n}.'.$this->alias.'.'.$this->primaryKey,
-
array('%s'.$options['separator'].'%s',
-
'{n}.'.$this->alias.'.'.$field[1],
-
'{n}.'.$this->alias.'.'.$field[2]));
-
break;
-
-
default:
-
return parent::find($type, $options);
-
break;
-
}
-
}
Now all we have to do in our controller is:
CODE:
-
$this->User->find('superlist', array('fields'=>array('User.id','User.name','User.email'),'separator'=>' * '));
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.