From 9a0f174b66a77fa6ea44a976de2f3d649db6cbf2 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Wed, 18 Aug 2021 16:26:53 -0400 Subject: [PATCH] SearchKit - Allow random sorting --- Civi/Api4/Query/SqlFunctionRAND.php | 32 +++++++++++++++++++ .../crmSearchAdminDisplay.component.js | 16 +++++++--- .../crmSearchAdminDisplaySort.html | 2 +- .../phpunit/api/v4/Action/SqlFunctionTest.php | 17 ++++++++++ 4 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 Civi/Api4/Query/SqlFunctionRAND.php diff --git a/Civi/Api4/Query/SqlFunctionRAND.php b/Civi/Api4/Query/SqlFunctionRAND.php new file mode 100644 index 000000000000..1cb0cfeeb915 --- /dev/null +++ b/Civi/Api4/Query/SqlFunctionRAND.php @@ -0,0 +1,32 @@ += 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)) }; }; diff --git a/ext/search_kit/ang/crmSearchAdmin/crmSearchAdminDisplaySort.html b/ext/search_kit/ang/crmSearchAdmin/crmSearchAdminDisplaySort.html index 4e548899aa97..a3a1cf737e23 100644 --- a/ext/search_kit/ang/crmSearchAdmin/crmSearchAdminDisplaySort.html +++ b/ext/search_kit/ang/crmSearchAdmin/crmSearchAdminDisplaySort.html @@ -1,7 +1,7 @@
- diff --git a/tests/phpunit/api/v4/Action/SqlFunctionTest.php b/tests/phpunit/api/v4/Action/SqlFunctionTest.php index 078b9eeaa82a..5cf7373770d8 100644 --- a/tests/phpunit/api/v4/Action/SqlFunctionTest.php +++ b/tests/phpunit/api/v4/Action/SqlFunctionTest.php @@ -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']); + } + }