How to add a color picker to custom admin form in magento 2?

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 it.

Adding the field in main.php. ( app/code/Ayakil/Faq/Block/Adminhtml/Module/Edit/Tab/Main.php)

//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 )

<?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 )

<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.

Color picker in Admin Form - Magento
Color picker in Admin Form – Magento

That’s it. Have a nice day.Enjoy coding , Learn , Experience , Teach and Help.

Leave a Reply

Your email address will not be published. Required fields are marked *