Sometimes while creating an extension, you may need to provide admin the complete control of the frontend UI. Changing UI includes the change of background color, font colors which arises the need of adding color picker in Magento 2 Admin Configuration.
Generally, the settings in a Magento 2 extension resides under Stores –> Configuration and here you need to add the color picker to allow change the color in frontend UI. Here, I’ll show to add color picker in Magento 2 Admin Configuration in just three steps!
Steps to Add Color Picker in Magento 2 Admin Configuration:
1. Add color picker to textbox through system.xml file located at app\code\Vendor\Module\etc\adminhtml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> <system> <section> <group id="my_color_group" ...> <field id="my_color_option" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Background Color</label> <comment><![CDATA[Background color]]></comment> <frontend_model>Vendor\Module\Block\Color</frontend_model> </field> </group> </section> </system> </config>
2. Create one Color.php file at below location under the hood of extension app\code\Vendor\Module\Block
<?php namespace Vendor\Module\Block; use Magento\Config\Block\System\Config\Form\Field; use Magento\Backend\Block\Template\Context; use Magento\Framework\Registry; use Magento\Framework\Data\Form\Element\AbstractElement; class Color extends Field { protected $_coreRegistry; public function __construct($context, Registry $coreRegistry, array $data = []) { $this->_coreRegistry = $coreRegistry; parent::__construct($context, $data); } protected function _getElementHtml(AbstractElement $element) { $html = $element->getElementHtml(); $cpPath = $this->getViewFileUrl('Vendor_Module::js'); if (!$this->_coreRegistry->registry('colorpicker_loaded')) { $html .= '<script type="text/javascript" src="' . $cpPath . '/' . 'jscolor.js"></script>'; $this->_coreRegistry->registry('colorpicker_loaded', 1); } $html .= '<script type="text/javascript"> var el = document.getElementById("' . $element->getHtmlId() . '"); el.className = el.className + " jscolor{hash:true}"; </script>'; return $html; } } ?>
3. Add the JS file at Vendor_Module/view/adminhtml/web/js/jscolor.js, click here to copy jscolor.js
Clear the cache and navigate to stores configuration. The color picker option will be displayed. Use this color picker anywhere in Magento 2 with your own customized code when needed!