Is it possible to have one exposed filter apply to multiple fields? I did search around the issues posted here, and stumbled across the views_or module. However, while I can use that to OR filters together (one for each field), it still means I have to expose one filter for each field. I guess this would work if I could hide everything except the first filter, and then have the other filters automatically get set to the value of the first.

CommentFileSizeAuthor
#50 views_filters_populate.tar_.gz1.62 KBhanoii
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

patchak’s picture

This is also something I would be interested in. For example I have 4 email fields in this site I took over, and now users of the site would like to query all those 4 email fields at the same time and not search one by one...

Is there any way to do this?
Thanks

susannaschroeder’s picture

I too am very interested in this. We need to create a search form that has one form input field, and searches within multiple db fields, including a taxonomy field.

Imagine we accept a "key word" - then we need to find every record where that keyword is in the tile, and in the summary.

How can we modify a view query (safely) to do this?

Thanks,
Susanna

merlinofchaos’s picture

There's no really good way to do that in Views. Maybe with a lot of code hacking you could accomplish it.

jjesus’s picture

Is there a way to modify the SQL query used for the view to include an OR in the WHERE clause?

I have a similar requirement ... a School table has columns City/State/Country ... I have only a single input text field that I want to match against any of those 3 location fields.

jjesus’s picture

I ended up using VIEWS_OR and a custom form. http://drupal.org/project/views_or

rapsli’s picture

@jjesus, could you post some code of how you did it, because I'm looking for exactely the same solution.

latte’s picture

If you could post how you did this you would have some pretty good karma around here.
Seems like a bunch of people are looking for this option.

Thanks in advance.

Latte/

anthonyjhall’s picture

SpriteGF’s picture

Another thread recommended CCK Computed Fields:
http://drupal.org/node/126522

darrenmothersele’s picture

I came up with a solution based on the idea given for multiple views on the stackoverflow link you gave.

Unfortunately, it relied on a 'feature' in Views 2.6 that has now been fixed as a bug in 2.8. i.e. you can no longer create multiple exposed filters that have the same filter identifier.

I'm now looking for an alternative solution...

dawehner’s picture

Why do you not set different operators?

darrenmothersele’s picture

@dereine I'm not sure I understand how that would help?

dawehner’s picture

I mean different identifiers.

darrenmothersele’s picture

Because I want all exposed filters to operate on the same value - without the user having to enter exactly the same value into all of them. In 2.6 you can do this - it exposes one filter box, and the same value is used for all filters.

darrenmothersele’s picture

Because I want all exposed filters to operate on the same value - without the user having to enter exactly the same value into all of them. In 2.6 you can do this - it exposes one filter box, and the same value is used for all filters.

jpklein’s picture

Just because Views UI doesn't allow you to set the same filter identifier doesn't mean you can't still do it... For anyone that stumbles on this thread like I did, here's a recipe that worked for me.

I had three fields in my view that I wanted my users to be able to search across using a single text field: Name, Display Name, and Title.

First, install the Views_Or module and set up your view's Filters as follows:

Views Or: Begin alternatives =
Node: Title exposed
Views Or: Next alternative =
Content: Name exposed
Views Or: Next alternative =
Content: Display Name exposed
Views Or: End alternatives =

When you're exposing these fields, set the Filter Identifier to be the same except append a different digit at the end. In my case, I used "search1", "search2", and "search3".

