Magento2.1.9 : Out of stock product Backorder not working?Add product to quote when not in stockMagento 2:...

Blindfold battle as a gladiatorial spectacle - what are the tactics and communication methods?

Find some digits of factorial 17

Why do no American passenger airlines still operate dedicated cargo flights?

Eww, those bytes are gross

How to say "Brexit" in Latin?

Explain the objections to these measures against human trafficking

How to remove lines through the legend markers in ListPlot?

My cat mixes up the floors in my building. How can I help him?

If I deleted a game I lost the disc for, can I reinstall it digitally?

CREATE ASSEMBLY System.DirectoryServices.AccountManagement.dll without enabling TRUSTWORTHY

How long is the D&D Starter Set campaign?

Why did the villain in the first Men in Black movie care about Earth's Cockroaches?

What is the wife of a henpecked husband called?

It took me a lot of time to make this, pls like. (YouTube Comments #1)

How to solve a large system of linear algebra?

what does しにみえてる mean?

Which one of these password policies is more secure?

What are "industrial chops"?

Word or phrase for showing great skill at something WITHOUT formal training in it

How to limit sight distance to 1 km

Table formatting top left corner caption

What is the purpose of easy combat scenarios that don't need resource expenditure?

In Linux what happens if 1000 files in a directory are moved to another location while another 300 files were added to the source directory?

Caruana vs Carlsen game 10 (WCC) why not 18...Nxb6?



Magento2.1.9 : Out of stock product Backorder not working?


Add product to quote when not in stockMagento 2: Add a product to the cart programmaticallyMagento offline custom Payment method with drop down listCart page error in Magento 2.2.3How to solve Front controller reached 100 router match iterations in magento2Add configure product in Cart using Magento 2 API facing an issueUnable to save Stock ItemMagento 2.3 Can't view module's front end page output?Get Out of Stock products to show in magento 2.3get invoice item using order_item_id in magento 2













1















I have to used Magento2.1.9 when I add out of stock product to cart it is not working and am getting error as this product out of stock I need backorder working properly for out of stock product and I find, this is a bug in magento2.1.9 and applied patch after resolve issue but i am not getting patch file . So Ihave tried the other way override this file and add code below we are using.




MagentoCatalogInventoryModelQuoteItemQuantityValidatorQuantityValidator.php




<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="XXXXXXXXModelQuoteItemQuantityValidator" />
</config>


this is my code used QuantityValidator.php



    <?php
namespace XXXXXXXXXXModelQuoteItem;

use MagentoCatalogInventoryModelStock;

/**
* Quantity validation.
*/
class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator
{
protected $optionInitializer;

/**
* @var QuantityValidatorInitializerStockItem
*/
protected $stockItemInitializer;

/**
* Stock registry.
*
* @var MagentoCatalogInventoryApiStockRegistryInterface
*/
protected $stockRegistry;

/**
* Stock state.
*
* @var MagentoCatalogInventoryApiStockStateInterface
*/
protected $stockState;

/**
* @param QuantityValidatorInitializerOption $optionInitializer
* @param QuantityValidatorInitializerStockItem $stockItemInitializer
* @param MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry
* @param MagentoCatalogInventoryApiStockStateInterface $stockState
*/
public function __construct(
QuantityValidatorInitializerOption $optionInitializer,
QuantityValidatorInitializerStockItem $stockItemInitializer,
MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
MagentoCatalogInventoryApiStockStateInterface $stockState
) {


$this->optionInitializer = $optionInitializer;
$this->stockItemInitializer = $stockItemInitializer;
$this->stockRegistry = $stockRegistry;
$this->stockState = $stockState;
}

/**
* Check product inventory data when quote item quantity declaring
*
* @param MagentoFrameworkEventObserver $observer
*
* @return void
* @throws MagentoFrameworkExceptionLocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function validate(MagentoFrameworkEventObserver $observer)
{
/* @var $quoteItem MagentoQuoteModelQuoteItem */
$quoteItem = $observer->getEvent()->getItem();
if (!$quoteItem ||
!$quoteItem->getProductId() ||
!$quoteItem->getQuote() ||
$quoteItem->getQuote()->getIsSuperMode()
) {
return;
}
$product = $quoteItem->getProduct();
$qty = $quoteItem->getQty();

/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $this->stockRegistry->getStockItem(
$quoteItem->getProduct()->getId(),
$quoteItem->getProduct()->getStore()->getWebsiteId()
);

if (!$stockItem instanceof MagentoCatalogInventoryApiDataStockItemInterface) {
throw new MagentoFrameworkExceptionLocalizedException(__('The stock item for Product is not valid.'));
}

/** @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
$stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

/** @var MagentoCatalogInventoryApiDataStockStatusInterface|bool $parentStockStatus */
$parentStockStatus = false;

/**
* Check if product in stock. For composite products check base (parent) item stock status
*/
if ($quoteItem->getParentItem()) {
$product = $quoteItem->getParentItem()->getProduct();
$parentStockStatus = $this->stockRegistry->getStockStatus(
$product->getId(),
$product->getStore()->getWebsiteId()
);
}

if ($stockStatus) {
if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
|| $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
) {
$quoteItem->addErrorInfo(
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('This product is out of stock.')
);
$quoteItem->getQuote()->addErrorInfo(
'stock',
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('Some of the products are out of stock.')
);
return;
} else {
// Delete error from item and its quote, if it was set due to item out of stock
$this->_removeErrorsFromQuoteAndItem($quoteItem, MagentoCatalogInventoryHelperData::ERROR_QTY);
}
}
}
}
?>


after override this file in our module getting this



ReflectionException                                                                                                                                                               
Class XXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist


if anyone know reply me










share|improve this question

























  • Try the below answer, it will work

    – Prathap Gunasekaran
    32 mins ago
















1















I have to used Magento2.1.9 when I add out of stock product to cart it is not working and am getting error as this product out of stock I need backorder working properly for out of stock product and I find, this is a bug in magento2.1.9 and applied patch after resolve issue but i am not getting patch file . So Ihave tried the other way override this file and add code below we are using.




MagentoCatalogInventoryModelQuoteItemQuantityValidatorQuantityValidator.php




<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="XXXXXXXXModelQuoteItemQuantityValidator" />
</config>


this is my code used QuantityValidator.php



    <?php
namespace XXXXXXXXXXModelQuoteItem;

use MagentoCatalogInventoryModelStock;

