Very often, we need to reduce the work of the admin. This post shows the code to add the default QTY while creating or editing products on the admin side.
We can see the default qty of the new product is zero; however, in certain situations, we need to change it to a specific number.
I will show how to save the default qty while editing or creating new products.
Add Default Qty While Editing Product
Step 1: Create di.xml to set modifier class using virtual type In Your Module
So, Let’s create the file di.xml.
<?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\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
<arguments>
<argument name="modifiers" xsi:type="array">
<item name="defaultQtyModifier" xsi:type="array">
<item name="class" xsi:type="string">Vendor\Module\Ui\DataProvider\Product\Form\Modifier\SetDefaultQtyModifier</item>
<item name="sortOrder" xsi:type="number">100</item>
</item>
</argument>
</arguments>
</virtualType>
</config>
Step 2: Create a SetDefaultQtyModifier class in the given path.
Create a Modifier class at the path mentioned in the file di.xml
<?php
namespace Vendor\Module\Ui\DataProvider\Product\Form\Modifier;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Catalog\Model\Locator\LocatorInterface;
class SetDefaultQtyModifier extends AbstractModifier
{
private const DEFAULT_QTY = 15;
/**
* @var LocatorInterface
*/
private LocatorInterface $locator;
/**
* Constructor
*
* @param LocatorInterface $locator
*/
public function __construct(
LocatorInterface $locator
) {
$this->locator = $locator;
}
/**
* Modify Data
*
* @param array $data
* @return array
*/
public function modifyData(array $data):array
{
$model = $this->locator->getProduct();
$modelId = $model->getId();
if (!isset($data[$modelId][self::DATA_SOURCE_DEFAULT]['quantity_and_stock_status']['qty'])) {
$data[$modelId][self::DATA_SOURCE_DEFAULT]['quantity_and_stock_status']['qty'] = self::DEFAULT_QTY;
}
return $data;
}
/**
* Modify Meta
*
* @param array $meta
* @return array
*/
public function modifyMeta(array $meta):array
{
return $meta;
}
}
That’s it; adding Default Qty While Editing a Product is easy.
Thanks for reading the post. Please share with your connection. Also, please use the comment box for your valuable suggestions.
You can visit the post to add multiple products to the cart.
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