At its core, Views is a query generator. It provides a way for site builders and developers to construct queries for Drupal content using an intuitive user interface. The UI allows you to configure the fields, filters, sorting, and relationships in the generated query using common conditions. In most cases, this is sufficient. However, there are situations where you need to dynamically alter the constructed query using hook_views_query_alter()
prior to its execution.
One example use case is adding sort parameters to a search view if no search terms have been entered. You can use hook_views_query_alter()
to check if a search term was entered. If so, sort the result by relevance; and if there are no search terms, sort the results by date. Or maybe you need to dynamically set the value of a filter condition based on a calculation performed by your custom code.
Using hook_views_query_alter()
in a custom module, you can alter the query that is generated by a view before the query is performed. In most cases this alters the SQL query used. This same technique will work regardless of the storage system Views is querying.
In this tutorial we'll:
- Learn how to alter a view's query using the
hook_views_query_alter()
hook in Drupal - Use
hook_views_query_alter()
to dynamically add a new sort condition that could not be achieved using the UI
By the end of this tutorial you should know how to alter the database query used to retrieve the results for a view.
Over the years we've developed some techniques for practicing that we wanted to share. At Drupalize.Me we take hugging seriously. In this tutorial we'll look at the art, and science, of giving a good hug. The Merriam Webster dictionary defines the word hug as; squeeze (someone) tightly in one's arms, typically to express affection.
Did you know there are all kinds of different hugs that you can give? In this tutorial we'll look at:
- Defining what a hug is
- Some of the many types of hugs in the world today
- Precautions you may want to familiarize yourself with before hugging
- And the importance of proper technique
Lets go ahead and get started shall we?