Next, select the tab to Export the view. Create a new custom module and paste the exported code into a hook_views_default_views() function. Search through this code for the filter identifier you set, and remove the final digit for all the fields you want to search using the same field, like this:

    'title' => array(
      'operator' => 'contains',
      'value' => '',
      'group' => '0',
      'exposed' => TRUE,
      'expose' => array(
        'use_operator' => 0,
        'operator' => 'title_op',
        'identifier' => 'search',  <-- set this the same for filters you want to group together
        'label' => 'Search Name fields',
        'optional' => 1,
        'remember' => 1,
      ),
      ...

Even though they're all set to use the same argument from the URL, your form will still display all three filter fields unless you remove them. To do that, create another function in your custom module implementing hook_form_views_exposed_form_alter(). In this code, check for the name of the view first, then unset the $form['#info'] entries for all but the first exposed filter field -- print_r() is your friend here. In my case:

function custommodule_form_views_exposed_form_alter(&$form, $form_state) {
  switch ($form_state['view']->name) {
    case 'customview':
      unset($form['#info']['filter-field_name_value']);
      unset($form['#info']['filter-field_displayname_value']);
      $form['submit']['#value'] = t('Search');
      break;
  }
}

Save and enable your custom module, then make a trivial change to the view you started creating via the UI and save it. Back in the views list you should see an option to 'Revert' the view you just edited. Select that, then go to Views->Tools and clear the views cache, and you're all set. Hope it helps!

rickyd1’s picture

I like your post. I wasn't in need of this, but I am going to have to try this just in case I ever have a client that needs this feature. Thanks for the post.

Cyberwolf’s picture

Subscribing.

keitarNo’s picture

That did the trick. Thanks !

dawehner’s picture

So this is fixed? If yes make the issue as fixed

robby.smith’s picture

Hi!

I was wondering if there is a chance of this becoming a feature request? (any major benefits other than this use case?) Or should it remain as a modification done by a custom module?

When a Filter Identifer that already exists is entered:
Current message: | This identifier is used by another handler. |
Suggested message: | This identifier is used by another handler. use it anyway |

- An override that would allow admin to force the Filter Identifer after a warning message.

Just a thought I had while trying #16 which worked nicely!

Thanks

darrenmothersele’s picture

+1 for this being a warning, rather than a validation error.

JThan’s picture

Thx to #16. Just add that hook_views_default_views needs to return an array containing the view

  $views[$view->name] = $view;
  return $views;

Then this is ready to go.

30equals’s picture

i'm trying to do the same thing, and followed the instruction of #16, but the code has no effect at all...?

danielbeeke2’s picture

Hey,

if you want to do like #16 but with less coding you can hack into core and comment out these lines in views_handler_filter.inc

if (!$this->view->display_handler->is_identifier_unique($form_state['id'], $form_state['values']['options']['expose']['identifier'])) {
form_error($form['expose']['identifier'], t('This identifier is used by another handler.'));
}

Daniel Beeke, At the Rise of Day

sime’s picture

Status: Active » Fixed

This can be done with computed fields module, particularly if all the fields you want to filter are from one node type.
http://drupal.org/node/126522

1) Create a new computed field (maybe call it 'field_search_data') on the target node type.
2) Configured it so that it aggregates all the other fields you want to filter on and saved the result in it's own db field.
3) In the fields display, hide the output of the field
4) In the view add a filter for the new field.

I think this is quite a nice solution that I've used a few times. So based on @merlinofchaos' opinion that an equivalent feature won't be built into views, I'm going to close the issue.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

khan2ims’s picture

Hi,

I followed #16 and also took into consideration #23. Now it displays only one field, but doesn't search the fields which have been commented out. I am using View 3 on Drupal 6. Do I need to change anything else?

Edit: I don't see "revert" link for the view, on the views list

nitin.xiitec’s picture

Something like this maybe an easier option. Use drupal_set_message(print_r($query)) to find your array variables. You will need the view_or module to first set the variables and then just put these functions in your module.

Thanks to #16 for the start but that method doesn't seem to work. My module doesn't call the first function. Therefore I went ahead with this shorter method.

<?php
function custom_search_views_query_alter(&$view, &$query) {

if ($view->name == 'SearchJobs') {

$query->where[1]['clauses'][1]="(node_revisions.body) LIKE ('%%%s%%')";
$query->where[1]['args'][1]=$query->where[1]['args'][0];

}
}

function custom_search_form_views_exposed_form_alter(&$form, $form_state) {

switch ($form_state['view']->name) {
case 'SearchJobs':
unset($form['#info']['filter-title']['label']);
unset($form['#info']['filter-body']['label']);
unset($form['body']);

$form['submit']['#value'] = t('Search for Jobs');
break;
}
}