/**
* Quantity validation.
*/
class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator
{
protected $optionInitializer;

/**
* @var QuantityValidatorInitializerStockItem
*/
protected $stockItemInitializer;

/**
* Stock registry.
*
* @var MagentoCatalogInventoryApiStockRegistryInterface
*/
protected $stockRegistry;

/**
* Stock state.
*
* @var MagentoCatalogInventoryApiStockStateInterface
*/
protected $stockState;

/**
* @param QuantityValidatorInitializerOption $optionInitializer
* @param QuantityValidatorInitializerStockItem $stockItemInitializer
* @param MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry
* @param MagentoCatalogInventoryApiStockStateInterface $stockState
*/
public function __construct(
QuantityValidatorInitializerOption $optionInitializer,
QuantityValidatorInitializerStockItem $stockItemInitializer,
MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
MagentoCatalogInventoryApiStockStateInterface $stockState
) {


$this->optionInitializer = $optionInitializer;
$this->stockItemInitializer = $stockItemInitializer;
$this->stockRegistry = $stockRegistry;
$this->stockState = $stockState;
}

/**
* Check product inventory data when quote item quantity declaring
*
* @param MagentoFrameworkEventObserver $observer
*
* @return void
* @throws MagentoFrameworkExceptionLocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function validate(MagentoFrameworkEventObserver $observer)
{
/* @var $quoteItem MagentoQuoteModelQuoteItem */
$quoteItem = $observer->getEvent()->getItem();
if (!$quoteItem ||
!$quoteItem->getProductId() ||
!$quoteItem->getQuote() ||
$quoteItem->getQuote()->getIsSuperMode()
) {
return;
}
$product = $quoteItem->getProduct();
$qty = $quoteItem->getQty();

/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $this->stockRegistry->getStockItem(
$quoteItem->getProduct()->getId(),
$quoteItem->getProduct()->getStore()->getWebsiteId()
);

if (!$stockItem instanceof MagentoCatalogInventoryApiDataStockItemInterface) {
throw new MagentoFrameworkExceptionLocalizedException(__('The stock item for Product is not valid.'));
}

/** @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
$stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

/** @var MagentoCatalogInventoryApiDataStockStatusInterface|bool $parentStockStatus */
$parentStockStatus = false;

/**
* Check if product in stock. For composite products check base (parent) item stock status
*/
if ($quoteItem->getParentItem()) {
$product = $quoteItem->getParentItem()->getProduct();
$parentStockStatus = $this->stockRegistry->getStockStatus(
$product->getId(),
$product->getStore()->getWebsiteId()
);
}

if ($stockStatus) {
if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
|| $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
) {
$quoteItem->addErrorInfo(
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('This product is out of stock.')
);
$quoteItem->getQuote()->addErrorInfo(
'stock',
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('Some of the products are out of stock.')
);
return;
} else {
// Delete error from item and its quote, if it was set due to item out of stock
$this->_removeErrorsFromQuoteAndItem($quoteItem, MagentoCatalogInventoryHelperData::ERROR_QTY);
}
}
}
}
?>


after override this file in our module getting this



ReflectionException                                                                                                                                                               
Class XXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist


if anyone know reply me










share|improve this question

























  • Try the below answer, it will work

    – Prathap Gunasekaran
    32 mins ago














1












1








1








I have to used Magento2.1.9 when I add out of stock product to cart it is not working and am getting error as this product out of stock I need backorder working properly for out of stock product and I find, this is a bug in magento2.1.9 and applied patch after resolve issue but i am not getting patch file . So Ihave tried the other way override this file and add code below we are using.




MagentoCatalogInventoryModelQuoteItemQuantityValidatorQuantityValidator.php




<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="XXXXXXXXModelQuoteItemQuantityValidator" />
</config>


this is my code used QuantityValidator.php



    <?php
namespace XXXXXXXXXXModelQuoteItem;

use MagentoCatalogInventoryModelStock;

/**
* Quantity validation.
*/
class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator
{
protected $optionInitializer;

/**
* @var QuantityValidatorInitializerStockItem
*/
protected $stockItemInitializer;

/**
* Stock registry.
*
* @var MagentoCatalogInventoryApiStockRegistryInterface
*/
protected $stockRegistry;

/**
* Stock state.
*
* @var MagentoCatalogInventoryApiStockStateInterface
*/
protected $stockState;

/**
* @param QuantityValidatorInitializerOption $optionInitializer
* @param QuantityValidatorInitializerStockItem $stockItemInitializer
* @param MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry
* @param MagentoCatalogInventoryApiStockStateInterface $stockState
*/
public function __construct(
QuantityValidatorInitializerOption $optionInitializer,
QuantityValidatorInitializerStockItem $stockItemInitializer,
MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
MagentoCatalogInventoryApiStockStateInterface $stockState
) {


$this->optionInitializer = $optionInitializer;
$this->stockItemInitializer = $stockItemInitializer;
$this->stockRegistry = $stockRegistry;
$this->stockState = $stockState;
}

/**
* Check product inventory data when quote item quantity declaring
*
* @param MagentoFrameworkEventObserver $observer
*
* @return void
* @throws MagentoFrameworkExceptionLocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function validate(MagentoFrameworkEventObserver $observer)
{
/* @var $quoteItem MagentoQuoteModelQuoteItem */
$quoteItem = $observer->getEvent()->getItem();
if (!$quoteItem ||
!$quoteItem->getProductId() ||
!$quoteItem->getQuote() ||
$quoteItem->getQuote()->getIsSuperMode()
) {
return;
}
$product = $quoteItem->getProduct();
$qty = $quoteItem->getQty();

/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $this->stockRegistry->getStockItem(
$quoteItem->getProduct()->getId(),
$quoteItem->getProduct()->getStore()->getWebsiteId()
);

if (!$stockItem instanceof MagentoCatalogInventoryApiDataStockItemInterface) {
throw new MagentoFrameworkExceptionLocalizedException(__('The stock item for Product is not valid.'));
}

/** @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
$stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

/** @var MagentoCatalogInventoryApiDataStockStatusInterface|bool $parentStockStatus */
$parentStockStatus = false;

/**
* Check if product in stock. For composite products check base (parent) item stock status
*/
if ($quoteItem->getParentItem()) {
$product = $quoteItem->getParentItem()->getProduct();
$parentStockStatus = $this->stockRegistry->getStockStatus(
$product->getId(),
$product->getStore()->getWebsiteId()
);
}

if ($stockStatus) {
if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
|| $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
) {
$quoteItem->addErrorInfo(
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('This product is out of stock.')
);
$quoteItem->getQuote()->addErrorInfo(
'stock',
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('Some of the products are out of stock.')
);
return;
} else {
// Delete error from item and its quote, if it was set due to item out of stock
$this->_removeErrorsFromQuoteAndItem($quoteItem, MagentoCatalogInventoryHelperData::ERROR_QTY);
}
}
}
}
?>


after override this file in our module getting this



ReflectionException                                                                                                                                                               
Class XXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist


if anyone know reply me










share|improve this question
















I have to used Magento2.1.9 when I add out of stock product to cart it is not working and am getting error as this product out of stock I need backorder working properly for out of stock product and I find, this is a bug in magento2.1.9 and applied patch after resolve issue but i am not getting patch file . So Ihave tried the other way override this file and add code below we are using.




MagentoCatalogInventoryModelQuoteItemQuantityValidatorQuantityValidator.php




<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="XXXXXXXXModelQuoteItemQuantityValidator" />
</config>


this is my code used QuantityValidator.php



    <?php
namespace XXXXXXXXXXModelQuoteItem;

use MagentoCatalogInventoryModelStock;

