0

Magento ver. 2.0.18

I created a custom module in backend there is color picker options.

for this i used this link color picker answer of @EmizenTech

it works perfectly but some time it gives and if i refresh the page error gone, in network i can see the jquery is loaded before the colorpicker.js

 index):421 Uncaught TypeError: $el.ColorPicker is not a function
        at HTMLDocument.<anonymous> ((index):421)
        at fire (jquery.js:3232)
        at Object.add [as done] (jquery.js:3291)
        at jQuery.fn.init.jQuery.fn.ready (jquery.js:3542)
        at (index):416
        at Object.execCb (require.js:1650)
        at Module.check (require.js:866)
        at Module.<anonymous> (require.js:1113)
        at require.js:132
        at require.js:1156

My /var/www/html/magentoce20/app/code/Companyname/ModuleName/Block/Color.php

<?php

namespace Companyname\ModuleName\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","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;
    }

}

My /var/www/html/magentoce20/app/code/Companyname/ModuleName/view/adminhtml/layout/adminhtml_system_config_edit.xml

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

My /var/www/html/magentoce20/app/code/Companyname/ModuleName/view/frontend/requirejs-config.js

var config = {

    deps: [
        "Companyname_ModuleName/js/main",
    ],


     map: {
        '*': {
            'slickjs': 'Companyname_ModuleName/js/slick/slick'

        }
    }

};

UPDATE : I just wrapped my colorpicker code in load so that html loads completely first and than js comes , i know require is doing same thing in magento 2 but currently this solves my issues. $(window).load(function() {

  • Sorry I reviewed example from core files and found out that alias is not needed. – Vivek Kumar Apr 4 '18 at 4:59
  • I think you should look into whether you have included the library in your corresponding layout xml . – Vivek Kumar Apr 4 '18 at 5:00
  • you are talking about adminhtml_system_config_edit.xml i shared the code above – inrsaurabh Apr 4 '18 at 5:08
0

Add the js file in head of adminhtml_system_config_edit.xml too. Update following code in your layout xml.

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  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>
| improve this answer | |
  • i read some where on SE that we should not include js directly in head and even if i included to check still problem is same that is some time error is thrown in console. – inrsaurabh Apr 4 '18 at 5:31
  • My extesnion is completed but stuck in QA just because of this , and i am not able to find any solution for this – inrsaurabh Apr 4 '18 at 5:32
  • can i wrap my color code in $(window).load(function() { } – inrsaurabh Apr 4 '18 at 11:14
  • I don't think it will help, but there is no reason to not try. – Vivek Kumar Apr 4 '18 at 15:32
  • This error come just because it loads before html is fully loaded I think, so is there any way to overcome other than . load ? – inrsaurabh Apr 4 '18 at 15:52
0

=> 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"/>
        <link src="jquery/colorpicker/js/colorpicker.js"/>
    </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 | |
  • @inrsaurabh check this solution it's 100% work. – Emipro Technologies Pvt. Ltd. Apr 5 '18 at 5:48
  • 1
    @emipro-technologies-pvt-ltd , thank you for your efforts and the code, but there is no difference in your method and the one suggested by vivek-kumar even most of the link suggest same except few dont suggest to add js in layout i this way ,they ask to do so using require and second as the color picker is already available in Mage 2 core do we need to include the same in our extension i am bit confused by reading different articles. – inrsaurabh Apr 9 '18 at 4:12

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.