I want to use the MySQL FIELD()
function to alter a query so that it orders a particular field on a particular order of keys.
The keys for this 'select' field are: active, under_contract, sold
I want to sort the View so that all of my results are sorted first by node.created DESC
(this is simple, of course) and then push all sold
nodes to the very bottom of the result.
I tried doing this first in hook_views_post_execute():
function mymodule_views_post_execute(&$view) {
if ($view->name == 'my_view') {
usort($view->result, function($a, $b) {
return ($a->field_field_status[0]['raw']['value'] == 'sold') ? 1 : -1;
});
}
}
but quickly discovered that, since my view only shows 25 results per page, this only pushes sold
nodes to the bottom of each page.
Next, I tried to use hook_views_query_alter()
to add the awesome MySQL FIELD()
function that I just discovered – which works to achieve my goal perfectly in MySQL - but can't be added (at least as I'm discovering) to a SelectQuery object, which Views uses to run the query:
function mymodule_views_query_alter(&$view, &$query) {
if ($view->name == 'my_view') {
$query->orderby[0] = array(
'field' => " FIELD(field_data_field_status.field_status_value, 'sold') ",
'direction' => 'DESC',
);
}
}
How can I add a FIELD()
orderby function to this query? Is there another method to push a particular filter value to the bottom of the result queue?
orderBy()
function I believe. See api.drupal.org/api/drupal/includes%21database%21database.inc/… Install the Devel module and dpm($query); in your hook_views_query_alter(), which should be MYMODULE_views_query_alter() ....$query->orderby
consists of arrays of[field],[direction]
. See: api.drupal.org/api/drupal/includes%21database%21select.inc/…. When Views formalizes the$query
array it runs the->orderBy()
method. Since$query
inhook_views_query_alter()
is simply an array and not yet an instantiation of a SelectQuery object, throwing ->orderBy() at it throws a fatal error,Call to undefined method
.orderBy($field, $direction)
).