betz’s picture

Thanks jpklein, that worked smoothly!
Made an article of this trick on
http://krimson.be/articles/2010/09/25/views-searching-multiple-fields-on...

jrz’s picture

Thanks BEtz for your article.

kmajzlik’s picture

any solution for 6.x-3.x ?

ziomizar’s picture

#26 is the simplest solution for me.
Works like a charm and not require creation of new module.
Only problem of this solution, maybe that need a lot of space for storing a big amount of data.

John Carbone’s picture

I needed this same functionality. Using #16 as a starting point, I did my filter identifier changes programmatically vs. in an exported View since we like to export Views regularly, I didn't want to create a maintenance issue. This was used to create a single form field searching across a custom Location field and the node title. Here's how I got there. It picks up at "Next, select the tab to Export the view." from #16 above.

function MYMODULE_views_pre_build(&$view) {
	if ($view->name == 'MYVIEWNAME') {
		$display_id = 'default';
		$view->set_display($display_id);
		
		$contact_name = $view->get_item($display_id, 'filter', 'contact_name');
		
		if (isset($contact_name)) {
			$contact_name['expose']['identifier'] = 'name';
			$view->set_item($display_id, 'filter', 'contact_name', $contact_name);
		}
		
		$node_title = $view->get_item($display_id, 'filter', 'title');
		
		if (isset($node_title)) {
			$node_title['expose']['identifier'] = 'name';
			$view->set_item($display_id, 'filter', 'title', $node_title);
		}
		
		$view->is_cacheable = FALSE;

	}
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
	if ($form_state['view']->name == 'MYVIEWNAME' && $form_state['view']->current_display == 'default') {
		if (isset($form['#info']['filter-title'])) {
			unset($form['#info']['filter-title']);
		}
		
		if (isset($form['#info']['filter-contact_name'])) {
			$form['#info']['filter-contact_name']['label'] = "Name";
		}
	}
}
Anonymous’s picture

#16 and #23

I'm having trouble understanding the unset function.
custommodule - should be the name of my module, yes?
'customview' - should be the name of the Views we're working on, yes?
'filter-field_lastname_value' - should be the name of what? the filter? the CCKField it refers to?
Could you help me?

function custommodule_form_views_exposed_form_alter(&$form, $form_state) {
switch ($form_state['view']->name) {
case 'customview':
unset($form['#info']['filter-field_lastname_value']);
unset($form['#info']['filter-field_location_value']);
$form['submit']['#value'] = t('Search');
break;
}
}
TYPEX’s picture

Nice solution if you are using a node view. This solution along with one suggesting the use of the computed fields module both require modules that work w nodes. Does anyone have a solution for combining exposed views in user profile fields? Muchas gracias

TechNikh’s picture

