Trouble creating a custom sort function for a CCK type

ultimike@drupal.org's picture
public
ultimike@drupal.org - Tue, 2008-07-08 19:56

Hello,

I'm trying to figure out the best way to use the Views (v1.x) API to create a custom sort function for a CCK type.

Here's what I have:

CCK fields:

  • title (string)
  • rating_a (int)
  • rating_b (int)
  • rating_c (int)
  • rating_d (int)

I need to develop a way to sort the view by the average of a variable number of the "rating" CCK fields.

For example, if the user wants to sort the nodes only by "rating_a" and "rating_c", then the "order by" clause would look something like this:

...ORDER BY (rating_a + rating_c)/2 DESC

Or, if the user wants to sort the nodes by "rating_b", "rating_c", and "rating_d", the order clause would look like this:

...ORDER BY (rating_b + rating_c + rating_d)/3 DESC

Make sense so far?

The various "rating_*" choices will be coming in via arguments in the form "rating_a+rating_b+rating_c". So far, my plan has been to hook_views_arguments to define the argument, then to write a custom handler. In the custom handler, I'm planning on using $query->add_orderby() in the "filter" $op to actually add the sort criteria.

The problem I'm having is that I'm not sure what to set the add_orderby() parameters to:

add_orderby($table, $field, $order, $alias = '')

When I look at the $query coming into the custom handler, I don't see any of the CCK tables joined. I know that at some point the CCK tables will be there, but it seems that when my module's hooks are called, the CCK stuff hasn't been added yet.

Am I taking the correct approach on this or am I going about this the wrong way? Any help would be appreciated.

Here's a (simplified) copy of the code:

/**
* Implementation of hook_views_arguments.
/
function mymodule_views_arguments() {
  $arguments = array(
    'ratings' => array(
      'name' => t('Ratings'),
      'handler' => 'mymodule_views_handler_rating',
      'help' => t('This argument sorts the results based on the ratings inputs.'),
    ),
  );
  return $arguments;
}

/
*
* Implementation of hook_views_handler_arguement.
*/
function mymodule_views_handler_rating($op, &$query, $a1, $a2 = null) {
  switch ($op) {
    case 'filter':
      dsm($query);
      //$query->add_orderby($table, $field, $order, $alias = '')
      break;
  }
}