search/amd/src/form-search-user-selector.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Search user selector module.
  17. *
  18. * @module core_search/form-search-user-selector
  19. * @copyright 2017 The Open University
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. define(['jquery', 'core/ajax', 'core/templates'], function($, Ajax, Templates) {
  23. return /** @alias module:core_search/form-search-user-selector */ {
  24. processResults: function(selector, results) {
  25. var users = [];
  26. $.each(results, function(index, user) {
  27. users.push({
  28. value: user.id,
  29. label: user._label
  30. });
  31. });
  32. return users;
  33. },
  34. transport: function(selector, query, success, failure) {
  35. var promise;
  36. // Search within specific course if known and if the 'search within' dropdown is set
  37. // to search within course or activity.
  38. var args = {query: query};
  39. var courseid = $(selector).attr('withincourseid');
  40. if (typeof courseid !== "undefined" && $('#id_searchwithin').val() !== '') {
  41. args.courseid = courseid;
  42. } else {
  43. args.courseid = 0;
  44. }
  45. // Call AJAX request.
  46. promise = Ajax.call([{methodname: 'core_search_get_relevant_users', args: args}]);
  47. // When AJAX request returns, handle the results.
  48. promise[0].then(function(results) {
  49. var promises = [];
  50. // Render label with user name and picture.
  51. $.each(results, function(index, user) {
  52. promises.push(Templates.render('core_search/form-user-selector-suggestion', user));
  53. });
  54. // Apply the label to the results.
  55. return $.when.apply($.when, promises).then(function() {
  56. var args = arguments;
  57. var i = 0;
  58. $.each(results, function(index, user) {
  59. user._label = args[i++];
  60. });
  61. success(results);
  62. return;
  63. });
  64. }).fail(failure);
  65. }
  66. };
  67. });