form_configurable.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. $(function () {
  2. const getFormData = function (elem) {
  3. const form_data = $("#edit_agent, #new_agent").serializeObject();
  4. const attribute = $(elem).data("attribute");
  5. form_data["attribute"] = attribute;
  6. delete form_data["_method"];
  7. return form_data;
  8. };
  9. return (window.initializeFormCompletable = function () {
  10. $("input[role~=validatable], select[role~=validatable]").on(
  11. "change",
  12. (e) => {
  13. const form_data = getFormData(e.currentTarget);
  14. const form_group = $(e.currentTarget).closest(".form-group");
  15. return $.ajax("/agents/validate", {
  16. type: "POST",
  17. data: form_data,
  18. success: (data) => {
  19. form_group.addClass("has-feedback").removeClass("has-error");
  20. form_group.find("span").addClass("hidden");
  21. form_group.find(".glyphicon-ok").removeClass("hidden");
  22. },
  23. error: (data) => {
  24. form_group.addClass("has-feedback").addClass("has-error");
  25. form_group.find("span").addClass("hidden");
  26. form_group.find(".glyphicon-remove").removeClass("hidden");
  27. },
  28. });
  29. }
  30. );
  31. $("input[role~=validatable], select[role~=validatable]").trigger("change");
  32. $.each($("select[role~=completable]"), (i, select) => {
  33. const $select = $(select);
  34. const value = $select.data("value");
  35. const setValue = (value) => {
  36. if (
  37. $select
  38. .find("option")
  39. .toArray()
  40. .some((option) => option.value == value)
  41. ) {
  42. $select.val(value).trigger("change");
  43. } else {
  44. $select
  45. .append(new Option(value, value, true, true))
  46. .trigger("change");
  47. }
  48. };
  49. if ($select.data("cacheResponse")) {
  50. const loadData = (data) => {
  51. $select.select2({ data: data, tags: true });
  52. setValue(value);
  53. };
  54. $.ajax("/agents/complete", {
  55. type: "POST",
  56. data: getFormData(select),
  57. success: (data) => loadData(data),
  58. error: (data) =>
  59. loadData([{ id: undefined, text: "Error loading data." }]),
  60. });
  61. } else {
  62. $select.select2({
  63. ajax: {
  64. url: "/agents/complete",
  65. type: "POST",
  66. data: (params) => getFormData(select),
  67. processResults: (data) => ({ results: data }),
  68. },
  69. tags: true,
  70. });
  71. setValue(value);
  72. }
  73. });
  74. $("input[type=radio][role~=form-configurable]").change(function (e) {
  75. const input = $(e.currentTarget)
  76. .parents()
  77. .siblings(
  78. `input[data-attribute=${$(e.currentTarget).data("attribute")}]`
  79. );
  80. if ($(e.currentTarget).val() === "manual") {
  81. input.removeClass("hidden");
  82. } else {
  83. input.val($(e.currentTarget).val());
  84. input.addClass("hidden");
  85. }
  86. });
  87. });
  88. });