Score:1

How to invoke a custom operation in Views

kz flag

I have a View that lists some nodes. Each node instance has a boolean - "Spam" - that defaults to FALSE.

In the view there is an "Operations" column where there shall be a link with the anchor text "Flag as spam". When the user clicks on that link, the value of the boolean Spam field for that node becomes "TRUE".

I found this tutorial: https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-add-a-column-with-dynamically-generated-action-buttons - but it is for Drupal 7.

However, what do I need to do to list a custom operation (with clickable link or button) in an "Operations" column produced by Views?

miststudent2011 avatar
fr flag
Maybe you can try like this https://drupal.stackexchange.com/questions/295329/custom-action-plugin-with-configurationform
sonfd avatar
in flag
Those are not "actions" they are "operations". Actions would be used for Views Bulk Operations.
Free Radical avatar
kz flag
@sonfd Thanks a lot for your correction. I've edited the question to use the correct terminology.
Score:1
in flag

Those are "operations". That view field is controlled by the EntityOperations field.

It's pretty easy to add a new operation for an entity by implementing hook_entity_operation.

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

/**
 * Implements hook_entity_operation().
 */
function mymodule_entity_operation(\Drupal\Core\Entity\EntityInterface $entity) {
  $operations = [];
  if ($entity->getEntityTypeId() == 'node' && someOtherCondition($entity)) {
    $operations['flag_as_spam'] = [
      'title' => t('Flag as Spam'),
      // Replace with the route you've created to set the node value.
      'url' => Url::fromRoute('entity.node.canonical', ['node' => $entity->id()]),
      'weight' => 50,
    ];
  }
  return $operations;
}
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.