1

I have referenced a few different questions here and other articles online, but cannot for the life of me determine what is going wrong.

Referenced:

Context: Website is a multi-vendor marketplace. I'm looking to save a timestamp at the moment a new product is added to the catalog by a vendor.

Desired result: Upon a new product being created, the Observer will insert the datetime to a custom database table.

I understand this datetime is already stored in catalog_product_entity, but I need it saved in a separate table, as the datetime will be changed periodically for each product. The $vendorId portion can be ignored, which is why I'm simply using a static integer for that column until I'm able to get this working at all. Please also excuse the rudimentary method of saving said data to the table. Again, I know for a fact that method works elsewhere, which is why I'm using it here. To ensure that it's not the issue, but something else wider in scope.

Actual Result: Data is not inserted into the custom database table.

Files Namespace\Custom\etc\module.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
      <module name="Namespace_Custom" setup_version="0.0.1">
        <sequence>
             <module name="Magento_Catalog"/>
         </sequence>
      </module>
    </config>

Namespace\Custom\registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Namespace_Custom',
    __DIR__
);

Namespace\Custom\etc\adminhtml\events.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_new_action">
        <observer name="Namespace_Custom_Product_Save_After" instance="Namespace\Custom\Observer\Adminhtml\ProductSaveAfter" />
    </event>
</config>

Namespace\Custom\Observer\Adminhtml\ProductSaveAfter.php

    <?php

    namespace Namespace\Custom\Observer\Adminhtml;

    use Magento\Framework\Event\Observer;
    use Magento\Framework\Event\ObserverInterface;

    class ProductSaveAfter implements ObserverInterface
    {
      /**
       * @var ObjectManagerInterface
      */
       protected $_objectManager;

      /**
      * @param \Magento\Framework\ObjectManagerInterface $objectManager
      */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_objectManager = $objectManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
     
        $product = $observer->getEvent()->getProduct();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        if($product->isObjectNew()){
          $productId = $product->getId();        


          $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
          $connection = $resource->getConnection();
          $table = $resource->getTableName('catalog_product_custom');

          $query = "INSERT INTO " . $table . " (entity_id, vendor_id, date_time)
          VALUES ($productId, 99, UNIX_TIMESTAMP())";
          $connection->query($query);
        }

    }
}

I have also tried using catalog_product_edit_action event.

3
  • Could you check if your observer code fired or not? Or your observer code fired but not save the data into the database?
    – Tu Van
    Oct 26, 2022 at 20:08
  • @TuVan Using the profiler, I see the catalog_product_edit_action fired both on the vendor's side and in the admin panel, but no sign of my Observer (I did check this prior to changing to new_action). I'm not actually seeing catalog_product_new_action event being fired on either vendor or admin side.
    – taskle
    Oct 26, 2022 at 20:28
  • Yep, both events are not fit your need. catalog_product_new_action call when you go to "Create a new product" page, catalog_product_edit_action call when you go to "Edit a product" page. I'll write the answer to help you resolve your issue.
    – Tu Van
    Oct 26, 2022 at 20:34

1 Answer 1

1

You should use controller_action_catalog_product_save_entity_after event for product save after.

Change your events.xml to:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_catalog_product_save_entity_after">
        <observer name="Namespace_Custom_Product_Save_After" instance="Namespace\Custom\Observer\Adminhtml\ProductSaveAfter" />
    </event>
</config>

I've fixed some issues and improved your Observer class:

<?php

namespace Namespace\Custom\Observer\Adminhtml;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ProductSaveAfter implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resource;

    /**
     * @param \Magento\Framework\App\ResourceConnection $resource
     */
    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->resource = $resource;
    }

    public function execute(Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();

        if ($product->isObjectNew()) {
            $table = $this->resource->getTableName('catalog_product_custom');
            $now = new \DateTime();
            $createdAt = $now->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT);
            $vendorId = 99;
            $this->resource->getConnection()->insert(
                $table,
                ["entity_id" => $product->getId(), "vendor_id" => $vendorId, "date_time" => $createdAt]
            );
        }
    }
}

Remove generated folder and re compile code:

rm -rf generated
bin/magento setup:di:compile

You are done.

2
  • You're correct, that event is the one that's needed. Appreciate the better code for inserting the data as well.
    – taskle
    Oct 27, 2022 at 14:16
  • Glad to help you. Cheers!
    – Tu Van
    Oct 27, 2022 at 14:34

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.