Magento 2 How to Add Custom Field in Custom Option

As we all know in Magento 2 customizable option is one of the most powerful and most convenient functionality. But, in some case developer needs to add few more custom fields in custom option at option-level for fulfilling their client's requirements but they don't know how to add custom options custom field in Magento 2. So, in this article, We are going to explain some simple steps.

Before we start I assume, you have already a created custom module. If you don't have it or don't know how to create it then check out our other article How To Create a Magento 2 Module.

Let's learn how to add custom option custom field in Magento 2?

Please follow bellow simple steps to Add Custom Field in Custom Option.

1. Create registration.php file at Vendor/Module/registration.php and paste the below code.

Copy
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

2. Create module.xml file at Vendor/Module/etc/module.xml and paste the below code.

Copy
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0">
		<sequence>
			<module name="Magento_Catalog"/>
		</sequence>
    </module>
</config>

Note: If you already have a module and implement this functionality in the existing module then don't forget to add Magento_Catalog in a sequence.

3. Create di.xml file at Vendor/Module/adminhtml/di.xml and paste the below code.

Copy
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<virtualType name="Magento\CatalogStaging\Ui\DataProvider\Product\Form\Modifier\Pool" type="Magento\Ui\DataProvider\Modifier\Pool">
		<arguments>
			<argument name="modifiers" xsi:type="array">
				<item name="new-modifier-all" xsi:type="array">
					<item name="class" xsi:type="string">Vendor\Module\Ui\DataProvider\Product\Form\Modifier\All</item>
					<item name="sortOrder" xsi:type="number">71</item>
				</item>
			</argument>
		</arguments>
	</virtualType>
	<virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool" type="Magento\Ui\DataProvider\Modifier\Pool">
		<arguments>
			<argument name="modifiers" xsi:type="array">
				<item name="new-modifier-all" xsi:type="array">
					<item name="class" xsi:type="string">Vendor\Module\Ui\DataProvider\Product\Form\Modifier\All</item>
					<item name="sortOrder" xsi:type="number">71</item>
				</item>
			</argument>
		</arguments>
	</virtualType>
	<virtualType name="Vendor\Module\Ui\DataProvider\Product\Form\Modifier\Pool" type="Magento\Ui\DataProvider\Modifier\Pool">
		<arguments>
			<argument name="modifiers" xsi:type="array">
			</argument>
		</arguments>
	</virtualType>
	<type name="Vendor\Module\Ui\DataProvider\Product\Form\Modifier\All">
		<arguments>
			<argument name="pool" xsi:type="object">Vendor\Module\Ui\DataProvider\Product\Form\Modifier\Pool</argument>
		</arguments>
	</type>
	<virtualType name="Vendor\Module\Ui\DataProvider\Product\Form\Modifier\Pool">
		<arguments>
			<argument name="modifiers" xsi:type="array">
				<item name="new-custom-option" xsi:type="array">
					<item name="class" xsi:type="string">Vendor\Module\Ui\DataProvider\Product\Form\Modifier\CustomOptions</item>
					<item name="sortOrder" xsi:type="number">72</item>
				</item>
			</argument>
		</arguments>
	</virtualType>
</config>

Now, it's time to create all the class files which we have mentioned in the above di.xml file. So, please follow the below steps and create all the files and add that code.

4. Create All.php file at Vendor/Module/Ui/DataProvider/Product/Form/Modifier/All.php and paste the below code.

Copy
<?php

namespace Vendor\Module\Ui\DataProvider\Product\Form\Modifier;

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

class All extends AbstractModifier implements ModifierInterface
{
    protected $pool;
    protected $meta = [];

    public function __construct(
        PoolInterface $pool
    ) {
        $this->pool = $pool;
    }

    public function modifyData(array $data)
    {
        foreach ($this->pool->getModifiersInstances() as $modifier) {
            $data = $modifier->modifyData($data);
        }

        return $data;
    }

    public function modifyMeta(array $meta)
    {
        $this->meta = $meta;

        foreach ($this->pool->getModifiersInstances() as $modifier) {
            $this->meta = $modifier->modifyMeta($this->meta);
        }

        return $this->meta;
    }
}

5. Create CustomOptions.php file at Vendor/Module/Ui/DataProvider/Product/Form/Modifier/CustomOptions.php and paste the below code.

Copy
<?php

namespace Vendor\Module\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions as CustomOptionsModifier;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Form\Element\Checkbox;
use Magento\Ui\Component\Form\Element\DataType\Text;
use Magento\Ui\Component\Form\Field;

class CustomOptions extends AbstractModifier
{
    protected $meta = [];

    public function __construct(
        UrlInterface $urlBuilder,
        LocatorInterface $locator,
        StoreManagerInterface $storeManager
    ) {
        $this->urlBuilder = $urlBuilder;
        $this->locator = $locator;
        $this->storeManager = $storeManager;
    }

    public function modifyData(array $data)
    {
        return $data;
    }

    public function modifyMeta(array $meta)
    {
        $this->meta = $meta;

        $this->addCustomOptionsFields();

        return $this->meta;
    }

    protected function addCustomOptionsFields()
    {
        $groupCustomOptionsName = CustomOptionsModifier::GROUP_CUSTOM_OPTIONS_NAME;
        $optionContainerName = CustomOptionsModifier::CONTAINER_OPTION;
        $commonOptionContainerName = CustomOptionsModifier::CONTAINER_COMMON_NAME;

        $this->meta[$groupCustomOptionsName]['children']['options']['children']['record']['children']
        [$optionContainerName]['children'][$commonOptionContainerName]['children'] = array_replace_recursive(
            $this->meta[$groupCustomOptionsName]['children']['options']['children']['record']['children']
            [$optionContainerName]['children'][$commonOptionContainerName]['children'],
            $this->getNewOptionFields()
        );
    }

    protected function getNewOptionFields()
    {
        $fields['new_field'] = $this->getNewFieldConfig(65);

        return $fields;
    }

    protected function getNewFieldConfig($sortOrder)
    {
        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'label' => __('New Field'),
                        'componentType' => Field::NAME,
                        'formElement' => Checkbox::NAME,
                        'dataScope' => 'new_field',
                        'dataType' => Text::NAME,
                        'sortOrder' => $sortOrder,
                        'valueMap' => [
                            'true' => '1',
                            'false' => '0',
                        ],
                    ],
                ],
            ],
        ];
    }
}

6. Create InstallSchema.php file at Vendor/Module/Setup/InstallSchema.php and paste the below code.

Copy
<?php

namespace Vendor\Module\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $tableName = $setup->getTable('catalog_product_option');
        if ($setup->getConnection()->isTableExists($tableName) == true) {
            $columns = [
                'new_field' => [
                    'type' => Table::TYPE_BOOLEAN,
                    'nullable' => false,
                    'default' => 0,
                    'comment' => 'New Field',
                ],
            ];
            $connection = $setup->getConnection();
            foreach ($columns as $name => $definition) {
                $connection->addColumn($tableName, $name, $definition);
            }
        }
        $installer->endSetup();
    }
}

7. Now install Module using the below commands

If your magento is running in a production mode then change it to developer mode before install this module.

Copy
php bin/magento deploy:mode:set developer
php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c

If you are a beginner and want to know more about Magento 2 Commands then check out our other article which is Useful Commands for Magento 2.

That’s it!

Now add new or edit any product from admin panel and check custom option custom field New Field is added in option level.

I hope this Magento article helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other handy commands which are not included in the list.

P.S. Do share this note with your team.




Search
Recent Posts
    Tags
    Newsletter
    SocialFollow on Twitter
    Visit now!