I have a custom block which displays the number of events added to favorites(Flag module). I am using the TWIG template to display those results. I want to refresh the block contents right after the user flags/unflags a node. Currently I can only get the updated value if I reload the page.
The build() looks like this:
class FavoritesBlock extends BlockBase
{
/**
* {@inheritdoc}
*/
public function getCacheMaxAge()
{
return 0;
}
public function build()
{
$uid = \Drupal::currentUser();
if ($uid->isAuthenticated()) {
$flag = \Drupal::service('flag')->getFlagById('favorites');
$count = \Drupal::service('flag.count')->getUserFlagFlaggingCount($flag, $uid);
$test = "Events added to favorites: " . $count;
$link_url = Url::fromUri("https://my-site/my-favorite-events");
$text = Link::fromTextAndUrl(t($test), $link_url)->toString();
}
return [
'#markup' => $text,
'#cache' => array(
'tags' => ['config:node_type_list'],
'max-age' => 0,
),
];
}
}
I also came upon the EventSubscriber which seems to be triggered exactly when I want, meaning on flagging/unflagging but I don't know if it is useful in this situation, I haven't much experience.
How could automatic block reload be achieved?