Recent Posts
- (02/24) Calling an Element from a Helper TAGS:CakephpWeb ProgrammingUsageTutorialExample
- (10/14) Forcing A Single Join in CakePHP PaginationTAGS:CakephpCakephp 13DatabaseErrorsHabtmMysqlMssqlWeb ProgrammingUsage
- (08/11) Inserting NOW() into MySQL Using CakePHPTAGS:CakephpDatabaseMysqlMssqlWeb ProgrammingUsage
- (08/07) Best PaginateCount for CakePHP - with Group By SupportTAGS:CakephpBehaviorsWeb ProgrammingUsageDatabaseExampleMysqlHabtmHack
- (04/03) CakePHP Error Messages Not Showing on FormTAGS:CakephpCakephp 13Web ProgrammingErrorsUsage
- (02/06) Sorting Paginated Results Using a Related Model Field in CakePHPTAGS:CakephpWeb ProgrammingUsageExample
- (11/02) Changing CakePHP's Model useTable on the FlyTAGS:CakephpWeb ProgrammingMysqlDatabaseExampleTutorial
- (10/18) The Funniest Error Message Ever - Thank You EclipseTAGS:EclipseWeb ProgrammingErrorsHumorWindowsUsageSoftwarePhpCakephp
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 2,793 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!
