We learn how to add color picker in Magento 2 system configuration using the system.xml file.
In Magento 2, there are many times we need to add color dynamic from system configuration which admin can set the value. This provides the admin to choose the color which one wants to show. So now add color picker into system configuration follow below steps:
<?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"/> </head> </page>
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> <system> <tab id="dolphin" translate="label" sortOrder="201"> <label>Dolphin</label> </tab> <section id="colorepickerdemo" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1"> <class>separator-top</class> <label>Colore Picker Demo</label> <tab>dolphin</tab> <resource>Dolphin_ColorePickerDemo::colorepickerdemo_config</resource> <group id="general_option" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>General</label> <field id="add_color" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> <label>Add Color</label> <frontend_model>Dolphin\ColorePickerDemo\Block\Color</frontend_model> </field> </group> </section> </system> </config>
<?php namespace Dolphin\ColorePickerDemo\Block; class Color extends \Magento\Config\Block\System\Config\Form\Field { protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) { $html = $element->getElementHtml(); $value = $element->getData('value'); $html .= '<script type="text/javascript"> require(["jquery"], function ($) { $(document).ready(function (e) { $("#' . $element->getHtmlId() . '").css("background-color","#' . $value . '"); $("#' . $element->getHtmlId() . '").colpick({ layout:"hex", submit:0, colorScheme:"dark", color: "#' . $value . '", onChange:function(hsb,hex,rgb,el,bySetColor) { $(el).css("background-color","#"+hex); if(!bySetColor) $(el).val(hex); } }).keyup(function(){ $(this).colpickSetColor(this.value); }); }); }); </script>'; return $html; } }
Here the above block returns javascript from the ‘_ElementHtml’ method. This block is responsible for showing color pickers.
I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.