How to make Union with different views or displays

Last updated on
12 April 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Suppose you need to build a view that combines fields of entity which have complex relationships with other entities and won't work in one view. But you could get the results for each relationship with an entity in one separate view. Then it comes to your mind the idea: what if you could make a union between those two views (may be two displays) instead of writing a complex sql query?  

Writing an sql query will be very hard to maintain in the future, especially if fields or relationships got altered.  It will be very hard to debug or to add required fields or relationships. It's very annoying, takes more time, and is hard to maintain.

I wrote this article in order to make it easier using an awesome module called Views Extra Handlers, which gives the ability to make extra advanced sql statements like group by one field instead of using aggregation settings, adding where conditions, join and the most powerful union.views union

A real case example: suppose you are building an e-commerce store and you need to make users able to follow products of specific categories or authors (if you your store is multi-seller), So you are using Flag to define two flags for taxonomy and users, let users flag them.

You could build a view getting products added by users that current logged in user follow.

You could build a view getting products in categories that current logged in user follow.

Surely you wouldn't be able to mix both results in one view.

But if you use the module Views Extra Handlers, you can do exactly that. You do it by building two separate blocks with the same fields and no sorting settings (because you can't use order by statements before union statements).

In one view, add the global query alter field and choose union. Set the view name and display id.
global query alter field

After that, add the sort for the two views or display ids to be the same and ensure fields are matching by cloning the first view and change your filters or relationships instead of build new one. 

Help improve this page

Page status: No known problems

You can: