From 56b2535636af64a793292102f6a36373b0c23326 Mon Sep 17 00:00:00 2001
From: Markus Klein <markus.klein@typo3.org>
Date: Mon, 31 Oct 2016 20:45:35 +0100
Subject: [PATCH] [FEATURE] Option to define ordering of suggest wizard results

This allows to configure the ordering cirteria for suggest wizard search results.

Resolves: #78523
Releases: master
Change-Id: I4bbcbeab765b037ba3b3457a2bc9ca3323f95f59
Reviewed-on: https://review.typo3.org/50460
Tested-by: TYPO3com <no-reply@typo3.com>
Reviewed-by: Christian Kuhn <lolli@schwarzbu.ch>
Tested-by: Christian Kuhn <lolli@schwarzbu.ch>
Reviewed-by: Andreas Fernandez <typo3@scripting-base.de>
Tested-by: Andreas Fernandez <typo3@scripting-base.de>
---
 .../Classes/Form/Wizard/SuggestWizard.php     | 33 +--------------
 .../Wizard/SuggestWizardDefaultReceiver.php   | 17 ++++----
 ...rovidesOptionToDefineOrderingOfResults.rst | 42 +++++++++++++++++++
 3 files changed, 51 insertions(+), 41 deletions(-)
 create mode 100644 typo3/sysext/core/Documentation/Changelog/master/Feature-78523-SuggestWizardProvidesOptionToDefineOrderingOfResults.rst

diff --git a/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizard.php b/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizard.php
index b89c2b12e464..868f728c533e 100644
--- a/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizard.php
+++ b/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizard.php
@@ -260,9 +260,9 @@ class SuggestWizard
         $maxItems = isset($config['maxItemsInResultList']) ? $config['maxItemsInResultList'] : 10;
         $maxItems = min(count($resultRows), $maxItems);
 
-        $listItems = $this->createListItemsFromResultRow($resultRows, $maxItems);
+        array_splice($resultRows, $maxItems);
 
-        $response->getBody()->write(json_encode($listItems));
+        $response->getBody()->write(json_encode(array_values($resultRows)));
         return $response;
     }
 
@@ -444,35 +444,6 @@ class SuggestWizard
         return $config;
     }
 
-    /**
-     * Creates a list of <li> elements from a list of results returned by the receiver.
-     *
-     * @param array $resultRows
-     * @param int $maxItems
-     * @return array
-     */
-    protected function createListItemsFromResultRow(array $resultRows, $maxItems)
-    {
-        if (empty($resultRows)) {
-            return [];
-        }
-        $listItems = [];
-
-        // traverse all found records and sort them
-        $rowsSort = [];
-        foreach ($resultRows as $key => $row) {
-            $rowsSort[$key] = $row['text'];
-        }
-        asort($rowsSort);
-        $rowsSort = array_keys($rowsSort);
-
-        // put together the selector entries
-        for ($i = 0; $i < $maxItems; ++$i) {
-            $listItems[] = $resultRows[$rowsSort[$i]];
-        }
-        return $listItems;
-    }
-
     /**
      * Checks the given field configuration for the tables that should be used for querying and returns them as an
      * array.
diff --git a/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizardDefaultReceiver.php b/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizardDefaultReceiver.php
index 5ca700fe94a7..03beae1ef70d 100644
--- a/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizardDefaultReceiver.php
+++ b/typo3/sysext/backend/Classes/Form/Wizard/SuggestWizardDefaultReceiver.php
@@ -50,13 +50,6 @@ class SuggestWizardDefaultReceiver
      */
     protected $mmForeignTable = '';
 
-    /**
-     * The statement by which records will be ordered
-     *
-     * @var string
-     */
-    protected $orderByStatement = '';
-
     /**
      * Configuration for this selector from TSconfig
      *
@@ -158,7 +151,6 @@ class SuggestWizardDefaultReceiver
         $this->prepareOrderByStatement();
         $result = $this->queryBuilder->select('*')
             ->from($this->table)
-            ->orderBy($this->orderByStatement)
             ->setFirstResult($start)
             ->setMaxResults(50)
             ->execute();
@@ -306,8 +298,13 @@ class SuggestWizardDefaultReceiver
      */
     protected function prepareOrderByStatement()
     {
-        if ($GLOBALS['TCA'][$this->table]['ctrl']['label']) {
-            $this->orderByStatement = $GLOBALS['TCA'][$this->table]['ctrl']['label'];
+        if (empty($this->config['orderBy'])) {
+            $this->queryBuilder->addOrderBy($GLOBALS['TCA'][$this->table]['ctrl']['label']);
+        } else {
+            foreach (QueryHelper::parseOrderBy($this->config['orderBy']) as $orderPair) {
+                list($fieldName, $order) = $orderPair;
+                $this->queryBuilder->addOrderBy($fieldName, $order);
+            }
         }
     }
 
diff --git a/typo3/sysext/core/Documentation/Changelog/master/Feature-78523-SuggestWizardProvidesOptionToDefineOrderingOfResults.rst b/typo3/sysext/core/Documentation/Changelog/master/Feature-78523-SuggestWizardProvidesOptionToDefineOrderingOfResults.rst
new file mode 100644
index 000000000000..a5072f0f40ce
--- /dev/null
+++ b/typo3/sysext/core/Documentation/Changelog/master/Feature-78523-SuggestWizardProvidesOptionToDefineOrderingOfResults.rst
@@ -0,0 +1,42 @@
+.. include:: ../../Includes.txt
+
+==============================================================================
+Feature: #78523 - Suggest wizard provides option to define ordering of results
+==============================================================================
+
+See :issue:`78523`
+
+Description
+===========
+
+It is now possible to set the ordering of results delivered by the suggest wizard.
+
+The new option is called php:`orderBy => 'somefield ASC'` and can hold the usual SQL order by definition.
+
+Example TCA configuration for ext:news suggest wizard returning the related articles sorted by datetime:
+
+.. code-block:: php
+
+   'config' => [
+       'type' => 'group',
+       'internal_type' => 'db',
+       'allowed' => 'tx_news_domain_model_news',
+       'foreign_table' => 'tx_news_domain_model_news',
+       'MM_opposite_field' => 'related_from',
+       'size' => 5,
+       'minitems' => 0,
+       'maxitems' => 100,
+       'MM' => 'tx_news_domain_model_news_related_mm',
+       'wizards' => [
+           'suggest' => [
+               'type' => 'suggest',
+               'default' => [
+                   'searchWholePhrase' => true,
+                   'addWhere' => ' AND tx_news_domain_model_news.uid != ###THIS_UID###',
+                   'orderBy => 'datetime DESC',
+               ]
+           ],
+       ],
+   ]
+
+.. index:: Backend, TCA
-- 
GitLab