MainelyDesign.com Blog

Using CakePHP's Set Class to Make Select List Options

Posted on 06/19/2009 at 11:22 am by Kevin Wentworth
Viewed 12,892 times | 0 comments

If you haven't become familar with any of the functionality of the CakePHP's Set class, I highly recommend you take a peak.  I don't know too much about it and really only learn about it as I go.  Well, I finally found out how to do something that used to take several lines of code: creating options for a select list that includes the Model.id as the key, but has a concatenated string for the value, like 'Model.name - created by Model.userName'.

Using the Set class this is easy.  With Set::combine() the following will work:

  1. $snapshots = $this->WebPage->Snapshot->returnSnapshots(array('type'=>'web_page', 'type_id'=> $id));
  2. $snapshot_list = Set::combine($snapshots, '{n}.Snapshot.id', array('{0} - {1}', '{n}.Snapshot.comments', '{n}.Snapshot.created'));

Explained:

  • the first parameter is the array you want to pull values out of
  • the second is the path for the id or key for the options array
  • the third is the path for the value of the options array (what the user will see)

The Path is pretty straightforward, place an {n} where you would normally use $key in a foreach($data as $key => $value).  I'm sure more explanation is needed, maybe at a later date.  Basically the {n} signifies where the array should be stepped/incremented.

What's got me excited is the ability to use an array as a path, where the first value is the pattern for the value and then you supply as many paths as needed. 

Per the above code excerpt, {0} - {1}, means:

  • to take the value from the first path ({n}.Snapshot.comments),
  • add a space+hyphen+space, and
  • add the second path value ({n}.Snapshot.created). 

Awesome!  No more foreach loops.

Cheers,

-Kevin Wentworth

Bookmark and Share

Tags for Using CakePHP's Set Class to Make Select List Options

Cakephp | Web Programming | Database

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design