Adding Flag Count field to Search API Solr index

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.

/**
 * Get the flag count for a given node.
 */
function mymodule_get_count($entity, $options, $name, $entity_type, &$info) {
  // Requiring type node since we're relying on $entity->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.

Drupal Version Compatibility:

Comments

Nice, thanks for sharing!

I get this error

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=59&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fc.content_type' in 'where clause': SELECT fc.count AS count FROM {flag_counts} fc WHERE (fc.fid = :db_condition_placeholder_0) AND (fc.content_type = :db_condition_placeholder_1) AND (fc.content_id = :db_condition_placeholder_2) ; Array ( [:db_condition_placeholder_0] => 1 [:db_condition_placeholder_1] => node [:db_condition_placeholder_2] => 1 ) in as_flagcount_get_count() (line 15 of /PATH/TO/MODULE/as_flagcount.module).

How could I add something to the User Index?

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.