0

I would like to add a checkbox as an exposed filter to my view. When checked it will show all ndoes with 0 comments.

I looked at BEF but it didn't seem to be able to handle this. I also have another exposed filter for that view, otherwise I could just hide the filter and use jquery to toggle the url when checking the checkbox.

2
  • can u filter result without exposing? i mean if there is no filter, results shown with 0 comments nodes?
    – monymirza
    Mar 20, 2013 at 5:14
  • no, I would like to show all nodes and have the option to filter by nodes with 0 comments
    – uwe
    Mar 21, 2013 at 5:11

1 Answer 1

2

You can add your own filter trough a custom module. I was in need of the same thing. The following code should work.

<?php
/**
 * Implements hook_views_api()
 */
function my_module_views_api() {
  return array(
    'api' => 3,
  );
}



/**
* Implements hook_views_data().
*/
function mymodule_views_data() {

  // comment_count
  $data['node_comment_statistics']['has_comment'] = array(
    'title' => t('Has comment'),
    'real field' => 'comment_count',
    'help' => t('Filter to see if entity has comments.'),
    'filter' => array(
      'handler' => 'cjsm_ikz_handler_filter_has_comments',
    ),
  );

  return $data;
}

The next thing should be a filter in an include file.

<?php
/**
* @file
* Definition of mymodule_handler_filter_has_comments.
*/

/**
 * Simple filter to see if entity has comments or not.
 *
 * @ingroup views_filter_handlers
 */
class mymodule_handler_filter_has_comments extends views_handler_filter_boolean_operator {
  function query() {
    $this->ensure_my_table();
    $field = "$this->table_alias.$this->real_field";

    if (empty($this->value)) {
      if ($this->accept_null) {
        $or = db_or()
        ->condition($field, 0, '=')
        ->condition($field, NULL, 'IS NULL');
        $this->query->add_where($this->options['group'], $or);
      }
      else {
        $this->query->add_where($this->options['group'], $field, 0, '=');
      }
    }
    else {
      $this->query->add_where($this->options['group'], $field, 0, '<>');
    }
  }
}

For me this is providing a selectbox. Because I also want to be able to see nodes with and without comments at the same time. But it does exactly what you are looking for. If you are having trouble implementing this I suggest you search for the ins and outs of creating custom views filters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.