[eluser]oddman[/eluser]
Hey all!
If anyone could direct me to a solution for this native to CI, that would be fantastic. As I was unable to find one, I wrote this short method which I threw into a file which extended the form helper. See below:
Code:
/*
* array2select
* Formats a given array for use by select boxes in CI. Example below:
* - form_dropdown('name', array2dropdown($array_of_values_from_db, 'id', 'name', '- Select -'))
* - Would return something like:
* <select name="name">
* <option value="">- Select -</option>
* <option value="id1">Name 1</option>
* <option value="id2">Name 2</option>
* </select>
*
* @param array $array
* @param string $value_field
* @param string $test_field
* @param string $first Not required
*
* @return array
* @author Kirk Bushell
* @url http://www.kirkbushell.com
*/
function array2dropdown($array, $value_field, $text_field, $first = null)
{
if (!is_array($array)) {
throw new Exception('Array expected for 1st argument, '.gettype($array).' received.');
}
$return = array();
if (!is_null($first)) {
$return[] = $first;
}
foreach ($array as $row) {
if (is_object($row)) {
$return[$row->$value_field] = $row->$text_field;
} else {
$return[$row[$value_field]] = $row[$text_field];
}
}
return $return;
}
Feel free to use and abuse
It will support arrays of data being sent, but will also support arrays of objects (like what DataMapper would provide).