/**
* Quantity validation.
*/
class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator
{
protected $optionInitializer;

/**
* @var QuantityValidatorInitializerStockItem
*/
protected $stockItemInitializer;

/**
* Stock registry.
*
* @var MagentoCatalogInventoryApiStockRegistryInterface
*/
protected $stockRegistry;

/**
* Stock state.
*
* @var MagentoCatalogInventoryApiStockStateInterface
*/
protected $stockState;

/**
* @param QuantityValidatorInitializerOption $optionInitializer
* @param QuantityValidatorInitializerStockItem $stockItemInitializer
* @param MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry
* @param MagentoCatalogInventoryApiStockStateInterface $stockState
*/
public function __construct(
QuantityValidatorInitializerOption $optionInitializer,
QuantityValidatorInitializerStockItem $stockItemInitializer,
MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
MagentoCatalogInventoryApiStockStateInterface $stockState
) {


$this->optionInitializer = $optionInitializer;
$this->stockItemInitializer = $stockItemInitializer;
$this->stockRegistry = $stockRegistry;
$this->stockState = $stockState;
}

/**
* Check product inventory data when quote item quantity declaring
*
* @param MagentoFrameworkEventObserver $observer
*
* @return void
* @throws MagentoFrameworkExceptionLocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function validate(MagentoFrameworkEventObserver $observer)
{
/* @var $quoteItem MagentoQuoteModelQuoteItem */
$quoteItem = $observer->getEvent()->getItem();
if (!$quoteItem ||
!$quoteItem->getProductId() ||
!$quoteItem->getQuote() ||
$quoteItem->getQuote()->getIsSuperMode()
) {
return;
}
$product = $quoteItem->getProduct();
$qty = $quoteItem->getQty();

/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $this->stockRegistry->getStockItem(
$quoteItem->getProduct()->getId(),
$quoteItem->getProduct()->getStore()->getWebsiteId()
);

if (!$stockItem instanceof MagentoCatalogInventoryApiDataStockItemInterface) {
throw new MagentoFrameworkExceptionLocalizedException(__('The stock item for Product is not valid.'));
}

/** @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
$stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

/** @var MagentoCatalogInventoryApiDataStockStatusInterface|bool $parentStockStatus */
$parentStockStatus = false;

/**
* Check if product in stock. For composite products check base (parent) item stock status
*/
if ($quoteItem->getParentItem()) {
$product = $quoteItem->getParentItem()->getProduct();
$parentStockStatus = $this->stockRegistry->getStockStatus(
$product->getId(),
$product->getStore()->getWebsiteId()
);
}

if ($stockStatus) {
if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
|| $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
) {
$quoteItem->addErrorInfo(
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('This product is out of stock.')
);
$quoteItem->getQuote()->addErrorInfo(
'stock',
'cataloginventory',
MagentoCatalogInventoryHelperData::ERROR_QTY,
__('Some of the products are out of stock.')
);
return;
} else {
// Delete error from item and its quote, if it was set due to item out of stock
$this->_removeErrorsFromQuoteAndItem($quoteItem, MagentoCatalogInventoryHelperData::ERROR_QTY);
}
}
}
}
?>


after override this file in our module getting this



ReflectionException                                                                                                                                                               
Class XXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist


if anyone know reply me







magento2 out-of-stock backorder product-detail-page






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 42 mins ago







Rv Singh

















asked 1 hour ago









Rv SinghRv Singh

671417




671417













  • Try the below answer, it will work

    – Prathap Gunasekaran
    32 mins ago



















  • Try the below answer, it will work

    – Prathap Gunasekaran
    32 mins ago

















Try the below answer, it will work

– Prathap Gunasekaran
32 mins ago





Try the below answer, it will work

– Prathap Gunasekaran
32 mins ago










2 Answers
2






active

oldest

votes


















0














Problem in your __construct. Try the following way:



