(views 3)

I'm struggling to add a custom sort to one of my view and figured I should use hook_views_query_alter

I have a previous mymodule custom module in which I have a mymodule_form_alter function (that works fine).

From what I read, it seems like I need 2 things:

  • an implementation of hook_views_api() and
  • a module.views.inc file located in the mymodule folder

So I added the following code to my mymodule.module file

/**
* Implementation of hook_views_api().
*/
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

and in the same folder I have a mymodule.views.inc:

function agenda_items_by_date_views_query_alter(&$view, &$query) {
	if ($view->name=='agenda_items_by_date') {
		$query->orderby[0] = 'field_data_field_item_num_field_item_num_value DESC';
	}
}

I'll tweak the order by clause when I can get it to work but I can't get it to work.

Can someone help figuring out what is wrong?

Comments

nixar’s picture

Ok so I managed to make it work by putting everything related to the hook_query_alter() in a second custom module. The biggest problem came from one function name... (read a noob mistake)

also for good measure, this can help: http://drupal.stackexchange.com/questions/3869/how-do-i-use-hook-views-q...

Edit:
Also the following didn't work:

function agenda_items_by_date_views_query_alter(&$view, &$query) {
   if ($view->name=='agenda_items_by_date') {
      $query->orderby[0] = 'field_data_field_item_num_field_item_num_value DESC';
   }
}

I had to change it to:

function mymodule2_views_query_alter(&$view, &$query) {
	if ($view->name=='agenda_items_by_date') {
		$query->orderby[0]['field'] = "field_data_field_item_num_field_item_num_value";
		$query->orderby[0]['direction'] = "DESC";
	}
}

Any ideas on how to ultimately do something like described here, using CASE... WHEN... THEN... in my ORDER BY clause: http://www.agileapproach.com/blog-entry/using-hookviewsqueryalter-change... ?

gillarf’s picture

I'm in the same situation, and have read the same posts as you :-)

Did you work it out? Your field is very strangely named by the way.