Skip to content
Snippets Groups Projects
Unverified Commit d66e9cf3 authored by colemanw's avatar colemanw Committed by GitHub
Browse files

Merge pull request #21177 from colemanw/rand

SearchKit - Allow random sorting (Fixes report#75)
parents c18ec7f7 9a0f174b
Branches
Tags
No related merge requests found
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
namespace Civi\Api4\Query;
/**
* Sql function
*/
class SqlFunctionRAND extends SqlFunction {
protected static $category = self::CATEGORY_MATH;
protected static function params(): array {
return [];
}
/**
* @return string
*/
public static function getTitle(): string {
return ts('Random Number');
}
}
......@@ -262,10 +262,18 @@
return _.findIndex(ctrl.display.settings.sort, [key]) >= 0;
}
return {
results: [{
text: ts('Columns'),
children: ctrl.crmSearchAdmin.getSelectFields(disabledIf)
}].concat(ctrl.crmSearchAdmin.getAllFields('', ['Field', 'Custom'], disabledIf))
results: [
{
text: ts('Random'),
icon: 'crm-i fa-random',
id: 'RAND()',
disabled: disabledIf('RAND()')
},
{
text: ts('Columns'),
children: ctrl.crmSearchAdmin.getSelectFields(disabledIf)
}
].concat(ctrl.crmSearchAdmin.getAllFields('', ['Field', 'Custom'], disabledIf))
};
};
......
<div class="form-inline" ng-repeat="sort in $ctrl.display.settings.sort">
<label for="crm-search-display-sort-{{$index}}">{{ $index ? ts('Also by') : ts('Sort by') }}</label>
<input id="crm-search-display-sort-{{$index}}" class="form-control huge" ng-model="sort[0]" crm-ui-select="{data: $ctrl.parent.fieldsForSort}" />
<select class="form-control" ng-model="sort[1]">
<select class="form-control" ng-model="sort[1]" ng-show="sort[0] !== 'RAND()'">
<option value="ASC">{{ ts('Ascending') }}</option>
<option value="DESC">{{ ts('Descending') }}</option>
</select>
......
......@@ -199,4 +199,21 @@ class SqlFunctionTest extends UnitTestCase {
}
}
public function testRandFunction() {
$cid = Contact::create(FALSE)
->addValue('first_name', 'hello')
->execute()->first()['id'];
$result = Contact::get(FALSE)
->addSelect('RAND() AS rand')
->addOrderBy('RAND()')
->setDebug(TRUE)
->setLimit(1)
->execute();
$this->assertStringContainsString('ORDER BY RAND()', $result->debug['sql'][0]);
$this->assertGreaterThanOrEqual(0, $result[0]['rand']);
$this->assertLessThan(1, $result[0]['rand']);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment