Recent Posts
- (09/10) Fixing Warning: the ECDSA host key for 'github.com' differs from the key for the IP addressTAGS:Web Server Admin
- (12/26) CakePHP 3 - Getting List of Column Definitions from a Table (like schema())TAGS:CakephpCake3
- (09/14) Change Order of Loaded Behaviors in CakePHP 3TAGS:Cake3CakephpWeb ProgrammingPhp
- (05/29) CakePHP 3 - Accept JSON Header Only Working When Debug FalseTAGS:Web ProgrammingCakephpCake3
- (05/23) Remove All Events from Google Calendar (Reset Calendar)TAGS:Web ProgrammingPhp
- (11/08) Google Tag Manager (GTM) Not Firing Default PageView EventTAGS:Web ProgrammingJavascriptGoogle Tag Manager
- (10/13) In PHP, how do you get __toString() Magic Method Result without calling echo?TAGS:CakephpCake3Cakephp 13PhpWeb Programming
- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
Subscribe to my feed
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 13,238 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:
- $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
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!