Skip to content

Instantly share code, notes, and snippets.

@DanielVF
Created April 16, 2009 00:30
Show Gist options
  • Save DanielVF/96121 to your computer and use it in GitHub Desktop.
Save DanielVF/96121 to your computer and use it in GitHub Desktop.
<?
// Written for my own use, 2009
function select_exisiting_or_new($object,$field_name){
// To use:
// echo select_exisiting_or_new($product,'manufacturer')?
$current_value = $object->$field_name;
$possible_values = $object->query("SELECT `$field_name` from $object->table_name GROUP BY `$field_name` ORDER BY `$field_name`");
ob_start();
?>
<select
name="<?=htmlspecialchars($field_name)?>"
onchange="var show_new = (this.selectedIndex==this.options.length-1); var new_field=document.getElementById('field_<?=htmlspecialchars($field_name)?>_extra'); new_field.style.display=(show_new?'inline':'none'); new_field.disabled=(show_new?false:true); if(show_new){new_field.focus()}"
id="field_<?=htmlspecialchars($field_name)?>">
<option value="">-- Choose One--</option>
<?php foreach ($possible_values as $pvalue):
$value = $pvalue->$field_name;
if($value==''){ continue; }
$checked = $value == $current_value ? 'selected' : '';
?>
<option <?=$checked?>><?=htmlspecialchars($value)?></option>
<?php endforeach ?>
<option value="">Add new...</option>
</select>
<input type="text" value="" name="<?=htmlspecialchars($field_name)?>" id="field_<?=htmlspecialchars($field_name)?>_extra" style="display:none" disabled="true">
<?
return ob_get_clean();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment