I am new to Magento 2 and trying to do a simple observer and event function for frontend (global to all module)
My understanding is that controller_action_predispatch
will be run before anything else.
Expectation: When I run any frontend site, eg: http://www.magentosite.com/xxx, an alert box will be displayed before any other action. when the user clicks ok on the alert box, only the page will be displayed.
But I can't see an alert box there. Hope someone can hint me which part did I implement wrongly or did I missing execute any command?
Update: Do I need to register my module (eg: add registration.php file)??? because I only actually have events.xml file and TestObserver.php inside the module name only currently?
app/code/Vendorname/Modulename/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="controller_action_predispatch">
<observer name="test" instance="Vendorname\Modulename\Observer\TestObserver" />
</event>
</config>
app/code/Vendorname/Modulename/Observer/TestObserver.php
<?php
namespace Vendorname\Modulename\Observer\TestObserver;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class TestObserver implements ObserverInterface
{
public function execute(Observer $observer)
{
echo "<script>javascript: alert('test msgbox')></script>";
}
}
?>
then run
php bin/magento cache:clean
php bin/magento cache:flush