[eluser]Iverson[/eluser]
I'm sure I'm not the only one who has tables like "Countries" or "States" that I need to edit or choose from. So I wrote a function to stick in the Datamapper library that will return a select menu populated from the db. It will even select a value given the id of the row. This will be useful when editing someone's record. If the Model you specify doesn't exist, it will not throw an error, but simply return FALSE;
Use:
Code:
$array = array(
'display' => 'country_code', # This is the field name you want to display for each option
'selected' => 2); # In this example, United States is id 2
$dropdown = $obj->dropdown('country', $array);
if($dropdown)
{
echo $dropdown;
}
/* Will produce
<select name="application">
<option value="1">AU</option>
<option value="2" selected="selected">US</option>
</select>
*/
Code:
// --------------------------------------------------------------------
/**
* Dropdown
*
* Display select menu for database table.
*
* @access public
* @param string
* @param array
* @return string
*/
function dropdown($class, $attr)
{
if(class_exists($class))
{
$this->load->helper('array');
$obj = new $class();
$display = element('display', $attr);
$extra = element('extra', $attr);
$obj->get();
if(count($obj->all) > 0)
{
$form = '<select name="' . $class . '\"';
if($extra)
{
$form .= $extra;
}
$form .= '>' . "\n";
$select_id = element('selected', $attr);
foreach($obj->all as $row)
{
$select = '';
if($select_id == $row->id)
{
$select = ' selected="selected" ';
}
$form .= "\t" . '<option value="' . $row->id . '"' . $select . '>' . stripslashes($row->$display) . "</option>\n";
}
$form .= "</select>\n";
return $form;
}
return FALSE;
}
return FALSE;
}