Skip to content

Instantly share code, notes, and snippets.

@jlleblanc
Created April 16, 2010 15:26
Show Gist options
  • Save jlleblanc/368556 to your computer and use it in GitHub Desktop.
Save jlleblanc/368556 to your computer and use it in GitHub Desktop.
<?php
defined( '_JEXEC' ) or die;
/**
* An helper class for generating dropdowns in Joomla.
*
* @package default
* @author Joseph LeBlanc
*/
class SmartDrops
{
private $value_source;
private $input_name;
private $value;
private $source_type;
/**
* Expects the name of the dropdown you're generating, along with a value
* source. The value source can be an array of values, or an SQL query. If
* an SQL query is used, it MUST return the columns 'value' and 'text' for
* the option values and labels, repsectively. Also allows the value to be
* preset.
*
* @param string $input_name
* @param mixed $value_source
* @param mixed $value
* @throws Exception
* @author Joseph LeBlanc
*/
function __construct($input_name, $value_source, $value = 0, $source_type = 'single')
{
if (!is_array($value_source) && !is_string($value_source)) {
throw new Exception("The value source for SmartDrops must either be an SQL query or array of values");
}
$this->value_source = $value_source;
$this->input_name = $input_name;
$this->value = $value;
$this->source_type = $source_type;
}
/**
* Generates the dropdown based on the preset value source and input name.
* Optionally, you can override the default value as well as its label.
*
* @param string $default_value
* @param string $default_label
* @return void
* @author Joseph LeBlanc
*/
public function generateDropdown($default_value = 0, $default_label = '-select-')
{
// If SQL, run it and get values. Otherwise, make from array.
if (is_string($this->value_source)) {
$options = $this->getOptionsFromSQL();
} else {
$options = $this->getOptionsFromArray();
}
$option = JHTML::_('select.option', $default_value, $default_label);
$options = array_merge(array($option), $options);
$dropdown = JHTML::_('select.genericlist', $options, $this->input_name, null, 'value', 'text', $this->value);
return $dropdown;
}
private function getOptionsFromSQL()
{
$database =& JFactory::getDBO();
$database->setQuery($this->value_source);
return $database->loadObjectList();
}
private function getOptionsFromArray()
{
$options = array();
foreach ($this->value_source as $key => $label) {
if ($this->source_type == 'keyed') {
$options[] = JHTML::_('select.option', $key, $label);
} else {
// single elements
$options[] = JHTML::_('select.option', $label, $label);
}
}
return $options;
}
public function __tostring()
{
return $this->generateDropdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment