Completed
Push — master ( cb8392...3a1609 )
by Dimas
09:53
created

roles.js ➔ buildData   A

Complexity

Conditions 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
c 0
b 0
f 0
dl 0
loc 15
rs 9.3333
1
function deleteRole(role) {
2
  console.log(getFuncName(), role);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
3
}
4
AjaxForm();
5
/**
6
 * Initialize global data source
7
 */
8
var dataSource = [];
9
var clonedCol = null;
10
11
jQuery(document).ready(function () {
12
  load_module(["select2"], function () {
13
    loadCSS("/assets/css/select2.min.css", function () {
14
      $.ajax({
15
        url: "",
16
        method: "post",
17
        data: {
18
          getAccess: guid(),
19
        },
20
        success: function (selectOptions) {
21
          if (selectOptions && Array.isArray(selectOptions)) {
22
            selectOptions.forEach(function (data, index) {
23
              dataSource.push({ text: data, id: data });
24
            });
25
          }
26
          //console.log(dataSource);
27
          initializeSelect2();
28
        },
29
      });
30
    });
31
  });
32
33
  $('[id^="add-select-"]').click(function (e) {
34
    e.preventDefault();
35
  });
36
37
  jQuery(document).on(
38
    "change",
39
    'select[id^="Roles-"],select[id^="Access-"]',
40
    buildData
41
  );
42
});
43
44
function initializeSelect2() {
45
  jQuery('[id^="select-"],select.select2').each(function (index, value) {
46
    var t = jQuery(this);
47
    if (t.data("select2")) {
48
      console.error("select2 already initialized on " + t.attr("id"));
49
      return;
50
    }
51
    t.select2({
52
      data: dataSource.filter(onlyUnique),
53
      theme: "material",
54
      placeholder: "Select a route",
55
      allowClear: true,
56
    });
57
    var val = jQuery(this).data("key");
58
    if (val && val.length) {
59
      t.val(val).trigger("change");
60
    }
61
    //console.log(val);
62
  });
63
}
64
65
function buildData(e) {
66
  var wrapselgrab = $("form#access-management").find("div[id^=Roles-]");
67
  if (wrapselgrab.length) {
68
    wrapselgrab.each(function (index, el) {
69
      var selgrab = $(this).find("select");
70
      if (selgrab.length) {
71
        for (let index = 1; index < selgrab.length; index++) {
72
          var element = selgrab[index];
73
          element.setAttribute("name", `access[${selgrab[0].value}][]`);
74
          //console.log(selgrab[index].getAttribute("name"));
75
        }
76
      }
77
    });
78
  }
79
}
80
81
/**
82
 * Get unique array
83
 * @param {any} value
84
 * @param {any} index
85
 * @param {any[]} self
86
 * @example dataArray.filter(onlyUnique)
87
 */
88
function onlyUnique(value, index, self) {
89
  return self.indexOf(value) === index;
90
}
91