0

Ive made an observer for the catalog_product_save_after event, but I want to only fire it when a new product is added to the catalog.

I did the same for the sales_order_save_after event and just added this code:

$order = $observer->getEvent()->getOrder();

if($order->getState() == 'new') {
    $this->shipment->write($order);
}

Is there an equivalent to this when making a new product?

I tried with catalog_product_new_action but didnt get any product data then.

3

Check event observer in $productobject->getId() is already exist or not if not exist then consider it's new one.. and use catalog_product_save_before

  • Didnt think about doing it that way! Thank you sir. – Digitaq Apr 5 at 13:22
0

For future references, this is the code I ended up using:

Like @Himanshu said, use the catalog_product_save_before event for your observer.

class Productsaveafter implements ObserverInterface
{
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    )
    {
        $this->logger = $logger;
        $this->productRepository = $productRepository;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $productExists = true;

        try {
            //load product with sku since new products dont have an id yet
            $isExists = $this->productRepository->get($product->getSku());
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
            $productExists = false;
        }

        if($productExists == false) {
            $this->article->writeArt($product);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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