public function __construct(
MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption $optionInitializer,
MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem $stockItemInitializer,
MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
MagentoCatalogInventoryApiStockStateInterface $stockState
) {





share|improve this answer
























  • I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

    – Rv Singh
    28 mins ago













  • XXXXXXXXX is it your custom module name?

    – Sohel Rana
    26 mins ago











  • yes this is my custom module inside i try it

    – Rv Singh
    25 mins ago











  • i apply all command getting error

    – Rv Singh
    25 mins ago











  • That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

    – Sohel Rana
    23 mins ago



















0














Try this,




In your 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">
<preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="VendorModuleModelQuoteItemQuantityValidator" />
</config>


Place the code in the following path




Vendor/Module/Model/Quote/Item/QuantityValidator.php




<?php                                                                 
namespace VendorModuleModelQuoteItem;
use MagentoCatalogInventoryApiDataStockItemInterface;
use MagentoCatalogInventoryApiStockRegistryInterface;
use MagentoCatalogInventoryApiStockStateInterface;
use MagentoCatalogInventoryHelperData;
use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption;
use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem;
use MagentoCatalogInventoryModelStock;
use MagentoFrameworkEventObserver;
use MagentoFrameworkExceptionLocalizedException;
use MagentoQuoteModelQuoteItem;
class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator{
protected $optionInitializer;


protected $stockItemInitializer;


protected $stockRegistry;

protected $stockState;

public function __construct(
Option $optionInitializer,
StockItem $stockItemInitializer,
StockRegistryInterface $stockRegistry,
StockStateInterface $stockState
) {
parent::__construct(
$optionInitializer,
$stockItemInitializer,
$stockRegistry,
$stockState
);
$this->optionInitializer = $optionInitializer;
$this->stockItemInitializer = $stockItemInitializer;
$this->stockRegistry = $stockRegistry;
$this->stockState = $stockState;
}
private function addErrorInfoToQuote($result, $quoteItem)
{
$quoteItem->addErrorInfo(
'cataloginventory',
Data::ERROR_QTY,
$result->getMessage()
);

$quoteItem->getQuote()->addErrorInfo(
$result->getQuoteMessageIndex(),
'cataloginventory',
Data::ERROR_QTY,
$result->getQuoteMessage()
);
}

public function validate(Observer $observer)
{
/* @var $quoteItem Item */
$quoteItem = $observer->getEvent()->getItem();
if (!$quoteItem ||
!$quoteItem->getProductId() ||
!$quoteItem->getQuote()
) {
return;
}
$product = $quoteItem->getProduct();
$qty = $quoteItem->getQty();

/* @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
if (!$stockItem instanceof StockItemInterface) {
throw new LocalizedException(__('The Product stock item is invalid. Verify the stock item and try again.'));
}

if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
foreach ($options as $option) {
$this->optionInitializer->initialize($option, $quoteItem, $qty);
}
} else {
$this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
}

if ($quoteItem->getQuote()->getIsSuperMode()) {
return;
}

/* @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
$stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

/* @var MagentoCatalogInventoryApiDataStockStatusInterface $parentStockStatus */
$parentStockStatus = false;

/**
* Check if product in stock. For composite products check base (parent) item stock status
*/
if ($quoteItem->getParentItem()) {
$product = $quoteItem->getParentItem()->getProduct();
$parentStockStatus = $this->stockRegistry->getStockStatus(
$product->getId(),
$product->getStore()->getWebsiteId()
);
}

if ($stockStatus) {
if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
|| $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
) {
$quoteItem->addErrorInfo(
'cataloginventory',
Data::ERROR_QTY,
__('This product is out of stock.')
);
$quoteItem->getQuote()->addErrorInfo(
'stock',
'cataloginventory',
Data::ERROR_QTY,
__('Some of the products are out of stocksssss.')
);
return;
} else {
// Delete error from item and its quote, if it was set due to item out of stock
$this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
}
}

/**
* Check item for options
*/
if ($options) {
$qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
$quoteItem->setData('qty', $qty);
if ($stockStatus) {
$this->checkOptionsQtyIncrements($quoteItem, $options);
}

// variable to keep track if we have previously encountered an error in one of the options
$removeError = true;
foreach ($options as $option) {
$result = $option->getStockStateResult();
if ($result->getHasError()) {
$option->setHasError(true);
//Setting this to false, so no error statuses are cleared
$removeError = false;
$this->addErrorInfoToQuote($result, $quoteItem, $removeError);
}
}
if ($removeError) {
$this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
}
} else {
if ($quoteItem->getParentItem() === null) {
$result = $quoteItem->getStockStateResult();
if ($result->getHasError()) {
$this->addErrorInfoToQuote($result, $quoteItem);
} else {
$this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
}
}
}
}

/**
* Verifies product options quantity increments.
*
* @param Item $quoteItem
* @param array $options
* @return void
*/
private function checkOptionsQtyIncrements(Item $quoteItem, array $options): void
{
$removeErrors = true;
foreach ($options as $option) {
$result = $this->stockState->checkQtyIncrements(
$option->getProduct()->getId(),
$quoteItem->getData('qty'),
$option->getProduct()->getStore()->getWebsiteId()
);
if ($result->getHasError()) {
$quoteItem->getQuote()->addErrorInfo(
$result->getQuoteMessageIndex(),
'cataloginventory',
Data::ERROR_QTY_INCREMENTS,
$result->getQuoteMessage()
);

$removeErrors = false;
}
}

if ($removeErrors) {
// Delete error from item and its quote, if it was set due to qty problems
$this->_removeErrorsFromQuoteAndItem(
$quoteItem,
Data::ERROR_QTY_INCREMENTS
);
}
}

/**
* Removes error statuses from quote and item, set by this observer
*
* @param Item $item
* @param int $code
* @return void
*/
protected function _removeErrorsFromQuoteAndItem($item, $code)
{
if ($item->getHasError()) {
$params = ['origin' => 'cataloginventory', 'code' => $code];
$item->removeErrorInfosByParams($params);
}

$quote = $item->getQuote();
if ($quote->getHasError()) {
$quoteItems = $quote->getItemsCollection();
$canRemoveErrorFromQuote = true;
foreach ($quoteItems as $quoteItem) {
if ($quoteItem->getItemId() == $item->getItemId()) {
continue;
}

$errorInfos = $quoteItem->getErrorInfos();
foreach ($errorInfos as $errorInfo) {
if ($errorInfo['code'] == $code) {
$canRemoveErrorFromQuote = false;
break;
}
}

if (!$canRemoveErrorFromQuote) {
break;
}
}

if ($canRemoveErrorFromQuote) {
$params = ['origin' => 'cataloginventory', 'code' => $code];
$quote->removeErrorInfosByParams(null, $params);
}
}
}}


Hope this helps :)






