Skip to content


Cakephp find(’list’) and select

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:
  1. function find($type, $options = array()) {
  2. switch ($type) {
  3. case 'superlist':
  4. if(!isset($options['fields']) || count($options['fields']) <3) {
  5. return parent::find('list', $options);
  6. }
  7.  
  8. if(!isset($options['separator'])) {
  9. $options['separator'] = ' ';
  10. }
  11.  
  12. $options['recursive'] = -1;
  13. $list = parent::find('all', $options);
  14.  
  15. for($i = 1; $i <= 2; $i++) {
  16. $field[$i] = str_replace($this->alias.'.', '', $options['fields'][$i]);
  17. }
  18.  
  19. return Set::combine($list, '{n}.'.$this->alias.'.'.$this->primaryKey,
  20. array('%s'.$options['separator'].'%s',
  21. '{n}.'.$this->alias.'.'.$field[1],
  22. '{n}.'.$this->alias.'.'.$field[2]));
  23. break;
  24.  
  25. default:
  26. return parent::find($type, $options);
  27. break;
  28. }
  29. }

Now all we have to do in our controller is:

CODE:
  1. $this->User->find('superlist', array('fields'=>array('User.id','User.name','User.email'),'separator'=>' * '));

source

Posted in cakephp, php.

Tagged with , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.