João Paulo Cercal

Staff Security Engineer at LastPass

  • PHP

Custom Fields in the Joomla panel

  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn

Read this article in

Hello, today I needed to add a custom field to the Joomla 1.6 administration panel for a component I was developing, and decided to share the “recipe” here on my blog.

This tutorial was developed based on the Official Joomla Documentation.

To create a custom field type for Joomla 1.6, you must create a class that extends a field type already defined by Joomla itself (media, text, etc), or else the base class for this functionality, which is “JFormField”.

The field types defined by Joomla itself are in the following directory:

  • joomla/libraries/joomla/form/fields/

We’ll create a specific field to retrieve three cities, to do this, create a file called “cidade.php” inside administrator/components/nome-do-seu-componente/models/fields/cidade.php and add the following code:

The class name should be prefixed with “JFormField” followed by the physical file name, which in this case is “cidade.php”, so the class name will be “JFormFieldCidade” using the CamelCase convention.

Two methods can be implemented by our “Cidade” class, they are:

  • getLabel()
  • getInput()

Both should return HTML.

The protected getLabel() method will return the label for our custom field, in many cases it isn’t needed because the class we extend already implements this functionality. On the other hand, the getInput() method should return the field’s html, which could be an input (text, radio, etc), or a select, for example.

See how our class turned out:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

// Importa a classe JFormField, da qual iremos extender
jimport('joomla.form.formfield');

class JFormFieldCidade extends JFormField
{
  // O valor da propriedade $type deve conter
  // o sufixo da classe nesse caso "Cidade"
  protected $type = 'Cidade';

  protected function getInput()
  {
    return '<select name="'.$this->name.'">'.
      '<option value="1" >Joinville</option>'.
      '<option value="2" >São Francisco do Sul</option>'.
      '<option value="3" >Itajaí</option>'.
      '</select>'
    ;
  }
}
?>

Within your code, you’ll have to process the attributes defined by the user in the XML form definition. Some of these attributes are accessible through protected member variables of JFormField.

For example, the name attribute is available in your code as $this->name. The same goes for: label, description, default, multiple and class.

Other parameters you may have defined can be accessed through $this->element, which is an array, the keys of this array are associative and take the property’s name. For example, the size attribute would be accessed like this: $this->element[‘size’].

Your XML would look like this:

1
<field name="cidade" type="cidade" label="Cidade" description="Cidades disponíveis" />