Skip to content

Commit

Permalink
Showing 4 changed files with 62 additions and 5 deletions.
32 changes: 32 additions & 0 deletions Civi/Api4/Query/SqlFunctionRAND.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?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');
}

}
Original file line number Diff line number Diff line change
@@ -251,10 +251,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))
};
};

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<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>
17 changes: 17 additions & 0 deletions tests/phpunit/api/v4/Action/SqlFunctionTest.php
Original file line number Diff line number Diff line change
@@ -199,4 +199,21 @@ public function testIncorrectNumberOfArguments() {
}
}

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 comments on commit 9a0f174

Please sign in to comment.