1

I need Quantity field to be filled with custom value when creating new product in admin. I have already tried modificators (haven't figured out how to set data for new product with modifyData($data) and this answer seems to be not working anymore.. Is there some way to do so?

Making an observer on event catalog_product_new_action and $observer->getEvent()->getProduct()->setQty(%number%) doesnt work either.

Cheers.

Kishan Savaliya
7,8451 gold badge14 silver badges29 bronze badges
asked Nov 21, 2019 at 13:38

1 Answer 1

1

You can create your own modifier pool in your custom extension to achieve this. Following files would do the work.

etc/adminhtml/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\DefaultQtyModifier</item>
 <item name="sortOrder" xsi:type="number">200</item>
 </item>
 </argument>
 </arguments>
 </virtualType>
</config>

Ui/DataProvider/Product/Form/Modifier/DefaultQtyModifier.php

<?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 DefaultQtyModifier extends AbstractModifier
{
 public function __construct(
 LocatorInterface $locator
 ) {
 $this->locator = $locator;
 }
 public function modifyData(array $data)
 {
 $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'] = 12;
 }
 return $data;
 }
 public function modifyMeta(array $meta)
 {
 return $meta;
 }
}

Here, instead of 12, you can defined your custom qty number.

Replace Vendor and Module with your original Vendor and Module name.

Hope this helps.

answered Nov 21, 2019 at 17:48
2
  • Thanks, it worked! I almost had it myself, but it wouldn't work until I moved di.xml to adminhtml/di.xml Commented Nov 22, 2019 at 6:33
  • You're welcome !!! Commented Nov 22, 2019 at 7:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.