跳到主要内容
版本:5.1

示例自定义字段

本节提供 4 个如何创建自定义字段的示例。这些示例也存在于 示例组件代码 中,你可以下载并安装它。

扩展 FormField 的自定义字段

如果扩展 FormField,则应提供 getInput 方法,并从该方法返回字段的 HTML 字符串。例如,要捕获 3 个字符的 IATA 机场代码

protected function getInput()
{
$html = "<input type='text' id='{$this->id}' name='{$this->name}' " .
"minlength='3' maxlength='3' size='3' " .
"oninput='this.value = this.value.toUpperCase()'/>";
return $html;
}

来自表单定义 XML 文件中 <field> 元素的属性将已在 setup 函数中加载到类的属性中,因此可以通过 $this->name 等访问。

设置 name 属性非常重要,因为这将在表单数据提交时用作 HTTP POST 数据中的键。

默认情况下,标签从表单定义 XML 字段中的 label= 属性设置。你可以覆盖它,例如如果你想包含一个链接

protected function getLabel()
{
$html = "Enter the <a href='https://wikipedia.org/wiki/IATA_airport_code' target='_blank'>" .
"3 character IATA airport code</a>";
return $html;
}

示例组件代码 中,自定义字段类型“custom1”给出了一个示例。

使用布局扩展 FormField 的自定义字段

如果设置实例变量 $layout,则它将被视为 getInput 的布局。然后你无需提供 getInput 的实现。

class Custom2Field extends FormField
{
protected $layout = 'custom2field';
}

Joomla 将 $this 中保存的属性数据加载到 $displayData 中,以便你可以在布局文件中提取变量,生成诸如 $id$name 之类的变量。例如,在站点 layouts/custom2field.php 文件中

<?php
defined('_JEXEC') or die;
extract($displayData);
?>
<input
type='text'
id='<?php echo $id?>'
name='<?php echo $name?>'
minlength='3'
maxlength='3'
size='3'
oninput='this.value = this.value.toUpperCase()'/>

请记住在清单 XML 文件中包含站点 layouts 文件夹!

示例组件代码 中,自定义字段类型“custom2”给出了一个示例。

扩展 ListField 的自定义字段

如果希望自定义字段显示选项列表,则可以扩展 Joomla\CMS\Form\Field\ListField 并覆盖 getOptions 函数

use Joomla\CMS\Form\Field\ListField;
class Custom3Field extends ListField
{
public function getOptions()
{
$options = array("BFS", "HND", "YYZ");
$options = array_merge(parent::getOptions(), $options);
return $options;
}
}

$options = array_merge(parent::getOptions(), $options) 将上一行的选项与表单定义 XML 文件中字段中的任何 <option> 元素合并。

示例组件代码 中,自定义字段类型“custom3”给出了一个示例。

扩展 GroupedlistField 的自定义字段

这使你的选项可以分组。例如,如果希望机场代码按国家/地区分组,则可以覆盖 getGroups

use Joomla\CMS\Form\Field\GroupedlistField;
class Custom4Field extends GroupedlistField
{
public function getGroups()
{
$groups['Japan'] = array("HND");
$groups['Canada'] = array("XXY", "ABC", "DEF");
$groups['Northern Ireland'] = array("BFS", "BHD");
$groups = array_merge(parent::getGroups(), $groups);
return $groups;
}
}

示例组件代码 中,自定义字段类型“custom4”给出了一个示例。