for views3 unset($form['#info']['filter-field_name']; is not sufficient. it's showing the extra textboxes near the apply button. Any idea how to fix this?

TechNikh’s picture

I take my previous comment back. It's working perfectly for views3

nourcy’s picture

I use

Views Or: Begin alternatives =<br>
Content: Keywords exposed<br>
Views Or: Next alternative =<br>
Content: Name exposed<br>
Views Or: Next alternative =<br>
Content: Display Name exposed<br>
Views Or: End alternatives =

I had a submit and I hide fields that I doesnt need in form_alter
And I set my keywords values to others in my submit

function mymodule_form_alter(&$form, $form_state, $form_id){
  if($form_state['view']->name == 'cv'){
    array_unshift($form['#submit'], 'mymodule_cv_submit');
    $hidden_fields = array("name", "display_name", ...);
    foreach($hidden_fields as $field){
      $form[$field]['#type'] = 'hidden';
    }
  }
}

function mymodule_cv_submit(&$form, &$form_state) {
  if(isset($form_state['input']['keywords'])){
    $keywords = $form_state['input']['keywords'];
    $hidden_fields = array("name", "display_name", ...);
    foreach($hidden_fields as $field){
      $form_state['values'][$field] = $keywords;
    }
  }
}

A little dirty but its works !

WildKitten’s picture

I tried #16 but I couldn't get it work. I don't like hacking the core, but #25 worked great!

  • So open views/handlers/views_handler_filter.inc and comment these lines:
     if (!$this->view->display_handler->is_identifier_unique($form_state['id'], $form_state['values']['options']['expose']['identifier'])) {
          form_error($form['expose']['identifier'], t('This identifier is used by another handler.'));
        }
  • install the Views_Or module and set up your view's Filters as follows:
    Views Or: Begin alternatives =
    Node: Title exposed
    Views Or: Next alternative =
    Content: Name exposed
    Views Or: Next alternative =
    Content: Display Name exposed
    Views Or: End alternatives =
    
  • When you're exposing these fields, set the Filter Identifier to be the same. In my case, I used "search" for all 3 filters.
afeijo’s picture

Here is my code for views 7-3, for 1 exposed filter to be used for filter for node title or one taxonomy

function custommodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'ViewName') {
    if (count($query->where[1]['conditions'])) {
// get the matching taxonomies
      $result = db_select('taxonomy_term_data', 't')
        ->fields('t', array('tid', 'name'))
        ->condition('name', $query->where[1]['conditions'][0]['value'].'%', 'like')
        ->orderBy('name')
        ->execute();
// feed all found terms into an array
      foreach($result as $row) {
        $values[$row->tid] = $row->tid;
      }

      $query->where[1]['conditions'][1] = $query->where[1]['conditions'][0];
      $query->where[1]['conditions'][1]['operator'] = 'in';
      $query->where[1]['conditions'][1]['field'] = 'taxonomy_term_data_field_data_field_{name}.tid';
      $query->where[1]['conditions'][1]['value'] = $values;
    }
	}
}

function custommodule_form_views_exposed_form_alter(&$form, $form_state) {
	switch ($form_state['view']->name) {
	case 'ViewName':
// hide the exposed filter
		$form['field_{name}_tid']['#type'] = 'hidden';
		break;
	}
}

HTH

doublejosh’s picture

