3

I want to assign the color code to a particular customer group by the system.xml file. I have successfully created the grid, but I am facing difficulty adding the color picker in the color column of the config setting. For clarification see below image:

enter image description here

Let me know if anyone has done this functionality. Appreciate it in advance.

-1
  1. In your layout file of page where you want to add color picker, add below code:

     <head>
      <css src="jquery/colorpicker/css/colorpicker.css"/>
      <link src="jquery/colorpicker/js/colorpicker.js"/>
     </head>
    
  2. Create a block file in Block folder.

     <?php
         namespace Vendor\Module\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 $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. Change your code only for field like

    <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>Vendor\Module\Block\Color</frontend_model> <!-- Our block for attaching color picker to text box -->
     </field>
    
1
  • The above code will add color picker on a field in system.xml, not in the grid. See the attached image. – D Singh Jul 3 '20 at 5:47

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.