PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

[FIXED] How to use events and observers in Magento 2

 August 23, 2022     magento2     No comments   

Issue

I want to track the Magento shop data by hooks the Magento events. I'm new in Magento2 so I don't know to hook the events and where to call an observer. I want to know how to call events which directory can we called. what hierarchy can be used? How to know the name of events?


Solution

Create a event file: events.xml

File: app/code/Vendor_Name/Module_Name/etc/frontend/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="checkout_cart_add_product_complete">
        <observer name="observername" instance="Vendor_Name\Module_Name\Observer\ObserverClass" />
    </event>
</config>

Create Observer class

File: app/code/Vendor_Name/Module_Name/Observer/ObserverClass.php

<?php

namespace Vendor_Name\Module_Name\Observer;

class ObserverClass implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        //Your code to run when event is fired.
        return 'Event fired';
    }
}

In above example, whenever event "checkout_cart_add_product_complete" is fired, the code inside Observer class will be executed.

To get a list of events available in Magento 2, you can visit : Link

Thanks, I hope this will help you. If you have any doubt or problem, feel free to ask in comment.



Answered By - Kapil Karangeeya
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing