Add Color Picker in Magento 2 Admin Configuration Options

Three years back I wrote an article on “How to Add Color Picker in Magento Admin Configuration Page“. Now it is 2016 and we are moving to Magento 2. In this article I will show how to add color picker in Magento 2 admin configuration page. Just like Magento 1 it is also very simple to do in Magento 2. Here are the steps of how to do it:

Magento 2 color picker
Magento 2 color picker

Our Module Namespace: Webspeaks
Module Name: Color

1. Create system.xml at app/code/Webspeaks/Color/etc/adminhtml/system.xml

All admin config options for your module will go in this file. For color picker we will create a text field as below.
Note: I have not added complete code for sake of readability.

<!-- File: app/code/Webspeaks/Color/etc/adminhtml/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>Webspeaks\Color\Block\Color</frontend_model> <!-- Our block for attaching color picker to text box -->
                </field>
            </group>
        </section>
    </system>
</config>

2. Create the Webspeaks\Color\Block\Color.php

This block will enable color picker options with the text box.

<?php
#File: app/code/Webspeaks/Color/Block/Color.php

namespace Webspeaks\Color\Block;

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"], 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;
    }

}

3. Add the color picker JavaScript library

Now finally we need to add color picker JavaScript library to admin config pages. Magento 2 by default is shipped with Color picker jQuery plugin. This plugin is present in lib/web/jquery/colorpicker/ folder.
Create the app/code/Webspeaks/Color/view/adminhtml/layout/adminhtml_system_config_edit.xml. This layout file will be called on all admin configuration pages. We will add our color picker JavaScript and CSS to this layout.

<!-- File: app/code/Webspeaks/Color/view/adminhtml/layout/adminhtml_system_config_edit.xml -->

<?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"/>
        <link src="jquery/colorpicker/js/colorpicker.js"/>
    </head>
</page>

See more about adding JavaScript and CSS in Magento 2 module.

Now clear the cache and refresh the page. You will see the color picker enabled ion config option.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

17 thoughts on “Add Color Picker in Magento 2 Admin Configuration Options

  1. Hey,
    Great tutorial

    i stack in this error on console log
    Uncaught TypeError: $el.ColorPicker is not a function(anonymous function) @

    any idea why?

    1. Ok its work after fix
      require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {

      but still , i get errors on console log

      what i did wrong?
      any idea?

    2. well its work but i had to delete the xml file because colorpicker.css and colorpicker.js are allrdy called .
      i use colorpicker on require command at Color.php and now its works 🙂
      Thanks

        1. yes but i really think people who used you tutorial will know that.

          Your choice 🙂

          By the way , i read your article on magento 2 with angualrjs2

          do you really think there is a place to implement AngularJS2 to M2?

          1. Yes,
            I got some workaround to use Angular2 with Magento 1.
            Although I haven't tried A2 with M2, but I feel there should not be any major problem in the integration.

      1. Hi,
        I changed my code like this require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {
        but still color picker not display ,

      2. How did you get rid of Uncaught Error: Mismatched anonymous define() module: function ($) in console log?? Please would you share??

  2. Very nice tutorial,
    Now working fine. i find my mistake, jQuery file is missing in this folder "…….\pub\static\adminhtml\Magento\backend\en_US\jquery\colorpicker\js"…..

    Thanks.:)

    1. Hi,
      You need to use require js to get rid of it. Change code like this:
      require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) { … })

      Also remove the JS from xml file.

  3. Hello Arvind,
    I have read your article. Thanks for the greate post.
    Can you please help me in adding custom tab in product admin and in that tab i want add options fields like in drop down fields. Please see screenshots http://prntscr.com/cf31do

    Thanks

Comments are closed.