1

I am trying to add a color picker in magento 2.1.7 using below link but it's not going to work anyone tell me that how to add color picker in magento 2.1.7

https://webkul.com/blog/add-color-picker-magento2-system-config/

4

Add JavaScript color picker library in your layout :

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="jquery/colorpicker/css/colorpicker.css"/>
    </head>
</page>

Create system.xml

<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>abc\Color\Block\Color</frontend_model> <!-- Our block for attaching color picker to text box -->
                </field>
            </group>
        </section>
    </system>
</config>

Create the block file:

<?php
namespace abc\Color\Block;

class Color extends \Magento\Config\Block\System\Config\Form\Field {
    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 $elementId = $("#' . $element->getHtmlId() . '");
                    $elementId.css("backgroundColor", "'. $value .'");

                    $elementId.ColorPicker({
                        color: "'. $value .'",
                        onChange: function (hsb, hex, rgb) {
                            $elementId.css("backgroundColor", "#" + hex).val("#" + hex);
                        }
                    });
                });
            });
            </script>';
        return $html;
    }

}
| improve this answer | |
  • 2
    There is no need to add link src="jquery/colorpicker/js/colorpicker.js"/> in layout file...! @Rohan Hapani Thanks...! – Sanjay Gohil Aug 23 '17 at 13:26
  • ok sir... Happy to helping :) – Rohan Hapani Aug 23 '17 at 13:46
  • 1
    Its working for me. Thanks – sarvesh Dineshkumar Patel Nov 11 '19 at 6:40

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.