Score:1

How to refresh/rebuild block without reloading the page?

ru flag

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?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.