Add Drupal 7 Flag/Unflag Links to View for All Available Actions

 

The view relationship for Flag module only allows you to set a single flag type as a target, which means only one flag type is available on a views row.

My specific use case is adding flag/unflag links to the /admin/content page which I've replaced by a view with the Admin Views module. I ended up digging around quite a bit through Flag module's source code to pop this one out.

The heart of it is in a views field template--one of your choosing. The code is agnostic as long as you have a the $row->nid field, and this specific code filters for just the node entity type, but you could use it for any of the other types readily.

<?php
  $flags = flag_get_flags();
  $links = array();
  foreach ($flags as $flag) {
    if ($flag->entity_type == 'node') {
      $links[] = flag_create_link($flag->name, $row->nid); // get links, if not possible ($flag->access($eid)), returns null.
    }
  }
  $links = array_values(array_filter($links));
?>
<div>
  <ul>
    <?php foreach ($links as $link) : ?>
      <li><?php print $link; ?></li>
    <?php endforeach; ?>
  </ul>
</div>

...and I wanted to stick it in a module rather than a theme, so I implemented this in my module to scan a subdir, templates, rather than shove it into the theme directory. Felt cleaner.

/**
 * Implements hook_views_api().
 *
 * Enabling using templates inside module
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'rs_contextual_links'),
    'template path' => drupal_get_path('module', 'rs_contextual_links') . '/templates',
  );
}

What I really wanted to do was implement a preprocess function to override $output for just this field type, but the preprocess function didn't exist without the template file declared. So why split the code up? Anyone know how to do that?

About the Author

Hi. My name is Jeremiah John. I'm a sf/f writer and activist.

I just completed a dystopian science fiction novel. I run a website which I created that connects farms with churches, mosques, and synagogues to buy fresh vegetables directly and distribute them on a sliding scale to those in need.

In 2003, I spent six months in prison for civil disobedience while working to close the School of the Americas, converting to Christianity, as one does, while I was in the clink.