Downloads

Google Ad

CakePHP Combine List Fields

Date: Sat, Aug 1st 2009, 19:57 Author: nick Views: 16538 Comments share

SuperList

Info:
Watch:
Get it:
A common problem with find('list') is not being able to combine multiple fields with a specific format for your drop down boxes. Not to fret, superlist comes to the rescue.

Based on teknoid's post: http://teknoid.wordpress.com/2008/09/04/findlist-with-three-or-combined-fields/

I've extended his superlist to allow for custom passed in formats and isn't limited to only combining two fields.

/app/app_model.php
  1. function find($type, $options = array()) {
  2.  switch ($type) {
  3.    case 'superlist':
  4.      $total_fields = count($options['fields']);
  5.      
  6.      if(!isset($options['fields']) || $total_fields < 3){
  7.        return parent::find('list', $options);
  8.      }
  9.      if(!isset($options['separator'])){
  10.        $options['separator'] = ' ';
  11.      }
  12.      
  13.      if(!isset($options['format'])){
  14.        $options['format'] = '%s';
  15.        for($i = 2; $i<$total_fields;$i++){
  16.          $options['format'] .= "{$options['separator']}%s";
  17.        }
  18.      }
  19.  
  20.      $options['recursive'] = -1;              
  21.      $list = parent::find('all', $options);
  22.      
  23.      $formatVals = array();
  24.      $formatVals[0] = $options['format'];
  25.      for($i = 1; $i < $total_fields; $i++){
  26.        $formatVals[$i] = "{n}.{$this->alias}.".str_replace("{$this->alias}.", '', $options['fields'][$i]);
  27.      }
  28.      
  29.      return Set::combine(
  30.        $list,
  31.        "{n}.{$this->alias}.{$this->primaryKey}",
  32.        $formatVals
  33.      );
  34.    break;              
  35.  
  36.    default:              
  37.      return parent::find($type, $options);
  38.    break;
  39.  }
  40. }

Example Usage:
  1. $users = $this->User->find('superlist', array(
  2.   'fields' => array('User.id', 'User.last_name', 'User.first_name'),
  3.   'separator' => ', '
  4.   ));
  5. //Output:
  6. //[User.id] => User.last_name, User.first_name

  1. $users = $this->User->find('superlist', array(
  2.   'fields' => array('User.id', 'User.last_name', 'User.first_name'),
  3.   'format' => '%s, %s'
  4.   ));
  5. //Output: same as above
  6. //[User.id] => User.last_name, User.first_name

  1. $users = $this->User->find('superlist', array(
  2.   'fields' => array('User.id', 'User.last_name', 'User.first_name', 'User.phone'),
  3.   'format' => '%s, %s -- %s '
  4.   ));
  5. //Output:
  6. //[User.id] => User.last_name, User.first_name -- User.phone