Question

How to add color picker in my custom module of Magento 2 admin panel form?

Not in System Configuration.

Was it helpful?

Solution

Never mind guys, I resolved the problem.

Step 1: app/code/Vendor/Module/Block/Adminhtml/Module/Edit/Tab/Main.php

//Replace your db field name with "color" 
 $field = $fieldset->addField(
       'color',
       'text',
       [
          'name' => 'color',
          'label' => __('Color'),
          'title' => __('Color')
        ]
 );
 $renderer = $this->getLayout()->createBlock('Vendor\Module\Block\Adminhtml\Color');
 $field->setRenderer($renderer);

Step 2: app/code/Vendor/Module/Block/Adminhtml/Color.php

<?php

namespace Vendor\Module\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;
    }

}

Finally, add Colorpicker CSS inside your module and put it in the head tag

Step 3: app/code/Vendor/Module/view/adminhtml/layout/module_index_edit.xml

<css src="jquery/colorpicker/css/colorpicker.css"/>

It's gonna work. You can see the color picker in your Admin Form.

Thanks :)

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top