The user interface elements’ includes strategically playing with colors, font size, borders, background, navigational components and input controls. Colors have always been an effective way to manipulate the reader’s attention, by selecting appropriate colors for the frames in a commendable UI.
In the light of changing colors for background and fonts, the developer needs to hand over complete authority of the frontend UI to the admin. In order to perform this task, the coder needs to add color picker in Magento 2 Admin configuration.
The settings in a Magento 2 extension falls under stores à configuration and here you will find an option to add the color picker for changing the color in frontend UI.
Here are the most popular 3 ways enlisted to add a color picker feature in Magento 2 Admin Configuration.
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 ...> <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 $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 is ready to use. Now you can use this color picker anywhere in the entire Magento 2 to generate your own customized code when needed!
I hope you liked the article. Do share and post doubts, if any, we would be more than happy to solve them!