I am working in one of the project using the Flag module. I want to add custom event when user flag any content. I am trying to use hook_flag_flag() but it is not working. This is the code I am using in a module file.

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Drupal\flag\Plugin\Flag\EntityFlagType;
use Drupal\flag\FlagInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\Core\Session\AccountInterface;

function nppe_custom_flag_flag( $flag, $entity_id, $account, $flagging) {
  drupal_set_message("This is custom message after Flag.");

Is there anything I am missing?


To add some custom event on flag/unflag actions in Drupal 8 you need to use Event subscriber:

public static function getSubscribedEvents() {
    $events = [];
    $events[FlagEvents::ENTITY_FLAGGED][] = ['onFlag'];
    $events[FlagEvents::ENTITY_UNFLAGGED][] = ['onUnflag'];
    return $events;

And then in onFlag() and onUnflag() methods you can implement your custom logic.

I just wrote a blog post with some code examples: http://dev.studiopresent.com/blog/back-end/perform-actions-flag-unflag-drupal-8

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.