With the help of class JForm, you can easily create HTML forms in Joomla. Forms created using JForm consist of form fields, implemented as JFormFields. There is a JFormField for each different field type you can find in a form, such as a text field type and a date field type. There are many standard field types.

You can extend standard field types or define your own. For example, if your component uses location addresses, you might want to define a form field type that outputs a select list of cities or towns.

Advantages of Custom Form Field Type

  • You can mix standard field types with your custom field type in a JForm-based form.
  • You can have a reusable code package that can be used easily throughout your code.
  • Extensions that collaborate with your extension can create form fields without meddling with your database tables and other internals.

Location of Files

The custom field types that belong to your component are located in: admin/models/fields/field_name.php

You can specify this path in your code:

JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');

When Linked With Form

To use the custom field type, you need to update the XML file that contains the form fields. Update the XML file:

<fieldset addfieldpath="/administrator/components/<component name>/models/fields">

When Not Linked With Form

For example, when you need the field as a drop down in a component as admin or site filter.

//Get custom field
JFormHelper::addFieldPath(JPATH_COMPONENT . '/models/fields');
$cities = JFormHelper::loadFieldType('City', false);
$cityOptions=$cities->getOptions(); // works only if you set your field getOptions on public!!

List Type Custom Field

if your form field type is a list, then you can use subclass JFormFieldList. You only have to override getOptions() method to return the options to be shown. The getInput() method will convert these options to HTML.

First, you have to load the subclass by adding the following code:

jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');

Then, create a class that extends JFormFieldList.

class JFormFieldHelloWorld extends JFormFieldList
{
protected $type = 'HelloWorld';

/**
* Method to get a list of options for a list input.
*/
protected function getOptions()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id,greeting');
$query->from('#__helloworld');
$db->setQuery((string) $query);
$messages = $db->loadObjectList();
$options = array();

if ($messages)
{
foreach ($messages as $message)
{
$options[] = JHtml::_('select.option', $message->id, $message->greeting);
}
}

$options = array_merge(parent::getOptions(), $options);

return $options;
}
}