6

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

Not in System Configuration.

7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.