Skip to main content

How to create custom events in drupal9?

In this section, we will learn how to define custom event, how to dispatch custom event and how to subscribe custom event. 

There will be following things which we we will see step wise step :

Step 1 :- Create modulename.info.yml file where filename is "drupal_custom_events.info.yml", here our module name is "drupal_custom_events".

name: Drupal Custom Events
type: module
description: 'This module will guide us about drupal events.'
package: Custom
version: 1.0
core_version_requirement: ^8 || ^9


Step 2 :- Create a routing file drupal_custom_events.routing.yml where we will define a route and call a form. 

drupal_custom_events.custom_event_dispatch_form:
  path: 'event_dispatch_form'
  defaults:
    _form:  '\Drupal\drupal_custom_events\Form\CustomEventDispatchForm'
    _title: 'Event Dispatch Form'
  requirements:
    _permission: 'administrator'


Step 3:- Create a Events folder inside src folder then create a file "CustomEvent.php". This file tell us about our custom event. "CUSTOM_FORM_SUBMIT" is our custom event name.

<?php

namespace Drupal\drupal_custom_events\Events;

use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Custom Events will be fired.
 */
class CustomEvent extends Event {
  const CUSTOM_FORM_SUBMIT = 'custom_form_submit';

  /**
   * A Reference ID
   */
  public $referenceId;

  /**
   * Constructs the object.
   *
   */
  public function __construct($referenceId) {
    $this->referenceId = $referenceId;
  }

  /**
   * getReferenceId()
   */
  public function getReferenceId() {
    return $this->referenceId;
  }

  /**
   * getEventDescription()
   */
  public function getEventDescription() {
    return "This is custom event!";
  } 

}

Step 4:- Create a "Form" folder inside src folder then give filename "CustomEventDispatchForm.php" according to our routing file. When this form will submit then we dispatch custom event.

<?php

namespace Drupal\drupal_custom_events\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\drupal_custom_events\Events\CustomEvent;

/**
 * Class CustomEventDispatchForm.
 */
class CustomEventDispatchForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_event_dispatch_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Reference'),
      '#description' => $this->t('Type any name here that will set event object, while subscribing it.'),
      '#maxlength' => 64,
      '#size' => 64,
    ];

    $form['dispatch'] = [
      '#type' => 'submit',
      '#value' => $this->t('Dispatch'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // How to dispatch an event in drupal 9
    $dispatcher = \Drupal::service('event_dispatcher');
    $event = new CustomEvent($form_state->getValue('name'));
    $dispatcher->dispatch(CustomEvent::CUSTOM_FORM_SUBMIT, $event);
  }
}

Step 5:- Create a drupal_custom_events.services.yml file for services where we will create a service for dispatch custom event.

services:
  # Name of this service.
  # Subscriber to the event we dispatch in custom event dispatch form submit, with dependencies injected.
  custom_event_subscriber:
    class: '\Drupal\drupal_custom_events\EventSubscriber\CustomEventSubscriber'
    arguments: 
      - '@messenger'
    tags:
      - { name: 'event_subscriber' }

Step 6:- Create a folder "EventSubscriber" inside src folder then give filename "CustomEventSubscriber.php" for subcribing events when custom form will submit

<?php

namespace Drupal\drupal_custom_events\EventSubscriber;

use Drupal\drupal_custom_events\Events\CustomEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Messenger\MessengerInterface;

/**
 * Class CustomEventSubscriber.
 *
 * @package Drupal\drupal_custom_events\EventSubscriber
 */
class CustomEventSubscriber implements EventSubscriberInterface {
  /**
   * Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

   /**
   * CustomEventSubscriber constructor.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   Messenger.
   */
  public function __construct(MessengerInterface $messenger) {
    $this->messenger = $messenger;
  }  

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      CustomEvent::CUSTOM_FORM_SUBMIT => 'onEventDispatchFormSubmit',
    ];
  }

  /**
   * This will react on custom event dispatched.
   */
  public function onEventDispatchFormSubmit(CustomEvent $event) {
    $this->messenger->addStatus(t('The custom event has been subscribed, which has been dispatch on CustomEventDispatchForm submit with '.$event->getReferenceId()." as Reference"));
  }
}


Comments

Post a Comment

Popular posts from this blog

How to configure memcache with drupal 8 on ubuntu for reduce page load?

Memcache is an in-memory (RAM). It store data in Key-Value Format. Memcached server automatically stores all the content (data) in allocated RAM on the server. After configure memcache, it increase Drupal Site performance by moving standard caches out of the database. Drupal does not come with memcache by default if we want to install it then we have to install it on server. There are many steps that how to install memcache on the server and how to configure it with drupal 8 for reducing the load on the database with every page request. Step1 :- Open terminal of your machine and run following commands :- a. sudo apt-get update b. sudo apt install memcached c. sudo apt install php-memcached Step2 :- Check that Memcache daemon is working by using the following command : a. "ps aus | grep memcached" Step3 :- Also, check Memcache extension is configured in PHP. For that you have create a file phpinfo.php then write below code. <?php phpinfo(); ?> or sudo vi /var/www/html...

How deploy your angular project on GitHub Pages

Step 1:- Create Repository on github Note :- Open terminal and goto your project direcoty then run following command which you got after created repository. Step 2:- git init Step 3:- git add . Step 4:- git commit -m "first commit" Step 5:- git branch -M main Step 6:- git remote add origin https://github.com/rahuldrupal5788/DevR9angular.git Step 7:- git push -u origin main Step 8:- We need to build our code in production mode for that we will create deployment files that will be deployed on GitHub Pages. By default, this deployment code is generated in the /dist/<ProdectName> folder under the angular project folder, but we need to generate this in the "docs" folder under the angular project folder. So, we need to make a small change in the angular.json file and change the outputpath value to "docs/". Step 9:- Run the following command with the baseHref  option in the git bash window to generate deployment files in the docs folder. ng build --prod --b...

What is Docker? How to create Dockerfile, Volumes? How to manage container with Port Mapping?

What is Docker? Docker is an open source centerlized Platform designed to Create, Deploy and run applications. Docker use container on the host OS to run applications. It allows application to use the same linux Kernal as a System on the host computer, rather than creating a whole virtual OS. We can install docker on any OS but Docker engine run natively on linux distribution. Docker written in 'go' language. Docker is a tool that perform OS level virtualization, also known as Containerization. Before Docker, many users faces the problem that a particular Code is running in  the developer's system but not in the User's System. Docker was first Release in March 2013. It is developed by Soloman Hykes and Sebastion Pahl. Docker is a set of Platform as a service that uses OS level Virtualization whereas VMware uses Hardware level Virtualization. We can say that Docker is a tools which create the VM. Advantages of Docker :- There are following advantage of Docker : No pre-a...