TransWikia.com

Action links available options / caching

Drupal Answers Asked by Marius Ilie on October 26, 2021

I have some action links defined in module.links.actions.yml which uses a custom “create entity” route. For entity creation I set up some restrictions and at some point the access is denied. The problem is that whilst the access to the page is denied, the action link is still visible until I clear all caches.

Is there a way to tell Drupal not to cache the links or to programmatically clear the links cache? Or some options I can add in the yml file to prevent caching?

Thanks.

One Answer

The following example implements an action link in Drupal 8 with the requirement of user-specific caching. This should allow you to hide/display the action link for the different users on your page. Providing different titles for different users should also work.

mymodule.links.action.yml:

entity.mymodule.add_form:
  class: DrupalmymodulePluginMenuLocalActionUserAction
  route_name: entity.mymodule.add_form
  title: 'Link to Add Form'
  appears_on:
    - entity.mymodule.collection

mymodule/src/Plugin/Menu/LocalAction/UserAction.php:

<?php

namespace DrupalrandomintroPluginMenuLocalAction;

use DrupalCoreMenuLocalActionDefault;
use SymfonyComponentDependencyInjectionContainerInterface;
use DrupalCoreSessionAccountInterface;
use DrupalCoreRoutingRouteProviderInterface;
use DrupalCoreRoutingRouteMatchInterface;

/**
 * Defines a test local action plugin class.
 */
class UserAction extends LocalActionDefault {

  /**
   * The current user.
   *
   * @var DrupalCoreSessionAccountInterface
   */
  protected $currentUser;


  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('router.route_provider'),
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return parent::getCacheContexts() + ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    // If the user is not Anonymous.
    if (!$this->currentUser->isAnonymous()) {
      // Getting the uid.
      $uid = $this->currentUser->id();
      // Adding the link.
      return ['user' => $uid];
    }
    return [];
  }

}

Answered by PhilippVerpoort on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP