:::: MENU ::::
Monthly Archives: December 2018

Magento 2 Add Custom field at Product Form

This tutorial is about Magento 2 Add a Custom field at Product Edit Page method.Very often many developers face trouble and ask many questions about how to add a custom field/fieldset at product edit page in the Backend of Magento 2. This is a very important demand when you want to use extra information on your page which Magento 2 doesn’t include by default.Moving forward, this article would be the piece of writing you should definitely read.

I think i should break it in steps because that would be easy to understand.

Lets start with the step 1.

Create file etc\adminhtml\di.xml.This file will declare the module’s UI provider to Magento system.

<?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="customTab" xsi:type="array">
                    <item name="class" xsi:type="string">
            QaisarSatti\HelloWorld\Ui\DataProvider\Product\Form\Modifier\ExtraField
            </item>
                    <item name="sortOrder" xsi:type="number">70</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Step 2: Create

Ui\DataProvider\Product\Form\Modifier\NewField.php

.This class will create field and fieldset for you. Paste the below code in the created file

<?php
namespace QaisarSatti\HelloWorld\Ui\DataProvider\Product\Form\Modifier;
use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Ui\Component\Form\Fieldset;
use Magento\Ui\Component\Form\Field;
use Magento\Ui\Component\Form\Element\Select;
use Magento\Ui\Component\Form\Element\DataType\Text;
class ExtraField extends AbstractModifier
{
    private $locator;
    public function __construct(
        LocatorInterface $locator
    ) {
        $this->locator = $locator;
    }
    public function modifyData(array $data)
    {
        return $data;
    }
    public function modifyMeta(array $meta)
    {
        return $this->meta;
    }
}

Furthermore modifyMeta() – creating field, fieldset.

modifyData() – adding data when product edit page is loaded.

locator – getting product’s information by using $this->locator->getProduct().

For example, we create 1 fieldset and 1 field select yes/no, the content of modifyMeta will be as folllows:

 public function modifyMeta(array $meta)
    {
        $meta = array_replace_recursive(
            $meta,
            [
                'custom_fieldset' => [
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'label' => __(Custom Fieldset'),
                                '
componentType' => Fieldset::NAME,
                                '
dataScope' => 'data.product.custom_fieldset',
                                '
collapsible' => true,
                                '
sortOrder' => 5,
                            ],
                        ],
                    ],
                    '
children' => [
'
custom_field' => $this->getCustomField()
],
                ]
            ]
        );
        return $meta;
    }

Furthermore as we can see, 1 fieldset in product page edit with label “Custom Fieldset”, the fields in this fieldset will be listed in ‘children’ item as an array. We only need to add 1 field with id custom_field through a function getCustomfield().

 public function getCustomField()
    {
        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'label' => __('Custom Field'),
                        'componentType' => Field::NAME,
                        'formElement' => Select::NAME,
                        'dataScope' => 'enabled',
                        'dataType' => Text::NAME,
                        'sortOrder' => 10,
                        'options' => [
                            ['value' => '0', 'label' => __('No')],
                            ['value' => '1', 'label' => __('Yes')]
                        ],
                    ],
                ],
            ],
        ];
    }

Similarly, we can add the other fields such as text, checkbox, file upload, so on.

Furthermore, If you want to create Custom Text Field, please add the following code:

public function getCustomField()

{

     return [

         'arguments' => [

             'data' => [

                 'config' => [

                     'label' => __('Custom Field'),

                     'componentType' => Field::NAME,

                     'formElement' => \Magento\Ui\Component\Form\Element\Input::NAME,

                     'dataScope' => 'enabled',

                     'dataType' => Text::NAME,

                     'sortOrder' => 10,

                 ],

             ],

         ],

     ];

}

Furthermore to assign value to the newly created field, just insert the code as below

public function modifyData(array $data)

