Drupal 8 - Override content operations links

Drupal provides us Operations links field that we can use in our views. For example, we can have an operations links field in a view which is listing all music albums in table format, like following.

Entity operations

This allows us to perform different operations like edit, delete and translate on specified entity.

By default, operation links points to default drupal pages. But sometimes you want to modify this behavior and link to your custom page.

We can achieve this by using hook_entity_operation.

Suppose I want to modify the album edit operation and link it to my own page, but only for album content type. I can do it by implementing hook_entity_operation link following.

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;

/**
 * Implements hook_entity_operation().
 */
function music_entity_operation_alter(array &$operations, EntityInterface $entity) {
  if (!(\Drupal::currentUser()->hasPermission('access content'))) {
    return;
  }

  $entityTypeId = $entity->getEntityTypeId();
  // make sure we are modifying only node entity
  if ($entityTypeId !== 'node') {
    return;
  }

  $nodeType = $entity->getType();
  $nodeId = $entity->id();
  // make sure that we are modifying only album content type
  if ($nodeType === 'album') {
    // modify the url for album edit page, and use our own instead of default drupal page.
    $editUrl = Url::fromRoute('album.edit_form', ['node' => $nodeId]);
    $operations['edit']['url'] = $editUrl;
  }
}

Be aware that this hook will be executed for every entity type and not just for nodes. So it's important that you do checks to make sure that you modify the behavior only for required entity type. Similarly, you can target specific content type as well, as illustrated in above code.

Using hook_entity_operation, you can add your own custom operations as well in a similar way.

Reference


  PHP, Drupal 8