Being able to sort a view using URL parameters seems like the most basic functionality, but it seems this is not possible using using views without some kind of module. I have to say Symphony handles this much better than Drupal.

The site I’m working on requires a series of text links which order a view by “most popular”, or “most comments”, but it seems I have to duplicate my view and set up another sort criteria.

There is an existing Drupal module “Views Argument Sort”, but with a status of “abandoned” I chose not to use this.

Instead I created a little module to handle my specific sort terms. First my links were created with a sort term on the end of each:

/blog
/blog/popular
/blog/most-comments

Views provide a useful hook (hook_views_pre_render) which is executed after the data has been prepared, allowing you to sort the view before it is displayed.

So my hook function is as follows:


function view_sort_views_pre_render(&$view) {

    if ($view->name == 'blog_posts') {

        $sort = end(explode('/', drupal_get_path_alias($_GET['q'])));
        // get the last argument (URL segment) from the URL

        switch ($sort) {
            case 'popular': 
                return __sort_view($view->result, 'node_counter_monthcount');
            break;
            case 'most-comments':
                return __sort_view($view->result, 'node_comment_statistics_comment_count');
            break;
        }
    }
}

I then have a function which sorts the view based on a particular field in the view


function __sort_view($view, $subkey, $order = 'asc') {

    if ($order == 'asc')
        $code = "return strnatcmp($b->{$subkey}, $a->{$subkey});";
    else $code = "return strnatcmp($a->{$subkey}, $b->{$subkey});";

    usort($view, create_function('$a,$b', $code));
    return $view;
}

Using “create_function” is not a very nice solution, but it was the only way I could find to create a single, generic function which allows the view to be sorted based on a variable.

« Back