Skip to main content

Custom Form Fields in Joomla

Published on
When I was developing my Joomla! components to make my GRealty suite I needed a few custom fields that were not native to Joomla The process is simple and only requires one new folder and one new file in your component. In your components admin/models/  folder create a new folder called 'fields'. Create a new PHP file, name it however you want your field to be referenced within Joomla. In my case I named it 'realtors' as it queried the database for the list of realtors. Here is the basic coding you will need, replace 'Sample' with the name you chose for your custom field. This code is for a drop down menu list, explore Joomla docs for other field types.
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.