share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "479"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f263944%2fmagento2-1-9-out-of-stock-product-backorder-not-working%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Problem in your __construct. Try the following way:



    public function __construct(
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption $optionInitializer,
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem $stockItemInitializer,
    MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
    MagentoCatalogInventoryApiStockStateInterface $stockState
    ) {





    share|improve this answer
























    • I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

      – Rv Singh
      28 mins ago













    • XXXXXXXXX is it your custom module name?

      – Sohel Rana
      26 mins ago











    • yes this is my custom module inside i try it

      – Rv Singh
      25 mins ago











    • i apply all command getting error

      – Rv Singh
      25 mins ago











    • That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

      – Sohel Rana
      23 mins ago
















    0














    Problem in your __construct. Try the following way:



    public function __construct(
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption $optionInitializer,
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem $stockItemInitializer,
    MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
    MagentoCatalogInventoryApiStockStateInterface $stockState
    ) {





    share|improve this answer
























    • I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

      – Rv Singh
      28 mins ago













    • XXXXXXXXX is it your custom module name?

      – Sohel Rana
      26 mins ago











    • yes this is my custom module inside i try it

      – Rv Singh
      25 mins ago











    • i apply all command getting error

      – Rv Singh
      25 mins ago











    • That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

      – Sohel Rana
      23 mins ago














    0












    0








    0







    Problem in your __construct. Try the following way:



    public function __construct(
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption $optionInitializer,
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem $stockItemInitializer,
    MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
    MagentoCatalogInventoryApiStockStateInterface $stockState
    ) {





    share|improve this answer













    Problem in your __construct. Try the following way:



    public function __construct(
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption $optionInitializer,
    MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem $stockItemInitializer,
    MagentoCatalogInventoryApiStockRegistryInterface $stockRegistry,
    MagentoCatalogInventoryApiStockStateInterface $stockState
    ) {






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 39 mins ago









    Sohel RanaSohel Rana

    22.2k34460




    22.2k34460













    • I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

      – Rv Singh
      28 mins ago













    • XXXXXXXXX is it your custom module name?

      – Sohel Rana
      26 mins ago











    • yes this is my custom module inside i try it

      – Rv Singh
      25 mins ago











    • i apply all command getting error

      – Rv Singh
      25 mins ago











    • That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

      – Sohel Rana
      23 mins ago



















    • I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

      – Rv Singh
      28 mins ago













    • XXXXXXXXX is it your custom module name?

      – Sohel Rana
      26 mins ago











    • yes this is my custom module inside i try it

      – Rv Singh
      25 mins ago











    • i apply all command getting error

      – Rv Singh
      25 mins ago











    • That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

      – Sohel Rana
      23 mins ago

















    I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

    – Rv Singh
    28 mins ago







    I apply this code but getting same error "ReflectionException Class XXXXXXXXXModelQuoteItemQuantityValidatorInitializerOption does not exist "

    – Rv Singh
    28 mins ago















    XXXXXXXXX is it your custom module name?

    – Sohel Rana
    26 mins ago





    XXXXXXXXX is it your custom module name?

    – Sohel Rana
    26 mins ago













    yes this is my custom module inside i try it

    – Rv Singh
    25 mins ago





    yes this is my custom module inside i try it

    – Rv Singh
    25 mins ago













    i apply all command getting error

    – Rv Singh
    25 mins ago





    i apply all command getting error

    – Rv Singh
    25 mins ago













    That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

    – Sohel Rana
    23 mins ago





    That does not make any sense why looking your module instead of MagentoCatalogInventory. Did you copied my answer without any change?

    – Sohel Rana
    23 mins ago













    0














    Try this,




    In your 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">
    <preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="VendorModuleModelQuoteItemQuantityValidator" />
    </config>


    Place the code in the following path




    Vendor/Module/Model/Quote/Item/QuantityValidator.php




    <?php                                                                 
    namespace VendorModuleModelQuoteItem;
    use MagentoCatalogInventoryApiDataStockItemInterface;
    use MagentoCatalogInventoryApiStockRegistryInterface;
    use MagentoCatalogInventoryApiStockStateInterface;
    use MagentoCatalogInventoryHelperData;
    use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption;
    use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem;
    use MagentoCatalogInventoryModelStock;
    use MagentoFrameworkEventObserver;
    use MagentoFrameworkExceptionLocalizedException;
    use MagentoQuoteModelQuoteItem;
    class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator{
    protected $optionInitializer;


    protected $stockItemInitializer;


    protected $stockRegistry;

    protected $stockState;

    public function __construct(
    Option $optionInitializer,
    StockItem $stockItemInitializer,
    StockRegistryInterface $stockRegistry,
    StockStateInterface $stockState
    ) {
    parent::__construct(
    $optionInitializer,
    $stockItemInitializer,
    $stockRegistry,
    $stockState
    );
    $this->optionInitializer = $optionInitializer;
    $this->stockItemInitializer = $stockItemInitializer;
    $this->stockRegistry = $stockRegistry;
    $this->stockState = $stockState;
    }
    private function addErrorInfoToQuote($result, $quoteItem)
    {
    $quoteItem->addErrorInfo(
    'cataloginventory',
    Data::ERROR_QTY,
    $result->getMessage()
    );

    $quoteItem->getQuote()->addErrorInfo(
    $result->getQuoteMessageIndex(),
    'cataloginventory',
    Data::ERROR_QTY,
    $result->getQuoteMessage()
    );
    }

    public function validate(Observer $observer)
    {
    /* @var $quoteItem Item */
    $quoteItem = $observer->getEvent()->getItem();
    if (!$quoteItem ||
    !$quoteItem->getProductId() ||
    !$quoteItem->getQuote()
    ) {
    return;
    }
    $product = $quoteItem->getProduct();
    $qty = $quoteItem->getQty();

    /* @var MagentoCatalogInventoryModelStockItem $stockItem */
    $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
    if (!$stockItem instanceof StockItemInterface) {
    throw new LocalizedException(__('The Product stock item is invalid. Verify the stock item and try again.'));
    }

    if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
    foreach ($options as $option) {
    $this->optionInitializer->initialize($option, $quoteItem, $qty);
    }
    } else {
    $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
    }

    if ($quoteItem->getQuote()->getIsSuperMode()) {
    return;
    }

    /* @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
    $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

    /* @var MagentoCatalogInventoryApiDataStockStatusInterface $parentStockStatus */
    $parentStockStatus = false;

    /**
    * Check if product in stock. For composite products check base (parent) item stock status
    */
    if ($quoteItem->getParentItem()) {
    $product = $quoteItem->getParentItem()->getProduct();
    $parentStockStatus = $this->stockRegistry->getStockStatus(
    $product->getId(),
    $product->getStore()->getWebsiteId()
    );
    }

    if ($stockStatus) {
    if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
    || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
    ) {
    $quoteItem->addErrorInfo(
    'cataloginventory',
    Data::ERROR_QTY,
    __('This product is out of stock.')
    );
    $quoteItem->getQuote()->addErrorInfo(
    'stock',
    'cataloginventory',
    Data::ERROR_QTY,
    __('Some of the products are out of stocksssss.')
    );
    return;
    } else {
    // Delete error from item and its quote, if it was set due to item out of stock
    $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
    }
    }

    /**
    * Check item for options
    */
    if ($options) {
    $qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
    $quoteItem->setData('qty', $qty);
    if ($stockStatus) {
    $this->checkOptionsQtyIncrements($quoteItem, $options);
    }

    // variable to keep track if we have previously encountered an error in one of the options
    $removeError = true;
    foreach ($options as $option) {
    $result = $option->getStockStateResult();
    if ($result->getHasError()) {
    $option->setHasError(true);
    //Setting this to false, so no error statuses are cleared
    $removeError = false;
    $this->addErrorInfoToQuote($result, $quoteItem, $removeError);
    }
    }
    if ($removeError) {
    $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
    }
    } else {
    if ($quoteItem->getParentItem() === null) {
    $result = $quoteItem->getStockStateResult();
    if ($result->getHasError()) {
    $this->addErrorInfoToQuote($result, $quoteItem);
    } else {
    $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
    }
    }
    }
    }

    /**
    * Verifies product options quantity increments.
    *
    * @param Item $quoteItem
    * @param array $options
    * @return void
    */
    private function checkOptionsQtyIncrements(Item $quoteItem, array $options): void
    {
    $removeErrors = true;
    foreach ($options as $option) {
    $result = $this->stockState->checkQtyIncrements(
    $option->getProduct()->getId(),
    $quoteItem->getData('qty'),
    $option->getProduct()->getStore()->getWebsiteId()
    );
    if ($result->getHasError()) {
    $quoteItem->getQuote()->addErrorInfo(
    $result->getQuoteMessageIndex(),
    'cataloginventory',
    Data::ERROR_QTY_INCREMENTS,
    $result->getQuoteMessage()
    );

    $removeErrors = false;
    }
    }

    if ($removeErrors) {
    // Delete error from item and its quote, if it was set due to qty problems
    $this->_removeErrorsFromQuoteAndItem(
    $quoteItem,
    Data::ERROR_QTY_INCREMENTS
    );
    }
    }

    /**
    * Removes error statuses from quote and item, set by this observer
    *
    * @param Item $item
    * @param int $code
    * @return void
    */
    protected function _removeErrorsFromQuoteAndItem($item, $code)
    {
    if ($item->getHasError()) {
    $params = ['origin' => 'cataloginventory', 'code' => $code];
    $item->removeErrorInfosByParams($params);
    }

    $quote = $item->getQuote();
    if ($quote->getHasError()) {
    $quoteItems = $quote->getItemsCollection();
    $canRemoveErrorFromQuote = true;
    foreach ($quoteItems as $quoteItem) {
    if ($quoteItem->getItemId() == $item->getItemId()) {
    continue;
    }

    $errorInfos = $quoteItem->getErrorInfos();
    foreach ($errorInfos as $errorInfo) {
    if ($errorInfo['code'] == $code) {
    $canRemoveErrorFromQuote = false;
    break;
    }
    }

    if (!$canRemoveErrorFromQuote) {
    break;
    }
    }

    if ($canRemoveErrorFromQuote) {
    $params = ['origin' => 'cataloginventory', 'code' => $code];
    $quote->removeErrorInfosByParams(null, $params);
    }
    }
    }}


    Hope this helps :)






    share|improve this answer




























      0














      Try this,




      In your 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">
      <preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="VendorModuleModelQuoteItemQuantityValidator" />
      </config>


      Place the code in the following path




      Vendor/Module/Model/Quote/Item/QuantityValidator.php




      <?php                                                                 
      namespace VendorModuleModelQuoteItem;
      use MagentoCatalogInventoryApiDataStockItemInterface;
      use MagentoCatalogInventoryApiStockRegistryInterface;
      use MagentoCatalogInventoryApiStockStateInterface;
      use MagentoCatalogInventoryHelperData;
      use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption;
      use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem;
      use MagentoCatalogInventoryModelStock;
      use MagentoFrameworkEventObserver;
      use MagentoFrameworkExceptionLocalizedException;
      use MagentoQuoteModelQuoteItem;
      class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator{
      protected $optionInitializer;


      protected $stockItemInitializer;


      protected $stockRegistry;

      protected $stockState;

      public function __construct(
      Option $optionInitializer,
      StockItem $stockItemInitializer,
      StockRegistryInterface $stockRegistry,
      StockStateInterface $stockState
      ) {
      parent::__construct(
      $optionInitializer,
      $stockItemInitializer,
      $stockRegistry,
      $stockState
      );
      $this->optionInitializer = $optionInitializer;
      $this->stockItemInitializer = $stockItemInitializer;
      $this->stockRegistry = $stockRegistry;
      $this->stockState = $stockState;
      }
      private function addErrorInfoToQuote($result, $quoteItem)
      {
      $quoteItem->addErrorInfo(
      'cataloginventory',
      Data::ERROR_QTY,
      $result->getMessage()
      );

      $quoteItem->getQuote()->addErrorInfo(
      $result->getQuoteMessageIndex(),
      'cataloginventory',
      Data::ERROR_QTY,
      $result->getQuoteMessage()
      );
      }

      public function validate(Observer $observer)
      {
      /* @var $quoteItem Item */
      $quoteItem = $observer->getEvent()->getItem();
      if (!$quoteItem ||
      !$quoteItem->getProductId() ||
      !$quoteItem->getQuote()
      ) {
      return;
      }
      $product = $quoteItem->getProduct();
      $qty = $quoteItem->getQty();

      /* @var MagentoCatalogInventoryModelStockItem $stockItem */
      $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
      if (!$stockItem instanceof StockItemInterface) {
      throw new LocalizedException(__('The Product stock item is invalid. Verify the stock item and try again.'));
      }

      if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
      foreach ($options as $option) {
      $this->optionInitializer->initialize($option, $quoteItem, $qty);
      }
      } else {
      $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
      }

      if ($quoteItem->getQuote()->getIsSuperMode()) {
      return;
      }

      /* @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
      $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

      /* @var MagentoCatalogInventoryApiDataStockStatusInterface $parentStockStatus */
      $parentStockStatus = false;

      /**
      * Check if product in stock. For composite products check base (parent) item stock status
      */
      if ($quoteItem->getParentItem()) {
      $product = $quoteItem->getParentItem()->getProduct();
      $parentStockStatus = $this->stockRegistry->getStockStatus(
      $product->getId(),
      $product->getStore()->getWebsiteId()
      );
      }

      if ($stockStatus) {
      if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
      || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
      ) {
      $quoteItem->addErrorInfo(
      'cataloginventory',
      Data::ERROR_QTY,
      __('This product is out of stock.')
      );
      $quoteItem->getQuote()->addErrorInfo(
      'stock',
      'cataloginventory',
      Data::ERROR_QTY,
      __('Some of the products are out of stocksssss.')
      );
      return;
      } else {
      // Delete error from item and its quote, if it was set due to item out of stock
      $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
      }
      }

      /**
      * Check item for options
      */
      if ($options) {
      $qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
      $quoteItem->setData('qty', $qty);
      if ($stockStatus) {
      $this->checkOptionsQtyIncrements($quoteItem, $options);
      }

      // variable to keep track if we have previously encountered an error in one of the options
      $removeError = true;
      foreach ($options as $option) {
      $result = $option->getStockStateResult();
      if ($result->getHasError()) {
      $option->setHasError(true);
      //Setting this to false, so no error statuses are cleared
      $removeError = false;
      $this->addErrorInfoToQuote($result, $quoteItem, $removeError);
      }
      }
      if ($removeError) {
      $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
      }
      } else {
      if ($quoteItem->getParentItem() === null) {
      $result = $quoteItem->getStockStateResult();
      if ($result->getHasError()) {
      $this->addErrorInfoToQuote($result, $quoteItem);
      } else {
      $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
      }
      }
      }
      }

      /**
      * Verifies product options quantity increments.
      *
      * @param Item $quoteItem
      * @param array $options
      * @return void
      */
      private function checkOptionsQtyIncrements(Item $quoteItem, array $options): void
      {
      $removeErrors = true;
      foreach ($options as $option) {
      $result = $this->stockState->checkQtyIncrements(
      $option->getProduct()->getId(),
      $quoteItem->getData('qty'),
      $option->getProduct()->getStore()->getWebsiteId()
      );
      if ($result->getHasError()) {
      $quoteItem->getQuote()->addErrorInfo(
      $result->getQuoteMessageIndex(),
      'cataloginventory',
      Data::ERROR_QTY_INCREMENTS,
      $result->getQuoteMessage()
      );

      $removeErrors = false;
      }
      }

      if ($removeErrors) {
      // Delete error from item and its quote, if it was set due to qty problems
      $this->_removeErrorsFromQuoteAndItem(
      $quoteItem,
      Data::ERROR_QTY_INCREMENTS
      );
      }
      }

      /**
      * Removes error statuses from quote and item, set by this observer
      *
      * @param Item $item
      * @param int $code
      * @return void
      */
      protected function _removeErrorsFromQuoteAndItem($item, $code)
      {
      if ($item->getHasError()) {
      $params = ['origin' => 'cataloginventory', 'code' => $code];
      $item->removeErrorInfosByParams($params);
      }

      $quote = $item->getQuote();
      if ($quote->getHasError()) {
      $quoteItems = $quote->getItemsCollection();
      $canRemoveErrorFromQuote = true;
      foreach ($quoteItems as $quoteItem) {
      if ($quoteItem->getItemId() == $item->getItemId()) {
      continue;
      }

      $errorInfos = $quoteItem->getErrorInfos();
      foreach ($errorInfos as $errorInfo) {
      if ($errorInfo['code'] == $code) {
      $canRemoveErrorFromQuote = false;
      break;
      }
      }

      if (!$canRemoveErrorFromQuote) {
      break;
      }
      }

      if ($canRemoveErrorFromQuote) {
      $params = ['origin' => 'cataloginventory', 'code' => $code];
      $quote->removeErrorInfosByParams(null, $params);
      }
      }
      }}


      Hope this helps :)






      share|improve this answer


























        0












        0








        0







        Try this,




        In your 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">
        <preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="VendorModuleModelQuoteItemQuantityValidator" />
        </config>


        Place the code in the following path




        Vendor/Module/Model/Quote/Item/QuantityValidator.php




        <?php                                                                 
        namespace VendorModuleModelQuoteItem;
        use MagentoCatalogInventoryApiDataStockItemInterface;
        use MagentoCatalogInventoryApiStockRegistryInterface;
        use MagentoCatalogInventoryApiStockStateInterface;
        use MagentoCatalogInventoryHelperData;
        use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption;
        use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem;
        use MagentoCatalogInventoryModelStock;
        use MagentoFrameworkEventObserver;
        use MagentoFrameworkExceptionLocalizedException;
        use MagentoQuoteModelQuoteItem;
        class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator{
        protected $optionInitializer;


        protected $stockItemInitializer;


        protected $stockRegistry;

        protected $stockState;

        public function __construct(
        Option $optionInitializer,
        StockItem $stockItemInitializer,
        StockRegistryInterface $stockRegistry,
        StockStateInterface $stockState
        ) {
        parent::__construct(
        $optionInitializer,
        $stockItemInitializer,
        $stockRegistry,
        $stockState
        );
        $this->optionInitializer = $optionInitializer;
        $this->stockItemInitializer = $stockItemInitializer;
        $this->stockRegistry = $stockRegistry;
        $this->stockState = $stockState;
        }
        private function addErrorInfoToQuote($result, $quoteItem)
        {
        $quoteItem->addErrorInfo(
        'cataloginventory',
        Data::ERROR_QTY,
        $result->getMessage()
        );

        $quoteItem->getQuote()->addErrorInfo(
        $result->getQuoteMessageIndex(),
        'cataloginventory',
        Data::ERROR_QTY,
        $result->getQuoteMessage()
        );
        }

        public function validate(Observer $observer)
        {
        /* @var $quoteItem Item */
        $quoteItem = $observer->getEvent()->getItem();
        if (!$quoteItem ||
        !$quoteItem->getProductId() ||
        !$quoteItem->getQuote()
        ) {
        return;
        }
        $product = $quoteItem->getProduct();
        $qty = $quoteItem->getQty();

        /* @var MagentoCatalogInventoryModelStockItem $stockItem */
        $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
        if (!$stockItem instanceof StockItemInterface) {
        throw new LocalizedException(__('The Product stock item is invalid. Verify the stock item and try again.'));
        }

        if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
        foreach ($options as $option) {
        $this->optionInitializer->initialize($option, $quoteItem, $qty);
        }
        } else {
        $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
        }

        if ($quoteItem->getQuote()->getIsSuperMode()) {
        return;
        }

        /* @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
        $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

        /* @var MagentoCatalogInventoryApiDataStockStatusInterface $parentStockStatus */
        $parentStockStatus = false;

        /**
        * Check if product in stock. For composite products check base (parent) item stock status
        */
        if ($quoteItem->getParentItem()) {
        $product = $quoteItem->getParentItem()->getProduct();
        $parentStockStatus = $this->stockRegistry->getStockStatus(
        $product->getId(),
        $product->getStore()->getWebsiteId()
        );
        }

        if ($stockStatus) {
        if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
        || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
        ) {
        $quoteItem->addErrorInfo(
        'cataloginventory',
        Data::ERROR_QTY,
        __('This product is out of stock.')
        );
        $quoteItem->getQuote()->addErrorInfo(
        'stock',
        'cataloginventory',
        Data::ERROR_QTY,
        __('Some of the products are out of stocksssss.')
        );
        return;
        } else {
        // Delete error from item and its quote, if it was set due to item out of stock
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        }

        /**
        * Check item for options
        */
        if ($options) {
        $qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
        $quoteItem->setData('qty', $qty);
        if ($stockStatus) {
        $this->checkOptionsQtyIncrements($quoteItem, $options);
        }

        // variable to keep track if we have previously encountered an error in one of the options
        $removeError = true;
        foreach ($options as $option) {
        $result = $option->getStockStateResult();
        if ($result->getHasError()) {
        $option->setHasError(true);
        //Setting this to false, so no error statuses are cleared
        $removeError = false;
        $this->addErrorInfoToQuote($result, $quoteItem, $removeError);
        }
        }
        if ($removeError) {
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        } else {
        if ($quoteItem->getParentItem() === null) {
        $result = $quoteItem->getStockStateResult();
        if ($result->getHasError()) {
        $this->addErrorInfoToQuote($result, $quoteItem);
        } else {
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        }
        }
        }

        /**
        * Verifies product options quantity increments.
        *
        * @param Item $quoteItem
        * @param array $options
        * @return void
        */
        private function checkOptionsQtyIncrements(Item $quoteItem, array $options): void
        {
        $removeErrors = true;
        foreach ($options as $option) {
        $result = $this->stockState->checkQtyIncrements(
        $option->getProduct()->getId(),
        $quoteItem->getData('qty'),
        $option->getProduct()->getStore()->getWebsiteId()
        );
        if ($result->getHasError()) {
        $quoteItem->getQuote()->addErrorInfo(
        $result->getQuoteMessageIndex(),
        'cataloginventory',
        Data::ERROR_QTY_INCREMENTS,
        $result->getQuoteMessage()
        );

        $removeErrors = false;
        }
        }

        if ($removeErrors) {
        // Delete error from item and its quote, if it was set due to qty problems
        $this->_removeErrorsFromQuoteAndItem(
        $quoteItem,
        Data::ERROR_QTY_INCREMENTS
        );
        }
        }

        /**
        * Removes error statuses from quote and item, set by this observer
        *
        * @param Item $item
        * @param int $code
        * @return void
        */
        protected function _removeErrorsFromQuoteAndItem($item, $code)
        {
        if ($item->getHasError()) {
        $params = ['origin' => 'cataloginventory', 'code' => $code];
        $item->removeErrorInfosByParams($params);
        }

        $quote = $item->getQuote();
        if ($quote->getHasError()) {
        $quoteItems = $quote->getItemsCollection();
        $canRemoveErrorFromQuote = true;
        foreach ($quoteItems as $quoteItem) {
        if ($quoteItem->getItemId() == $item->getItemId()) {
        continue;
        }

        $errorInfos = $quoteItem->getErrorInfos();
        foreach ($errorInfos as $errorInfo) {
        if ($errorInfo['code'] == $code) {
        $canRemoveErrorFromQuote = false;
        break;
        }
        }

        if (!$canRemoveErrorFromQuote) {
        break;
        }
        }

        if ($canRemoveErrorFromQuote) {
        $params = ['origin' => 'cataloginventory', 'code' => $code];
        $quote->removeErrorInfosByParams(null, $params);
        }
        }
        }}


        Hope this helps :)






        share|improve this answer













        Try this,




        In your 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">
        <preference for="MagentoCatalogInventoryModelQuoteItemQuantityValidator" type="VendorModuleModelQuoteItemQuantityValidator" />
        </config>


        Place the code in the following path




        Vendor/Module/Model/Quote/Item/QuantityValidator.php




        <?php                                                                 
        namespace VendorModuleModelQuoteItem;
        use MagentoCatalogInventoryApiDataStockItemInterface;
        use MagentoCatalogInventoryApiStockRegistryInterface;
        use MagentoCatalogInventoryApiStockStateInterface;
        use MagentoCatalogInventoryHelperData;
        use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerOption;
        use MagentoCatalogInventoryModelQuoteItemQuantityValidatorInitializerStockItem;
        use MagentoCatalogInventoryModelStock;
        use MagentoFrameworkEventObserver;
        use MagentoFrameworkExceptionLocalizedException;
        use MagentoQuoteModelQuoteItem;
        class QuantityValidator extends MagentoCatalogInventoryModelQuoteItemQuantityValidator{
        protected $optionInitializer;


        protected $stockItemInitializer;


        protected $stockRegistry;

        protected $stockState;

        public function __construct(
        Option $optionInitializer,
        StockItem $stockItemInitializer,
        StockRegistryInterface $stockRegistry,
        StockStateInterface $stockState
        ) {
        parent::__construct(
        $optionInitializer,
        $stockItemInitializer,
        $stockRegistry,
        $stockState
        );
        $this->optionInitializer = $optionInitializer;
        $this->stockItemInitializer = $stockItemInitializer;
        $this->stockRegistry = $stockRegistry;
        $this->stockState = $stockState;
        }
        private function addErrorInfoToQuote($result, $quoteItem)
        {
        $quoteItem->addErrorInfo(
        'cataloginventory',
        Data::ERROR_QTY,
        $result->getMessage()
        );

        $quoteItem->getQuote()->addErrorInfo(
        $result->getQuoteMessageIndex(),
        'cataloginventory',
        Data::ERROR_QTY,
        $result->getQuoteMessage()
        );
        }

        public function validate(Observer $observer)
        {
        /* @var $quoteItem Item */
        $quoteItem = $observer->getEvent()->getItem();
        if (!$quoteItem ||
        !$quoteItem->getProductId() ||
        !$quoteItem->getQuote()
        ) {
        return;
        }
        $product = $quoteItem->getProduct();
        $qty = $quoteItem->getQty();

        /* @var MagentoCatalogInventoryModelStockItem $stockItem */
        $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
        if (!$stockItem instanceof StockItemInterface) {
        throw new LocalizedException(__('The Product stock item is invalid. Verify the stock item and try again.'));
        }

        if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
        foreach ($options as $option) {
        $this->optionInitializer->initialize($option, $quoteItem, $qty);
        }
        } else {
        $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
        }

        if ($quoteItem->getQuote()->getIsSuperMode()) {
        return;
        }

        /* @var MagentoCatalogInventoryApiDataStockStatusInterface $stockStatus */
        $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

        /* @var MagentoCatalogInventoryApiDataStockStatusInterface $parentStockStatus */
        $parentStockStatus = false;

        /**
        * Check if product in stock. For composite products check base (parent) item stock status
        */
        if ($quoteItem->getParentItem()) {
        $product = $quoteItem->getParentItem()->getProduct();
        $parentStockStatus = $this->stockRegistry->getStockStatus(
        $product->getId(),
        $product->getStore()->getWebsiteId()
        );
        }

        if ($stockStatus) {
        if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
        || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
        ) {
        $quoteItem->addErrorInfo(
        'cataloginventory',
        Data::ERROR_QTY,
        __('This product is out of stock.')
        );
        $quoteItem->getQuote()->addErrorInfo(
        'stock',
        'cataloginventory',
        Data::ERROR_QTY,
        __('Some of the products are out of stocksssss.')
        );
        return;
        } else {
        // Delete error from item and its quote, if it was set due to item out of stock
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        }

        /**
        * Check item for options
        */
        if ($options) {
        $qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
        $quoteItem->setData('qty', $qty);
        if ($stockStatus) {
        $this->checkOptionsQtyIncrements($quoteItem, $options);
        }

        // variable to keep track if we have previously encountered an error in one of the options
        $removeError = true;
        foreach ($options as $option) {
        $result = $option->getStockStateResult();
        if ($result->getHasError()) {
        $option->setHasError(true);
        //Setting this to false, so no error statuses are cleared
        $removeError = false;
        $this->addErrorInfoToQuote($result, $quoteItem, $removeError);
        }
        }
        if ($removeError) {
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        } else {
        if ($quoteItem->getParentItem() === null) {
        $result = $quoteItem->getStockStateResult();
        if ($result->getHasError()) {
        $this->addErrorInfoToQuote($result, $quoteItem);
        } else {
        $this->_removeErrorsFromQuoteAndItem($quoteItem, Data::ERROR_QTY);
        }
        }
        }
        }

        /**
        * Verifies product options quantity increments.
        *
        * @param Item $quoteItem
        * @param array $options
        * @return void
        */
        private function checkOptionsQtyIncrements(Item $quoteItem, array $options): void
        {
        $removeErrors = true;
        foreach ($options as $option) {
        $result = $this->stockState->checkQtyIncrements(
        $option->getProduct()->getId(),
        $quoteItem->getData('qty'),
        $option->getProduct()->getStore()->getWebsiteId()
        );
        if ($result->getHasError()) {
        $quoteItem->getQuote()->addErrorInfo(
        $result->getQuoteMessageIndex(),
        'cataloginventory',
        Data::ERROR_QTY_INCREMENTS,
        $result->getQuoteMessage()
        );

        $removeErrors = false;
        }
        }

        if ($removeErrors) {
        // Delete error from item and its quote, if it was set due to qty problems
        $this->_removeErrorsFromQuoteAndItem(
        $quoteItem,
        Data::ERROR_QTY_INCREMENTS
        );
        }
        }

        /**
        * Removes error statuses from quote and item, set by this observer
        *
        * @param Item $item
        * @param int $code
        * @return void
        */
        protected function _removeErrorsFromQuoteAndItem($item, $code)
        {
        if ($item->getHasError()) {
        $params = ['origin' => 'cataloginventory', 'code' => $code];
        $item->removeErrorInfosByParams($params);
        }

        $quote = $item->getQuote();
        if ($quote->getHasError()) {
        $quoteItems = $quote->getItemsCollection();
        $canRemoveErrorFromQuote = true;
        foreach ($quoteItems as $quoteItem) {
        if ($quoteItem->getItemId() == $item->getItemId()) {
        continue;
        }

        $errorInfos = $quoteItem->getErrorInfos();
        foreach ($errorInfos as $errorInfo) {
        if ($errorInfo['code'] == $code) {
        $canRemoveErrorFromQuote = false;
        break;
        }
        }

        if (!$canRemoveErrorFromQuote) {
        break;
        }
        }

        if ($canRemoveErrorFromQuote) {
        $params = ['origin' => 'cataloginventory', 'code' => $code];
        $quote->removeErrorInfosByParams(null, $params);
        }
        }
        }}


        Hope this helps :)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 32 mins ago









        Prathap GunasekaranPrathap Gunasekaran

        663213




        663213






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f263944%2fmagento2-1-9-out-of-stock-product-backorder-not-working%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

            How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

            夢乃愛華...