2

I'm trying to set an event that will launch function that loads some data from outside server and print it to javascript div element. I tried many ways but I can't figure out how to make this event be called only on for a specific node type.

Code I got so far:

class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onRespond',27]; //so far it works on respond but on every page
    return $events;
  }

  public function onRespond(FilterResponseEvent $event) {
    //do some stuff
  }

}

1 Answer 1

1

I managed to do it but I feel it could be done much better.

class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::TERMINATE][] = ['onRespond',27];
    return $events;
  }

  public function onRespond(PostResponseEvent $event) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $output = [];
    if (isset($node) && isset($name)) {

      $nodeType = $node->getType();
      $soap_response = new classThatHandleRequests();
      $output = $soap_response -> get_clients_fv($name);
      echo('<script>var JSONarray = ' . print_r($output,1) . ';</script>');
    }
  }
}
1
  • 1
    \Drupal calls should be avoided in classes, use dependency injection instead.
    – leymannx
    Nov 29, 2018 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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