We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
Magento 2: Add ColorPicker in System Config
To add a Color Picker in Magento 2 System Configuration, follow these steps:
1. Create Block
Create aColorPicker.php file in app/code/Vendor/Module/Block/:
<?php
namespace Vendor\Vendor\Block\Adminhtml;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class ColorPicker extends Field
{
/**
* @param AbstractElement $element
* @return string
*/
protected function _getElementHtml(AbstractElement $element)
{
$html = $element->getElementHtml();
$value = $element->getData('value');
$html .= '<script type="text/javascript">
require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {
$(document).ready(function () {
var $el = $("#' . $element->getHtmlId() . '");
$el.css("backgroundColor", "' . $value . '");
// Attach the color picker
$el.ColorPicker({
color: "' . $value . '",
onChange: function (hsb, hex, rgb) {
$el.css("backgroundColor", "#" + hex).val("#" + hex);
}
});
});
});
</script>';
return $html;
}
}
2. Create Layout xml
Create aadminhtml_system_config.xml file in app/code/Vendor/Module/view/adminhtml/layout:
<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<head>
<css src="jquery/colorpicker/css/colorpicker.css"/>
<link src="jquery/colorpicker/js/colorpicker.js"/>
</head>
</page>
3. Create System.xml
Add the below code to yoursystem.xml file
<field id="text_color" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Message Text Color</label>
<comment><![CDATA[Text color]]></comment>
<depends>
<field id="enabled">1</field>
</depends>
<frontend_model>Vendor\Module\Block\Adminhtml\ColorPicker</frontend_model> <!-- Our block for attaching color picker to text box -->
</field>