:::: MENU ::::

Magento Tutorial | Magento Blog | Learn Magento 2

Cookies Consent Popup

Magento 2 is built on a powerful event-driven architecture. This means you can hook into specific events and perform custom actions before or after certain operations. One common requirement is to run logic before inserting data into the database, such as modifying product attributes, validating customer data, or logging changes.

Understanding Events in Magento 2

Magento dispatches events at key points in its workflow. Developers can listen to these events using observers. For example:

  • catalog_product_save_before → Triggered before a product is saved.
  • customer_save_before → Triggered before a customer record is saved.
  • sales_order_place_before → Triggered before an order is placed.

By listening to these events, you can run custom logic before Magento inserts or updates records.

Step 1: Define events.xml

Inside your module, create etc/events.xml to register the observer:

<?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_save_before">
        <observer name="vendor_module_product_before_save"
                  instance="Vendor\Module\Observer\ProductBeforeSave" />
    </event>

</config>

This tells Magento to call your observer before a product is saved.

Step 2: Create the Observer Class

Now create the observer class in Vendor/Module/Observer/ProductBeforeSave.php:

<?php
namespace Vendor\Module\Observer;

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

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

        // Example: Add prefix to product name before saving
        $name = $product->getName();
        $product->setName('[Custom] ' . $name);

        // Example: Log action
        file_put_contents(BP . '/var/log/product_before_save.log',
            "Product " . $product->getSku() . " modified before save at " . date('Y-m-d H:i:s') . "\n",
            FILE_APPEND
        );
    }
}

This observer modifies the product name and logs the action before Magento inserts/updates the product record.

Other Useful Events

  • customer_save_before → Validate or modify customer data before insert.
  • sales_order_place_before → Add custom logic before order placement.
  • checkout_cart_product_add_after → Run logic after a product is added to cart.

Best Practices

  • Keep observer logic lightweight; avoid heavy operations that slow down saves.
  • Use dependency injection for services instead of direct file_put_contents.
  • Log actions for debugging, but disable verbose logging in production.
  • Test observers in development before deploying to production.

Conclusion

Magento 2’s event/observer system makes it easy to perform actions before inserting or saving data. By registering events in events.xml and writing observer classes, you can customize Magento’s behavior in a clean, upgrade‑safe way. This approach is ideal for adding validations, modifying attributes, or logging changes before data is persisted.

Happy Coding & Customizing!

0 comments:

Post a Comment