Add Fields in Customizable option of products in admin


There are situations when we want to add an extra field in customizable options of products in admin to get our work done or to perform few more functionalities on products or on product Page/ while placing an order for a particular product.
Even with the help of this, we can set validation on particular products according to our needs.

So, Let Get Dig into this

But before this, we assume that one should have a basic knowledge about the module and its base structure, as its a core of our work. if not then please go to this Link.

Now as we are aware of the base module structure.

Let’s Get Started:

Here we will be adding our custom fields via phtml file, which we can include by injecting it into di.xml file by user preference.

But why we are using preference here, it’s just because we have to add additional fields in Magento core custom options for which preference is the best way to easily allow custom changes in our custom file, other than that we can also use plugins for this but for our work its a relevant way.
And for further clarification, one can prefer this too.

Above file have to be created at Vendor/Module/etc/adminhtml/di.xml
in our case its Excellence/Hello/etc/adminhtml/di.xml.

Now we have to create the file that we defined in the above preference at Excellence\Hello\Ui\DataProvider\Product\Form\Modifier\CustomOptions and write our custom code to add new fields.

In the above code, we have simply extended the core customoption.php file and after that have added our extra field of code in function getSelectTypeGridConfig().

static::FIELD_QTY_NAME => $this->getQtyFieldConfig(55),
static::FIELD_PRODUCT_SKU => $this->getProductSkuFieldConfig(51)

In both functions (getQtyFieldConfig(), getProductSkuFieldConfig()) we have added our code in which we have described our fields validations and names.

As for now, we have created functionality that will create fields in admin but to save their data we need to add their field name in catalog_product_option_type_value database table. To do this we have to update the catalog_product_option_type_value table in our database.

This could be done in two ways either by Creating InstallSchema.php file or by UpgradeSchema.php file at Vendor/Module/Setup.

We are using the UpgradeSchema.php file as we have already Installed module so for this we can simply upgrade our module version and the fields get added into the Database Table.
For further clarification on InstallSchema and UpgradeSchema, one can check on This.

In our case its Excellence/Hello/Setup

For new Instance, we can use InstallSchema.php.

In our case Its Excellence/Hello/Setup

Above we have updated our database using InstallSchema.php file

After That Just Run These Commands:
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean
php bin/magento cache:f

Finally, we get this on admin End: