public function SortAllowedValues::query in Views List Sort 8
Called to add the sort to a query.
Sort by index of allowed values using sql FIELD function.
Overrides SortPluginBase::query
See also
http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
File
- src/
Plugin/ views/ sort/ SortAllowedValues.php, line 57
Class
- SortAllowedValues
- Sort handler for fields with allowed_values.
Namespace
Drupal\views_list_sort\Plugin\views\sortCode
public function query() {
$this
->ensureMyTable();
// Skip if disabled.
if (!$this->options['allowed_values']) {
return;
}
$field_storage = $this
->getFieldStorageDefinition();
$allowed_values = array_keys(options_allowed_values($field_storage));
$connection = Database::getConnection();
$formula = '';
// Reverse the values returned by the FIELD function and the allowed values
// so '0' is heavier than the rest.
if ($this->options['null_heavy']) {
$allowed_values = array_reverse($allowed_values);
$formula .= '-1 * ';
}
$formula .= 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map([
$connection,
'quote',
], $allowed_values)) . ')';
$this->query
->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_' . $this->field . '_allowed_values');
}