The flagging events don't deal with responses, so you won't be able to return one from there. A different approach is to create a route subscriber, and alter the flag.action_link_flag
and flag.action_unlink_flag
routes, replacing the controller with your own custom one, e.g.
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('flag.action_link_flag')) {
$route->setDefault('_controller', 'Drupal\custom_module\Controller\CustomController::flag');
}
if ($route = $collection->get('flag.action_link_flag')) {
$route->setDefault('_controller', 'Drupal\custom_module\Controller\CustomController::unflag');
}
}
Your custom controller would extend the original flag controller (Drupal\flag\Controller\ActionLinkController
), use its methods to generate the original response, and then just tack your JS command(s) onto the end.
class CustomController extends ActionLinkController {
public function flag(FlagInterface $flag, $entity_id) {
$response = parent::flag($flag, $entity_id);
$response->addCommand(...);
return $response;
}
// Same for unflag()
}
For full coverage, you might also need to do something similar to the flag.action_link_flag_nojs
and flag.action_link_unflag_nojs
routes. But if your functionality is purely JS and doesn't need to be present for users without it, probably no need to bother.