From e06931b5c830e5afbd445e796886a5b79825b96d Mon Sep 17 00:00:00 2001
From: Alexei Gorobets <asgorobets@gmail.com>
Date: Thu, 6 Aug 2015 17:12:54 +0300
Subject: [PATCH] Issue #2411977 by asgorobets: Add support for flag links
 display in node links option

---
 flag.module | 39 +++++++++++++++++++++++++++++++++++++--
 1 file changed, 37 insertions(+), 2 deletions(-)

diff --git a/flag.module b/flag.module
index 03550c6..8661aa3 100644
--- a/flag.module
+++ b/flag.module
@@ -152,7 +152,42 @@ function flag_entity_extra_field_info() {
  * Implements hook_node_links_alter().
  */
 function flag_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
-  //@todo: Define this for handling the showOnLinks() flag mode.
+  // Get all possible flags for this entity type.
+  $flag_service = \Drupal::service('flag');
+  $flags = $flag_service->getFlags($entity->getEntityTypeID(), $entity->bundle());
+
+  foreach ($flags as $flag) {
+    // Do not display the flag if disabled.
+    if (!$flag->isEnabled()){
+      continue;
+    }
+
+    $link_type_plugin = $flag->getLinkTypePlugin();
+    $flag_type_plugin = $flag->getFlagTypePlugin();
+
+    // Only add cache key if flag link is displayed.
+    if ($flag_type_plugin->showInLinks($context['view_mode']) === 0) {
+      continue;
+    }
+
+    $action = 'flag';
+    if ($flag->isFlagged($entity)) {
+      $action = 'unflag';
+    }
+
+    // If the user does not have permission, go to the next foreach loop and
+    // don't display this flag.
+    if (!$flag->hasActionAccess($action)){
+      continue;
+    }
+
+    $link = $link_type_plugin->renderLink($action, $flag, $entity);
+    $links['node']['#links']['flag-' . $flag->get('id')] = [
+      'url' => $link['#url'],
+      "title" => $link['#title'],
+      "attributes" => $link["#attributes"],
+    ];
+  }
 }
 
 /**
@@ -182,7 +217,7 @@ function flag_entity_view(array &$build, EntityInterface $entity, EntityViewDisp
     $flag_type_plugin = $flag->getFlagTypePlugin();
 
     // Only add cache key if flag link is displayed.
-    if ($flag_type_plugin->showAsField() && !$display->getComponent('flag_' . $flag->id())) {
+    if (!$flag_type_plugin->showAsField() || !$display->getComponent('flag_' . $flag->id())) {
       continue;
     }
 
-- 
2.3.2 (Apple Git-55)

