Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Adding Flag Count field to Search API Solr index

Parent Feed: 

Just a quick snippet!

Dropping this in a custom module will allow you to easily index values from the Flag module's {flag_count} table in a Search API Solr index.

nid,
  // but this could be used for user objects too.
  if ($entity_type == 'node') {
    $query = db_select('flag_counts' ,'fc');
    $query->fields('fc', array('count'));
    $query->condition('fc.fid', $info['data']['flag']->fid);
    $query->condition('fc.content_type', 'node');
    $query->condition('fc.content_id', $entity->nid);
    $count = $query->execute()->fetchColumn();
  }
  return !empty($count) ? $count : 0;
}

/**
* Implements hook_entity_property_info_alter().
*/
function mymodule_entity_property_info_alter(&$info) {
  if (isset($info['node']['bundles'])) {
    // For each content type.
    foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
      // Find all applicable flags for this content type.
      $flags = flag_get_flags('node', $bundle_type);
      // For each applicable flag.
      foreach ($flags as $fid => $flag) {
        $info['node']['bundles'][$bundle_type]['properties']['flag_' . $flag->name . '_count'] = array(
          'label' => t('@title Flag Count', array('@title' => $flag->title)),
          'description' => t('The total number of @title flags for this node.', array('@title' => $flag->title)),
          'type' => 'integer',
          'getter callback' => 'mymodule_get_count',
          'computed' => TRUE,
          'data' => array('flag' => $flag),
        );
      }
    }
  }
}
?>

After placing this in a custom module enabling, just go to the 'fields' tab on the desired Search API Solr index and select the 'flag_type Flag Count' field with type integer.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web