Magento version: 2.0.2


namespace Demo\Product\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class ProductObserver implements ObserverInterface
    public function execute(Observer $observer)
        /* @var $product \Magento\Catalog\Model\Product */
        $product = $observer->getEvent()->getProduct();
        if(!$product) {
            $product = 888;
        $data = array(
            'product' => $product,
            'value' => 333
        $myfile = fopen("/file_path/Observer.txt", "w");
        fwrite($myfile, print_r($data, true));


<?xml version="1.0"?>
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="owner_product_observer" instance="DianziBuy\Product\Observer\OwnerProductObserver" />

This is my custom observer code & events setting above. when i click the save button of product, there is no product data is written into file and got a blank page. So, what's wrong my code?


you are doing it right.
The only problem is that you are trying to write to the file something that's too big.

$product = $observer->getEvent()->getProduct(); returns an instance of the product being saved and that one contains a lot of info.
Try to limit your print to this

    $product = $observer->getEvent()->getProduct();
    $data = array(
        'product' => $product->getId(), //or $product->getName()
        'value' => 333
  • Hi I'm new to Magento 2.0.2. where I have to place these files. please give the path... – Codesen Mar 23 '16 at 9:17
  • I need to write observer for "checkout_cart_product_add_after". How can I add – Codesen Mar 23 '16 at 9:18
  • 1
    @Codesen like this -> stackoverflow.com/a/54157687/8520328 – Kowsigan Atsayam Jan 25 at 11:34

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.