Skip to main content

Tutorial: Build your own custom field plugin - owlimg.php

Written by Elisa Foltyn

This Joomla! Custom Field Plugin shows images from a selected folder in an "Owl Carousel". In this tutorial, I'll explain to you, how to build your own "Custom Field Plugin".

owlimg.php

The main file of our plugin is calling the field. In the first step, the following code is enough to display the field. 

<?php
/**
* @package Joomla.Plugin
* @subpackage Fields.Owl
*
* @copyright Copyright (C) 2017 NAME. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/

defined('_JEXEC') or die;

JLoader::import('components.com_fields.libraries.fieldslistplugin', JPATH_ADMINISTRATOR);

class PlgFieldsOwlimg extends FieldsListPlugin
{

}

After PlgFields the name of the plugin follows, beginning with an uppercase letter so PlgFieldsOwlimg. With extends, we say that we want to extend an existing class. In this case FieldsListPlugin. If it's not a list we would use FieldsPlugin.

You can find the files where these classes are called from in administrator/components/com_fields/libraries.

Now we don't want to only show the field, but also define for example, that the images directory is the root of the possible selections in the field. So we change the code from above to the following:

<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  Fields.Owlimg
 *
 * @copyright   Copyright (C) 2017 NAME. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::import('components.com_fields.libraries.fieldslistplugin', JPATH_ADMINISTRATOR);

class PlgFieldsOwlimg extends FieldsListPlugin
{

	public function onCustomFieldsPrepareDom($field, DOMElement $parent, JForm $form)
	{
		$fieldNode = parent::onCustomFieldsPrepareDom($field, $parent, $form);
		if (!$fieldNode)
		{
			return $fieldNode;
		}

		$fieldNode->setAttribute('directory', 'images/');
		$fieldNode->setAttribute('hide_default', true);
		$fieldNode->setAttribute('hide_none', true);

		return $fieldNode;
	}

}

So we add in our class PlgFieldsOwlimg the method onCustomFieldsPrepareDom and set some attributes, such as the images directory where our images folders are. 

It's definitely time we get together!