cakePHP generateList for custom query

I had a situation today in a cakephp project where I needed to do a custom query to get at a bunch of user names that had some pretty ethereal associations with the view I was working on. That was fine, some SQL later I was getting at the correct data. The issue I now had as that whereas previously I would have just done…

  1.  
  2. $this->set(‘people’, $this->Thing->People->generateList());
  3.  

then in the view I would have done…

  1.  
  2. <?php echo $html->selectTag(‘Thing/person_id’, $people, $html->tagValue(‘Thing/person_id’), array(), array(), true);?>
  3.  

I now couldn’t as there was no way to run generateList on my new custom query (if there is a way that you know I’d love to hear about it).

Anyway, after some digging around I was able to refactor some of the code in generateList() to do what I wanted…

  1.  
  2. $myPeople = $this->Thing->query("SELECT people.name, people.id FROM … custom SQL …");
  3.  
  4. // this is the cool stuff
  5. $keys = Set::extract($myPeople, ‘{n}.people.id’);
  6. $vals = Set::extract($myPeople, ‘{n}.people.name’);
  7.  
  8. if (!empty($keys) && !empty($vals)) {
  9.   $myPeople = array_combine($keys, $vals);
  10. }
  11.  
  12. $this->set(‘people’, $myPeople);
  13.  

Now you can use the OOTB select to generate a drop down that is populated from your custom SQL.

I have to say, I was pretty blown away by extract, never really used it before, but it’s pretty handy.


About this entry