Recently I have found one solution to add color picker on system configuration options in Magento 2. Lets discuss in detail.
In order to add color picker on system configuration options, we have to add one system field and require one Block file.
Use below code to add system field.
<field id="color" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Text Color</label>
<frontend_model>Hiddentechies\DigitalProduct\Block\Color</frontend_model>
</field>Now lets create Block file – Color.php
<?php
namespace Hiddentechies\DigitalProduct\Block;
use Magento\Framework\Registry;
class Color extends \Magento\Config\Block\System\Config\Form\Field {
protected $_coreRegistry;
public function __construct(
\Magento\Backend\Block\Template\Context $context, Registry $coreRegistry, array $data = []
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context, $data);
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) {
$base = $this->getBaseUrl();
$html = $element->getElementHtml();
$cpPath = $base . 'pub/media/js/';
if (!$this->_coreRegistry->registry('colorpicker_loaded')) {
$html .= '<script type="text/javascript" src="' . $cpPath . 'jscolor.js"></script><style type="text/css">input.jscolor { background-image: url(' . $cpPath . 'color.png) !important; background-position: calc(100% - 8px) center; background-repeat: no-repeat;} input.jscolor.disabled,input.jscolor[disabled] { pointer-events: none; }</style>';
$this->_coreRegistry->registry('colorpicker_loaded', 1);
}
$html .= '<script type="text/javascript">
var el = document.getElementById("' . $element->getHtmlId() . '");
el.className = el.className + " jscolor";
</script>';
return $html;
}
}Lets discuss some terms used in this block.
Hiddentechies – Vendor Name
DigitalProduct– Module Name
color.png – add color icon image at pub/media/js/ directory
jscolor.js – add color picker js at pub/media/js/ directory
You can download the color picker Js from below URL.
http://jscolor.com/download/
Thats it.


Leave a Reply