{

     $data = array_replace_recursive(

         $data,

         [

             $productId => [

                 'product' => [

                     'enabled' => 'your_value'

                 ]

             ]

         ]

     );

     return $data;
}

In a nutshell, with the Custom field/fieldset you can put extra product’s information as your desire and I hope that this tutorial will help you understand clearly about custom field/fieldset at Product edit page in Backend of Magento 2.

Similarly here i will just give you a glimpse of how to add the custom field inside the advance inventory is to declare Ui Component, I will keep it short to make it fast and easy:

In the\\view\adminhtml\ui_component\product_form.xml please add:

<?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">
    <modal name="advanced_inventory_modal">
        <fieldset name="stock_data">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Stock Configuration</item>
                    <item name="dataScope" xsi:type="string"/>
                    <item name="sortOrder" xsi:type="number">100</item>
                    <item name="collapsible" xsi:type="boolean">false</item>
                </item>
            </argument>
            <field name="custom_toggle">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="sortOrder" xsi:type="number">3000</item>
                        <item name="dataType" xsi:type="string">boolean</item>
                        <item name="formElement" xsi:type="string">checkbox</item>
                        <item name="source" xsi:type="string">category</item>
                        <item name="prefer" xsi:type="string">toggle</item>
                        <item name="label" xsi:type="string" translate="true">Custom Label</item>
                        <item name="notice" xsi:type="string">Custom description.</item>
                        <item name="valueMap" xsi:type="array">
                            <item name="true" xsi:type="string">1</item>
                            <item name="false" xsi:type="string">0</item>
                        </item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">false</item>
                        </item>
                        <item name="default" xsi:type="string">0</item>
                    </item>
                </argument>
            </field>
        </fieldset>
    </modal>
</form>

So, that’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 27, 2018


Magento 2 Color Picker in system configuration

This tutorial is about addingColor Picker in Magento 2 admin configuration. In this article I will show how to add jquery color picker in Magento 2 system configuration. You can use following step to use this jquery color picker on frontend too. Magento 2 have default lib/web/jquery/colorpicker/js/colorpicker library so you don’t have to add any external library for that. Below are the steps of how to do it:

Lets start with the Image to demonstrate you what it looks like:

Magento 2 color picker

Magento 2 color picker

Here my Module Namespace is QaisarSatti.
And my module name is: HelloWorld

Lets have have a look at different steps below:

1. Create system.xml at app/code/QaisarSatti/HelloWorld/etc/adminhtml/system.xml
All admin config options for your module will go in this file. For color picker we will create a text field as below. Just for your information i have not added complete code here for sake of readability.

    <field id="color_background" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
         <label>Background Color</label>
         <frontend_model>QaisarSatti\HelloWorld\Block\ColorPicker</frontend_model> <!-- block for adding color picker on text box -->
     </field>

2. Create the QaisarSatti\HelloWorld\Block\ColorPicker.php
This code will enable color picker options with the text box.

<?php

namespace QaisarSatti\HelloWorld\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 $currentelement = $("#'
. $element->getHtmlId() . '");
                    $currentelement.css("backgroundColor", "'
. $value .'");  //adding already selected value

                    // Attach the color picker
                    $currentelement.ColorPicker({
                        color: "'
. $value .'",
                        onChange: function (hsb, hex, rgb) {
                            $el.css("backgroundColor", "#" + hex).val("#" + hex);
                        }
                    });
                });
            });
            </script>'
;
        return $html;
    }

}

Now
3. Add the color picker JavaScript library.
Now finally we need to add color picker JavaScript library to admin config pages. Magento 2 by default is shipped with Color picker jQuery plugin. This plugin is present in lib/web/jquery/colorpicker/ folder.
Create the app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml. This layout file will be called on all admin configuration pages. We will add our color picker JavaScript and CSS to this layout.

<!-- File: app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml -->

<?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"/>
    </head>
</page>

Now clear the cache and refresh the page. You will see the color picker enabled in config option.

That’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 27, 2018