Trying to decide on my approach. This always means make a big list :)

  1. Programatic view via export built without UI and Views OR query. views_or
  2. Combine data via submit handler and Views OR query. Effects caching? views_or
  3. Compute and store a shared value in single field. computed_field
  4. Make dynamic field though no views integration :( dynamicfield
  5. Use a computed custom field only within the view. views_customfield
  6. Modify views query via eval PHP. views_modify_query
  7. Add filters and/or fields into views via eval PHP. viewsphp
  8. Add filters via eval PHP. viewsphpfilters
hanoii’s picture

subs

hanoii’s picture

Version: 6.x-2.5 » 6.x-2.9
Status: Closed (fixed) » Needs review

I will soon upload a module that would really sort this out without any hacking, basically it follows the views_or approach but it adds one new filter that can be used to populate other filter values. So in this case, you would just do the normal views_or approach except without really exposing those filters, instead, you would expose the new filter added by my module which will populate the other filters.

I might just upload it to d.o. as I feel it's a nice module, but I wonder if there are any souls on this issue to try it out. If so,. I might upload it here first.

hanoii’s picture

Version: 6.x-2.9 » 6.x-2.x-dev
hanoii’s picture

Title: Apply One Exposed Filter to Multiple Fields » new request: views filter populate
Project: Views (for Drupal 7) » Views Hacks
Version: 6.x-2.x-dev » 6.x-1.x-dev
Component: exposed filters » General
Category: support » feature

I was smartly pointed to Views hack, which sounds like a good place to add this feature rather than contributing a new module myself, what do you think?

Basically what this new module I did does, is exports a new filter within a 'Global' section that allows you to enter a value (via a textfield) and choose what filters of the current display should use that value (via checkboxes). This is specially useful for use cases like this one, in which you might one one exposed filter to sort them all.

Any thoughts of this being added to Views hacks? Do you think worth doing a new module? Would you give me maintainer access or you would maintain it yourself?

Thanks,

hanoii’s picture

Title: new request: views filter populate » new module: views filter populate
daemonsy’s picture

Subscribe

doublejosh’s picture

Love this @hanoii
Need any testing? Got a sandbox?

hanoii’s picture

I thought I uploaded it here, but I haven't. Attached is the module.

If this is needed I don't mind uploading contributing it as a separate module.

You might need to rename it back to tar.gz for it to work.

To use, add a new filter of the global section, called filter populate or something, expand it and select the filters that this should populate. Do not expand those filters you selected, and do the views_or combination you need as you would do without this.

doublejosh’s picture

Did this end up landing anywhere else?

Also, there don't appear to be Global filters in Views 6.2.12
Do I need 6.x-3.0-alpha3?

doublejosh’s picture

My fault. Hadn't enabled it. Sorry!!! Looks wonderful now.

doublejosh’s picture

Status: Needs work » Needs review

Seems to be working for me as expected. Amazing. Saved me at least a day.
Not 100% this is from this module but, when there are no results it shows everything, much like an argument setting what to do when doesn't validate.

infojunkie’s picture

Status: Needs review » Needs work

Thanks for the submission, useful handler indeed.

I found a problem trying to send values to a Node: Type and Node: Title simultaneously. I get a warning:

warning: array_values() expects parameter 1 to be array, string given in /home/kratib/www/d6/sites/all/modules/views/handlers/views_handler_filter_in_operator.inc on line 348.

This is because the filter value assignment in views_filters_populate_handler_filter::pre_query() says:

$this->view->filter[$filter]->value = $value;

whereas views_handler_filter_in_operator probably expects an array of values.

This raises the question of the general applicability of this module: can it only work with just string filter values?

hanoii’s picture

Status: Needs review » Needs work

well, at first yes, I guess there might be ways to try to improve the module and start handling more use cases, but this has one basic aim which is to try to create a text field to filter different elements, and yes, those are most likely free text. For typed filters, not sure how used that would be or how, but if necessary I can try to take a look and see if I can come up with a solution to that, for as a starter, I thin it's a pretty useful module.

Also let me know if you prefer form e to create a separate module to load off some support for that.

infojunkie’s picture

Status: Needs work » Closed (won't fix)

Because I have very little free time to take on new sub-modules, I think it would be best for you to create a new module. Thanks!

hanoii’s picture

Title: new module: views filter populate » Apply One Exposed Filter to Multiple Fields
Project: Views Hacks » Views (for Drupal 7)
Version: 6.x-1.x-dev » 6.x-2.x-dev
Component: General » exposed filters
Status: Closed (won't fix) » Closed (fixed)

I am restoring this issue name and project, and changing it's status just for leaving the issue with a proper referecne.

I have contributed the module to http://drupal.org/project/views_filters_populate, it should have a dev release soon if I haven't missed anything, feel free to try, test, contribute and report issues with that module.

ankitchauhan’s picture

Hi Nitin

Thank you very much for a very short and helpful method. It works fine.

I went with #16 method. But after installing views_or module and configured field as well, I was facing problem after exporting view it wasn't working somehow. I have applied your code. Now my problem is resolved.

Thanks once again.

Max_Headroom’s picture

doublejosh’s picture

Seconded. I use that and it's great.

a.milkovsky’s picture

#59
Great module. But there is 1 problem "only populates STRING exposed filters"

gokulnk’s picture

On my Drupal instance I have Views 7.x-3.7 there is a filter Global: Combine fields filter (exposed) This lets me add multiple fields and then enables users to search on selected fields using a single filter.

argiepiano’s picture

Issue summary: View changes

Confirming #62: Global: combine fields filter works like a charm. More information here: https://swsblog.stanford.edu/blog/views-exposed-filters-multiple-field-search

Ajay Gadhavana’s picture

Its awesome features by views module suppose you want to search address based on zip code or using any text of that address then you can go with global filter.

steps : FILTER CRITERIA = > ADD => Global => Global: Combine fields filter => select your fields thats it.
Enjoy :D