[2012-06-20]
Custom Form Fields in Joomla
defined('_JEXEC') or die;
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
class JFormFieldSample extends JFormFieldList
{
protected $type = 'sample';
protected function getOptions()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, title');
$query->from('#__tbl_name');
$db->setQuery((string)$query);
$sample = $db->loadObjectList();
$options = array();
if ($sample)
{
foreach($sample as $item)
{
$options[] = JHtml::_('select.option', $item->id, $item->title);
}
}
$options = array_merge(parent::getOptions(), $options);
return $options;
}
}
Then to use the custom field, open your XML file in admin/models/forms/. Insert the code, and again change the name Sample to your field name.
<field name="sample_field" type="sample" label="Sample" description="Sample custom field!"> <option value="0">First Text</option> </field>The type parameter is where your input's name comes into play. It tells Joomla to find the JFormFieldSample class as how to execute the input.
📘 Understanding Drupal: A Complete Guide to Caching Layers — my new book is out now!
Want more? Sign up for my weekly newsletter