Order view on string length

Let's keep on with useful snippets. Here is, in 4 lines of code, how to order view results on title string length.

1
2
3
4
5
6
7
8
9
10
11
<?php
 
/**
 * Implements hook_query_TAG_alter().
 *
 * @param SelectQuery $query
 */
function glossaire_query_views_export_alter(SelectQuery $query) {
  $query->addExpression('LENGTH(node.title)', 'title_length');
  $query->orderBy('title_length', 'DESC');
}

This is used in the custom module of the french glossary. The code was built from the documentation available on drupal.org.