When a product is saved, I want to check if the product has an inventory source set, and if not, set one. The event name I'm observing is catalog_product_save_after
.
This is the Observer code:
class validateProductSources implements ObserverInterface
{
/**
* @var Http
*/
protected $request;
protected $productRepoInterface;
protected $sourceItemsBySku;
protected $_sourceItemsSaveInterface;
protected $_sourceItemFactory;
public function __construct(
Http $request,
ProductRepositoryInterface $productRepoInterface,
GetSourceItemsBySkuInterface $sourceItemsBySku,
SourceItemsSaveInterface $sourceItemsSaveInterface,
SourceItemInterfaceFactory $sourceItemFactory
)
{
$this->request = $request;
$this->productRepoInterface = $productRepoInterface;
$this->sourceItemsBySku = $sourceItemsBySku;
$this->_sourceItemsSaveInterface = $sourceItemsSaveInterface;
$this->_sourceItemFactory = $sourceItemFactory;
}
public function execute(Observer $observer)
{
$this->request->getParams();
$productId = $this->request->getParam('id');
$product = $this->productRepoInterface->getById($productId);
$sku = $product->getSku();
$sourceItems = $this->sourceItemsBySku->execute($sku);
if(!$sourceItems){
$sourceItem = $this->_sourceItemFactory->create();
$sourceItem->setSourceCode('default');
$sourceItem->setSku($sku);
$sourceItem->setQuantity(1);
$sourceItem->setStatus(1);
$this->_sourceItemsSaveInterface->execute([$sourceItem]);
}
}
}
The code is executed. I know this because I've tested it with the logger. The products source is not set though.
What baffles me is that if I use the same code in a controller (minus the request to get the product ID), the source is successfully set.
Could anyone tell me Why this happens, and how to fix it?