Book Image

Magento 2 Development Cookbook

Book Image

Magento 2 Development Cookbook

Overview of this book

With the challenges of growing an online business, Magento 2 is an open source e-commerce platform with innumerable functionalities that gives you the freedom to make on-the-fly decisions. It allows you to customize multiple levels of security permissions and enhance the look and feel of your website, and thus gives you a personalized experience in promoting your business.
Table of Contents (13 chapters)
12
Index

Creating your own event


When we create our own event, we have to dispatch it with a custom name. In this recipe, you will learn how events are dispatched and what we can do with parameters that are sent with the event.

Getting ready

We will create an event that is fired when a visitor opens the /helloworld/index/event page.

The code in this recipe builds further on the Packt_HelloWorld module that we created in Chapter 4, Creating a Module, Chapter 5, Databases and Modules and Chapter 6, Magento Backend. Ensure that you have installed the start files.

How to do it...

The following steps describe how we can dispatch our own event:

  1. First, we will create the event page. For this, we need a controller action. Create the app/code/Packt/HelloWorld/Controller/Index/Event.php file with the following content:

    <?php
    namespace Packt\HelloWorld\Controller\Index;
    
    class Event extends \Magento\Framework\App\Action\Action {
      /** @var \Magento\Framework\View\Result\PageFactory  */
      protected $resultPageFactory...