Magento2 | PWA | GraphQL

Add colour picker option in product add/edit admin form Magento2


In this post you will learn about how to add colour picker option in the product add/edit admin form Magento2.


Let's start by creating a custom module.

Find the Complete module on Github at Magelearn_ProductColorPicker

Create folder in app/code/Magelearn/ProductColorPicker

Add registration.php file in it:
<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_ProductColorPicker', __DIR__);
Add composer.json file in it:
{
    "name": "magelearn/module-ProductColorPicker",
    "description": "Magento2 add colorpicker in product add/edit admin form",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\ProductColorPicker\\": ""
        }
    }
}
Add etc/module.xml file in it:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_ProductColorPicker" setup_version="1.0.0">
    </module>
</config>

Create InstallData script to add product colour picker attribute

Next, we will create a script to add `product_label_font_color`  attribute. So create a file at Magelearn/ProductColorPicker/Setup/InstallData.php
<?php
namespace Magelearn\ProductColorPicker\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Eav\Setup\EavSetupFactory;

/**
 * Class InstallData
 * @package Magelearn\Productattachement\Setup
 *
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * @var EavSetupFactory
     */
    protected $_eavSetupFactory;
    
    public function __construct(
        EavSetupFactory $eavSetupFactory
        ) {
            $this->_eavSetupFactory = $eavSetupFactory;
    }
    
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->_eavSetupFactory->create(["setup"=>$setup]);
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'product_label_font_color',
            [
                'group' => 'Content',
                'type' => 'text',
                'label' => 'Product Label Font Color',
                'input' => 'text',
                'frontend' => '',
                'class' => '',
                'source' => '',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => true,
                'unique' => false,
                'apply_to' => 'simple,configurable', // applicable for simple and configurable product
                'used_in_product_listing' => true
            ]
            );
    }
}

Now to display this colour picker attribute in Product edit form,
Create file at Magelearn/ProductColorPicker/view/adminhtml/ui_component/product_form.xml

<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="content">
        <field name="product_label_font_color" sortOrder="670" formElement="colorPicker">
            <settings>
                <label translate="true">Product Label Font Color</label>
                <componentType>colorPicker</componentType>
                <dataScope>product_label_font_color</dataScope>
                <dataType>text</dataType>
            </settings>
            <formElements>
                <colorPicker>
                    <settings>
                        <colorPickerMode>full</colorPickerMode>
                        <colorFormat>hex</colorFormat>
                    </settings>
                </colorPicker>
            </formElements>
        </field>
    </fieldset>
</form>

To Display this colour picker attribute properly on Product edit form we will modify product data provider form. 

Add file at Magelearn/ProductColorPicker/etc/adminhtml/di.xml

<?xml version="1.0" encoding="UTF-8"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="add_color_picker" xsi:type="array">
                    <item name="class" xsi:type="string">Magelearn\ProductColorPicker\Ui\DataProvider\Product\Form\Modifier\ColorPicker</item>
                    <item name="sortOrder" xsi:type="number">200</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Add the Data Provider class at Magelearn/ProductColorPicker/Ui/DataProvider/Product/Form/Modifier/ColorPicker.php

<?php

declare(strict_types = 1);

namespace Magelearn\ProductColorPicker\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;

class ColorPicker extends AbstractModifier
{
    /**
     * @param array $data
     *
     * @return array
     */
    public function modifyData(array $data): array
    {
        return $data;
    }

    /**
     * @param array $meta
     *
     * @return array
     */
    public function modifyMeta(array $meta): array
    {
        $codes = [
            'product_label_font_color'
        ];

        foreach ($codes as $code) {
            if (!isset($meta['content']['children']['container_' . $code])) {
                continue;
            }

            $meta['content']['children']['container_' . $code]['children'] = array_replace_recursive(
                $meta['content']['children']['container_' . $code]['children'],
                [
                    $code => [
                        'arguments' => [
                            'data' => [
                                'config' => [
                                    'visible' => 0,
                                ],
                            ]
                        ]
                    ]
                ]
            );
        }

        return $meta;
    }
}

Now colour picker attribute is now ready to use in your product Add/edit form.


Hope this article will help you to make any customization in your custom module.

0 Comments On "Add colour picker option in product add/edit admin form Magento2"

Back To Top