From d7734740b29e4673d3433a5f560aeff71e238967 Mon Sep 17 00:00:00 2001
From: Stephan Robotta <stephan.robotta@bfh.ch>
Date: Mon, 28 Nov 2022 15:59:52 +0100
Subject: [PATCH] MDL-76074 completion: fixed filter in reports with custom
 user fields

When the site uses custom user text fields that would show up in a
user list, the filter for firstname or lastname didnt work anymore.
If a filter was used, no result would show up. Users where shown only
when the course reports where used without filters.
---
 lib/completionlib.php | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/lib/completionlib.php b/lib/completionlib.php
index 94cd4b0c924..46bad39d87a 100644
--- a/lib/completionlib.php
+++ b/lib/completionlib.php
@@ -1424,14 +1424,15 @@ class completion_info {
         $fieldssql = $userfieldsapi->get_sql('u', true);
         $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
         $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
-        $sql .= $fieldssql->joins;
-        $params = array_merge($params, $fieldssql->params);
 
         if ($where) {
             $sql .= " AND $where";
             $params = array_merge($params, $whereparams);
         }
 
+        $sql .= $fieldssql->joins;
+        $params = array_merge($params, $fieldssql->params);
+
         if ($sort) {
             $sql .= " ORDER BY $sort";
         }