Select2 in Joomla 3

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

One of the most visible changes in Joomla 3 are form elements.

HTML select list

Classic select list

jQuery Chosen element

jQuery Chosen element

Introduction - formbehavior.chosen

I really like new style of select lists and looked for the way this change was done. After while of searching in Joomla code and playing with it, I realized the magic formula is:

JHtml::_('formbehavior.chosen', 'select');

This command calls function chosen of JHtmlFormbehavior class stored in

[joomla root]/libraries/cms/html/formbehavior.php

Basically, this function adds Javascript and stylesheet files of jQuery Chosen plugin to Joomla document and use its features for all select elements.

Chosen plugin in Joomla 3 is big step forward but Select2 in my opinion offers more. Specially, I need possibility to add images for items in select lists.

Class formbehavior2 for Select2

Analogous to chosen & formbehavior, I created following file:

abstract class JHtmlFormbehavior2
{
	/**
	 * @var    array  Array containing information for loaded files
	 * @since  3.0
	 */
	protected static $loaded = array();

	/**
	 * Method to load the Select2 JavaScript framework and supporting CSS into the document head
	 *
	 * @param   string  $selector  Class for Chosen elements. [optional]
	 * @param   string  $option    options for Select2 elements. [optional]
	 * @param   mixed   $debug     Is debugging mode on? [optional]
	 *
	 * @return  void
	 *
	 * @since   3.0
	 */
	public static function select2($selector = '.advancedSelect', $option = '', $debug = null)
	{
		if (isset(static::$loaded[__METHOD__][$selector]))
		{
			return;
		}

		// Include jQuery
		JHtml::_('jquery.framework');

   	// If no debugging value is set, use the configuration setting
		if ($debug === null)
		{
			$config = JFactory::getConfig();
			$debug  = (boolean) $config->get('debug');
		}

		JHtml::_('script', 'jui/select2.min.js', false, true, false, false, $debug);
		JHtml::_('script', 'jui/select2_locale_cs.js', false, true, false, false, $debug);
		JHtml::_('stylesheet', 'jui/select2.css', false, true);
		JFactory::getDocument()->addScriptDeclaration("
				jQuery(document).ready(function (){
					jQuery('" . $selector . "').select2({
						" .$option. "
					});
				});
			"
		);

		static::$loaded[__METHOD__][$selector] = true;

		return;
	}
} 

Function select2 load the Select2 JavaScript framework and supporting CSS into the document head.

Download

Download this archive and copy included files to [joomla root].

Archive content:

libraries/cms/html/formbehavior2.php
media/jui/js/select2.js
media/jui/js/select2.min.js
media/jui/css/select2.css
media/jui/css/select2.png
Well! Now you can create awesome forms in Joomla using Select2.
see and try demo component with select2 form elements
& learn more on formbehavior2.select2 syntax.