--- /dev/null
+<?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');
+ }
+
+}
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>
}
}
+ 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']);
+ }
+
}