lib/amd/src/form-cohort-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. * Course selector adaptor for auto-complete form element.
  17. *
  18. * @module core/form-cohort-selector
  19. * @copyright 2016 Damyon Wiese <damyon@moodle.com>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. * @since 3.1
  22. */
  23. define(['core/ajax', 'jquery'], function(ajax, $) {
  24. return {
  25. // Public variables and functions.
  26. processResults: function(selector, data) {
  27. // Mangle the results into an array of objects.
  28. var results = [];
  29. var i = 0;
  30. var excludelist = String($(selector).data('exclude')).split(',');
  31. for (i = 0; i < data.cohorts.length; i++) {
  32. if (excludelist.indexOf(String(data.cohorts[i].id)) === -1) {
  33. results.push({value: data.cohorts[i].id, label: data.cohorts[i].name});
  34. }
  35. }
  36. return results;
  37. },
  38. transport: function(selector, query, success, failure) {
  39. var el = $(selector);
  40. // Parse some data-attributes from the form element.
  41. // Build the query.
  42. var promises = null;
  43. if (typeof query === "undefined") {
  44. query = '';
  45. }
  46. var includes = el.data('includes');
  47. var contextid = el.data('contextid');
  48. var searchargs = {
  49. query: query,
  50. includes: includes,
  51. limitfrom: 0,
  52. limitnum: 100,
  53. context: {contextid: contextid}
  54. };
  55. var calls = [{
  56. methodname: 'core_cohort_search_cohorts', args: searchargs
  57. }];
  58. // Go go go!
  59. promises = ajax.call(calls);
  60. $.when.apply($.when, promises).done(function(data) {
  61. success(data);
  62. }).fail(failure);
  63. }
  64. };
  65. });