When managing product quantities outside of Magento using an ERP system, it may be beneficial to prevent admin users from updating quantities from the Magento admin. One way to achieve this is by disabling the quantity text field on the edit product page in the Magento admin.
Steps to disabling product quantity text field on the Magento 2 admin
Step 1: Use the following code to include a phtml file in the product edit page of Magento 2 admin. Add the code to catalog_product_new.xml file, which can be created under your_module/view/adminhtml/layout/
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="js">
<block class="Magento\Framework\View\Element\Template" name="js.qty_disabler" template="Dhairvi_DisableQty::product/stock/disabler.phtml"/>
</referenceContainer>
</body>
</page>
Step 2: Add the below code to the disabler.phtml file. The location of that file is something /your_module/view/adminthml/templates/product/stock/
<script>
require(['jquery'], function($) {
window.afterOptionsInit = function() {
if (!jQuery('[data-index = quantity_and_stock_status_qty] input')[0]) {
setTimeout(function(){window.afterOptionsInit();}, 500);
return;
}
$( "[data-index = quantity_and_stock_status_qty] input" ).attr("disabled", "true");
$( "[data-index = quantity_and_stock_status_qty] .admin__field-group-additional" ).hide();
}
window.afterOptionsInit();
});
</script>
You may have to run setup upgrade command from SSH after this change and that’s it.
Checkout our blog post “Magento 2 Get Product by ID and SKU” to know all possible ways to fetch products programmatically in Magento 2

