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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.