Adding a Custom Filter to Views in Drupal 7

im using Drupal 7 and I want to add a new filter to the views.

I have a custom clicks table with two fields; nid and clicks_left.

The filter should contain only the "Show only nodes with left clicks" checkbox. Therefore, the filter should join the node and click on nid ..

I read like thousands of pages of custom filters, but can't get it working =)

Please, can someone show me a working example so that I understand?

I got to the point that the filter appears under the filters, but what do I need to add to make the connection and check the box? Relevant code below:

FILE clicks_views.inc:

function clicks_views_data() { $data = array(); $data['clicks']['clicks_filter'] = array( 'group' => t('Clicks'), 'title' => t('Clicks left'), 'help' => t('Filter any Views based on clicks left'), 'filter' => array( 'field' => 'clicks_left', 'handler' => 'clicks_handler_filter', ), ); return $data; } 

FILE clicks_handler_filter.inc:

 <?php class clicks_handler_filter extends views_handler_filter { ??? }; 

I know that both functions are wrong;)

+6
source share
2 answers

Ok, I found a solution. For those who need it:

In clicks.module

 function clicks_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'clicks') . '/includes' ); } 

In clicks.views.inc

 function clicks_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'clicks') . '/includes', // path to view files ), 'handlers' => array( // register our custom filter, with the class/file name and parent class 'clicks_handler_filter' => array( 'parent' => 'views_handler_filter', ) ), ); } function clicks_views_data() { $data = array(); if(module_exists('clicks')) { $data['node']['clicks'] = array( 'group' => t('Clicks'), 'title' => t('Clicks left'), 'help' => t('Filter any Views based on clicks left'), 'filter' => array( 'handler' => 'clicks_handler_filter', ), ); } return $data; } 

In clicks_handler_filter.inc

 class clicks_handler_filter extends views_handler_filter { function admin_summary() { } function operator_form() { } function query() { $table = $this->ensure_my_table(); $join = new views_join(); $join->construct('clicks', $this->table_alias, 'nid', 'nid'); $this->query->ensure_table('clicks', $this->relationship, $join); $this->query->add_where($this->options['group'], "clicks.clicks_left", 0, ">"); } } 

This gives me the opportunity to add a โ€œclicksโ€ filter, which, if enabled, hides all results that donโ€™t have left clicks (clicks_left> 0)

+5
source

In fact, if your values โ€‹โ€‹in your tables are numeric, you do not need to create your own handler, you can use the default value from Views views_handler_filter_numeric .

You can see all handlers that already exist in handlers .

0
source

Source: https://habr.com/ru/post/896865/


All Articles