1

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?

1 Answer 1

0

I was able to fix this by changing catalog_product_save_after to controller_action_catalog_product_save_entity_after in events.xml, and using the following code:

public function execute(Observer $observer)
    {
        $product = $observer->getData('product');
        $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]);
        }
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.