Magento 2 Custom Module – Implement a Color Picker

magento2

In Magento 1.x I could use the included color picker by using the following form element:

$fieldset->addField('title_color', 'text', array(
      'label'     => Mage::helper('categorybanner')->__('Title Color'),
      'class'  => 'color {hash:true,required:false}',
      'required'  => false,
      'name'      => 'title_color',
  ));

Is there an included color picker element in Magento 2? If not how would I go about including a custom JS file on an admin grid?

Best Answer

Check out JSColor:

http://jscolor.com/

Its an open source and very easy to use Javascript library. All you have to do is import the library somewhere in your application, than you can simply create an input with the class "jscolor".

Get jscolor.js from above site and add inside Vendor/Modulename/view/adminhtml/web/js/jscolor.js

define js in your module xml head tag or create default.xml file inside Vendor/Modulename/view/adminhtml/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>      
        <script src="Vendor_Modulename::js/jscolor.js"/>
    </head>
</page>

Now set color picker in input like below:

$fieldset->addField('title_color', 'text', array(
      'label'     => __('Title Color'),
      'class'  => 'jscolor {hash:true,refine:false}',
      'required'  => false,
      'name'      => 'title_color',
  ));

This is working fine in magento 2.

Related Topic