For our custom module we have developed in magento 2. Some time we need to add a color picker field in admin panel custom form. This is some thing pretty simple task to handle by adding some extra code set to our custom module.
Assume we already have a custom module and we want to add a color picker field on the form.
Adding the field in main.php. ( app/code/Ayakil/Faq/Block/Adminhtml/Module/Edit/Tab/Main.php)
1 2 3 4 5 6 7 8 9 10 11 12 |
//Replace your database field name with "color_code" $field = $fieldset->addField( 'color_code', 'text', [ 'name' => 'color_code', 'label' => __('Color Code'), 'title' => __('Color Code') ] ); $renderer = $this->getLayout()->createBlock('Ayakil\Faq\Block\Adminhtml\Color'); $field->setRenderer($renderer); |
Creating the Color.php file – ( app/code/Ayakil/Faq/Block/Adminhtml/Color.php )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php namespace Ayakil\Faq\Block\Adminhtml; class Color extends \Magento\Config\Block\System\Config\Form\Field { /** * @param \Magento\Backend\Block\Template\Context $context * @param Registry $coreRegistry * @param array $data */ public function __construct( \Magento\Backend\Block\Template\Context $context, array $data = [] ) { parent::__construct($context, $data); } protected function _getElementHtml(\Magento\Framework\Data\Form\Element\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; } } |
Adding color-picker css in the custom module – ( app/code/Ayakil/Faq/view/adminhtml/layout/faq_index_edit.xml )
1 2 3 |
<head> <css src="jquery/colorpicker/css/colorpicker.css"/> </head> |
That’s all, you can see the color picker field in your admin panel custom form like below.

To view more articles visit the magento 2 section, graphql section
That’s it. Have a nice day.Enjoy coding , Learn , Experience , Teach and Help.
Outstanding post but I was wanting to know if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Thanks!
I really like and appreciate your blog article.Really looking forward to read more. Fantastic.
Thank you very much, Your appreciation motivated me a lot.
Like!! Great article post.Really thank you! Really Cool.