Hello Magento Friends,
Spicing up your Magento 2 admin panel with a color picker for custom forms can significantly improve the user experience. Imagine admins easily selecting colors instead of manually entering hex codes! This blog will guide you through incorporating a color picker into your custom admin grid forms.
Step 1: Create layout_index_edit.xml file in given below path.
{{magento_root}}\app\code\Vendor\Extension\view\adminhtml\layout\layout_index_edit.xml
Then add the code as follows
<head> <css src="jquery/colorpicker/css/colorpicker.css"/> </head>
Step 2: Create Form.php file in given below path.
{{magento_root}}\app\code\Vendor\Extension\Block\Adminhtml\Grid\Edit\Form.php
Now, add the code as given below
//Replace your database field name with "field_name" $field = $fieldset->addField( 'field_name', 'text', [ 'name' => 'field_name', 'label' => __('Color Code'), 'title' => __('Color Code') ] ); $renderer = $this->getLayout()->createBlock('Vendor\Extension\Block\Adminhtml\Color'); $field->setRenderer($renderer);
Step 3: Create a Color.php file in the following path.
{{magento_root}}\app\code\Vendor\Extension\Block\Adminhtml\Color.php
And include the below code
<?php namespace Vendor\Extension\Block\Adminhtml; 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; } }
Output:
By following these steps, you have successfully added a color picker to a custom admin grid form in Magento 2. This enhancement can greatly improve the usability and efficiency of your admin interface, making it easier for administrators to select and manage colors.
Relevant Read –
Happy Coding!
Hello Magento Friends, In Magento 2, customizations to the admin panel can significantly enhance the…
Hello Magento Friends, Magento 2 provides a robust event-driven architecture that allows developers to observe…
Hyvä is gradually gaining popularity in this current market, and even 3.5% of Magento websites…
In today’s fast-paced society, where convenience and safety are paramount, curbside pickup has emerged as…
Have you ever observed how complementary and similar items are often displayed together in brick-and-mortar…
You may be familiar with Hyvä, the frontend theme for Magento 2, which has been…