Drupal 7 custom views 3 filter handler with reference

There are a lot of tutorials, snippets and examples out there to show how to create a custom views filter by using the base (node) field or by using an exposed custom table. But what about if you need a filter on a node listing, but using a related field?

So, in this example we have a view which shows a list of nodes of type 'news'. This content type has an entity reference to 'projects'. What we need is an exposed filter to filter the news by projects. But we dont' want every project to show up in the dropdown select list. We only want certain projects (in this case the certain "special" mean they have a a certain boolean fiels checkbox marked).

In this case, we don't want to use hook_views_data() but we need to use hook_views_alter() as described here. Other example can be found here.

/**
 * Implements of hook_views_api().
 */
function my_custom_views_api() {
  return array('api' => 3);
}

function my_custom_views_data_alter(&$data) {
  $data['field_data_field_ref_project']['project_select'] = array(
    'title' => t('Select list crowdfunding projecten'),
    'group' => t('Content'),
    'help' => t('Filter by special project, choosing from dropdown list.'),
    'real field' => 'field_ref_project_target_id',
    'filter' => array(
      'handler' => 'my_custom_handler_filter_project_select',
    ),
  );
}


/**
 * My custom filter handler
 */
class my_custom_handler_filter_project_select extends views_handler_filter_in_operator {


  function get_value_options() {

  // our field "field_special_status_value" is a single boolean checkbox field in content type project.

    $nids = db_select('field_data_field_special_status', 'fdfss')
      ->fields('fdfss', array('entity_id'))
      ->condition('fdfss.field_special_status_value', 1, '=')
      ->execute()
      ->fetchCol();
    $nodes = node_load_multiple($nids);


    if (!empty($nodes)) {

      foreach ($nodes as $node) {
        $projects[$node->nid] = $node->title;
      }

      // Sort by username.
      natsort($projects);

      $this->value_options = $projects;

      return $projects;
    }
  }

}

 

About

This is the company blog of
Drupal specialist Merge.nl

We are located in Breda (Netherlands) and build websites using Drupal. More about us.

Content on this blog is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.

Creative Commons License

Recent Comments

Social