- Creating a custom form field type
- Form Field Type Class Requirements [ править ]
- Which Class to Subclass? [ править ]
- Location of Files [ править ]
- Naming Conventions and Skeleton [ править ]
- Grouping Custom Field Types [ править ]
- An Example Custom Field Type [ править ]
- Setting the Values of a List Option and Using JSON or an API Instead of a Database Call [ править ]
- Pitfalls [ править ]
- Using the Custom Field Type [ править ]
- Linked with a Form [ править ]
- Not Linked with a Form [ править ]
- Overriding getLabel() [ править ]
- Sample Component Code [ править ]
Creating a custom form field type
This article is tagged because it NEEDS REVIEW. You can help the Joomla! Documentation Wiki by contributing to it.
More pages that need help similar to this one are here. NOTE-If you feel the need is satistified, please remove this notice.
JForm, a feature introduced in Joomla! 2.5, lets you easily create HTML forms ( ). Forms created using JForm consist of form fields, implemented as JFormField. 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. JForm supports a large selection of standard field types. For a full list, see Standard form field types.
Joomla! makes it possible to extend standard field types or define your own. For example, if your component manages phone book entries, you might want to define a form field type that outputs a select list of cities. There are several advantages to defining a custom form field type:
- You will be able to mix standard field types with your custom field type in a JForm-based form.
- You will eventually have a reusable code package that can be used easily throughout your code.
- Extensions that collaborate with your extension will be able to create form fields without meddling with your database tables and other internals.
Form Field Type Class Requirements [ править ]
A form field type is defined in a class that must be a (not necessarily direct) subclass of JFormField. To work correctly, the class must define at least three methods:
- public function getLabel() This function will be called to create the label that belongs to your field and must return an HTML string containing it. Since JFormField defines a ready-to-use getLabel() implementation, custom form field types usually do not define their own getLabel(). If you leave it out, the inherited method of creating labels will be used. It is recommended to leave out the getLabel() method for consistency and speed unless you actually want to modify the label’s HTML.
- public function getInput() This function will be called to create the field itself and must return an HTML string containing it. This is also where most of the processing usually happens. In our phone book City field example, this function will have to retrieve a list of available cities and return an HTML with the cities inserted as s.
- public function getValue() This function will be called to get the field value. The value is obtained from the function LoadFormData in the Model
Inside your code, you will have to process the attributes set by the field’s user in the XML form definition. Some of those attributes are accessible via protected member variables of JFormField. For example, the name attribute is available in your code as $this->name. Similarly, label, description, default, multiple and class are also available as properties of $this. Other parameters you might have defined can be accessed through the $this->element array: the attribute size will be in $this->element[‘size’].
Which Class to Subclass? [ править ]
For a form field type to be usable in JForm, it needs to be a subclass of JFormField. However, it does not have to be a direct child of that class. You can also subclass an existing (standard or custom) form field type and thereby inherit useful code.
If your form field type is similar to an existing type, you should subclass that type. Especially if your form field type is a list, please subclass JFormFieldList. You only have to override getOptions() method to return the options to be shown. The getInput() method will convert those options to HTML.
To subclass an existing type, for example JFormFieldList, load it by adding the following after jimport(‘joomla.form.formfield’);:
jimport('joomla.form.helper'); JFormHelper::loadFieldClass('list');
If your form field type is unlike any existing type, subclass JFormField directly.
Location of Files [ править ]
- The standard form field types are located in libraries/joomla/form/fields/. You should not store custom fields there, nor should you have to use this path in your own code. The standard types are usually good examples.
- The custom field types that belong to your component are usually located in administrator/components//models/fields. You can specify this or another path in your code:
JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
- The XML files that define forms are usually located in administrator/components//models/forms. Use something like the following snippet to specify a path to your forms:
JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
Naming Conventions and Skeleton [ править ]
In this section, represents the camel-cased name of your component and represents the camel-cased name of your form field type. The field’s class should be placed in administrator/components//models/fields/.php, and look like this:
extends JFormField < //The field class must know its own type through the variable $type. protected $type = ''; public function getLabel() < // code that returns HTML that will be shown as the label >public function getInput() < // code that returns HTML that will be shown as the form field >>
Grouping Custom Field Types [ править ]
Warning: this information is partially incorrect and needs to be improved.
Custom field types can be grouped by using an underscore in the field name. A field class with a name for example like «JFormFieldMy_randomField» must be stored in administrator/components//models/fields/my/randomField.php. We can prefix our form field names with some group name, then we put an underscore and then a name of a field.
An Example Custom Field Type [ править ]
Suppose you’re working on your component named com_phonebook and you want to define a field that contains cities. Create the file administrator/components/com_phonebook/models/fields/city.php and write something similar to the following:
name.'">'. ''. ''. ''. ''; > >
A more advanced approach is extending the JFormFieldList class. Suppose you want to create a drop-down of cities dynamically from database based on a dynamic condition. You can do this in the following way:
input->get('country'); //country is the dynamic value which is being used in the view $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.cityname')->from('`#__tablename` AS a')->where('a.country = "'.$country.'" '); $rows = $db->setQuery($query)->loadObjectlist(); foreach($rows as $row)< $cities[] = $row->cityname; > // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $cities); return $options; > >
The above example shows a simple query which will show a list of cities from a table where city name belongs to its country respectively. You can create a drop-down based on more complex queries.
Setting the Values of a List Option and Using JSON or an API Instead of a Database Call [ править ]
If you want to use an API call instead of a database call to build a custom list item, use the following code.
This field was created in a module. To get it to work it needs to be saved to mod_modulename/models/fields/stackexchangesites.php. The naming convention is important as it is used within our function name.
// decode the JSON $sites = json_decode($json, true); // use a for each to iterate over the JSON foreach($sites['items'] as $site) < // choose the element of the JSON we want, and set it as a variable so we can use it in our array. $site = $site['api_site_parameter']; $site_url = $site['site_url']; // set an array and start adding values to it. Set another array within our array to set our value / text items. $stackExchangesSitesOptions[] = array("value" =>$site, "text" => $site_url); > // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $stackExchangesSitesOptions); return $options; > >
On the Frontend simply calling the parameter gets us the value.
$stackexchangesites = $params->get('stackexchangesites');
Pitfalls [ править ]
Loading a custom field can result in a Fatal Error if a core field exists with the same filename and the custom field extends the core field.
Consider a file testfields/radio.php containing
Calling JFormHelper::loadFieldClass(‘radio’) will yield a Fatal error: Class ‘JFormFieldRadio’ not found.
There are two reasons for this.
- JLoader cannot autoload JFormFieldRadio because the class name (JFormField*) does not match the path name (joomla/form/fields/* — notice the plural on fields).
- JFormHelper cannot load JFormFieldRadio because custom paths are scanned first and the requested field type(‘radio’) gets resolved before the core classes are reached.
Require the core field file directly:
and use JFormHelper::loadFieldClass properly with ‘test.radio’ instead of ‘radio’.
Using the Custom Field Type [ править ]
Linked with a Form [ править ]
To use the field type City, we need to update the XML file that contains the form fields. Open your XML file located in administrator/components/com_phonebook/models/forms and add the field in the usual way:
The attribute name is cAsE-sEnSiTiVe.
In addition, you may need to add the field path to the parent :
Not Linked with a Form [ править ]
For example, when you need the field as a dropdown in a component as admin/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!!
Overriding getLabel() [ править ]
As mentioned in the section Form field type class requirements, custom form field types usually do not define their own getLabel(). If you do want to create a custom label, you can still make use of the getLabel() that every field type class inherits from JFormField by defining it as follows:
public function getLabel() < return '' . parent::getLabel() . ''; >
This code will underline your form labels. (Please note that if your goal is to underline form labels, using CSS is the preferred way.)
If you want to do something completely different, you can of course also override it completely:
public function getLabel() < // Initialize variables. $label = ''; $replace = ''; // Get the label text from the XML element, defaulting to the element name. $text = $this->element['label'] ? (string) $this->element['label'] : (string) $this->element['name']; // Build the class for the label. $class = !empty($this->description) ? 'hasTip' : ''; $class = $this->required == true ? $class.' required' : $class; // Add replace checkbox $replace = 'name.']" value="1" />'; // Add the opening label tag and main attributes attributes. $label .= ''; return $label; >
This example will add a checkbox inside the label.
Sample Component Code [ править ]
Below is the code for a small component which you can install and run and can adapt to experiment further with custom fields. The component includes two custom fields
- A «City» field as described above (except that the options are hard-coded rather than being selected from a database). We’ll also allow multiple Cities to be selected and pre-select two of them as default.
- A custom «time» field which maps to the HTML «time» input type and includes underlining the label and support for setting a minimum and maximum time.
Create the following five files in a folder called com_custom_fields. Then zip up this folder to create com_custom_fields.zip. Install this component on your Joomla instance. Once installed, navigate on your browser to your Joomla site and add to the URL the parameter &option=com_custom_fields. This should display the form with the two custom fields. You can submit the form and see the HTTP POST parameters using the browser development tools but the component doesn’t contain any code which handles those parameters.
(As described in Basic form guide, the approach below isn’t the recommended way to design Joomla components but it’s written in this minimalist fashion to focus on the custom fields aspects).
com_custom_fields.xml The manifest file for the component.
com_custom_fields 1.0.0 Custom Fields demo component custom_fields.php form_definition.xml City.php Time.php
custom_fields.php The main code file which is run when an HTTP GET or POST is directed towards this component.
"jform")); Form::addFieldPath(__DIR__); ?>
form_definition.xml File containing the XML for the form definition, basically the two custom fields.
City.php PHP code for the City custom field.
1, 'text' => 'New York'), array('value' => 2, 'text' => 'Chicago'), array('value' => 3, 'text' => 'San Francisco'), ); // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $cities); // pre-select values 2 and 3 by setting the protected $value property $this->value = array(2, 3); return $options; > >
Time.php PHP code for the time custom field.
class) ? ' ' : ''; $attr .= !empty($this->element['min']) ? ' min="' . $this->element['min'] . '"' : ''; $attr .= !empty($this->element['max']) ? ' max="' . $this->element['max'] . '"' : ''; // set up html, including the value and other attributes $html = 'name . '" value="' . $this->value . '"' . $attr . '/>'; return $html; > public function getLabel() < return '' . parent::getLabel() . ''; > >