form_configurable.js.coffee 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. $ ->
  2. getFormData = (elem) ->
  3. form_data = $("#edit_agent, #new_agent").serializeObject()
  4. attribute = $(elem).data('attribute')
  5. form_data['attribute'] = attribute
  6. delete form_data['_method']
  7. form_data
  8. window.initializeFormCompletable = ->
  9. returnedResults = {}
  10. completableDefaultOptions = (input) ->
  11. results: [
  12. (returnedResults[$(input).data('attribute')] || {text: 'Options', children: [{id: undefined, text: 'loading ...'}]}),
  13. {
  14. text: 'Current',
  15. children: [id: $(input).val(), text: $(input).val()]
  16. },
  17. {
  18. text: 'Custom',
  19. children: [id: 'manualInput', text: 'manual input']
  20. },
  21. ]
  22. $("input[role~=validatable], select[role~=validatable]").on 'change', (e) =>
  23. form_data = getFormData(e.currentTarget)
  24. form_group = $(e.currentTarget).closest('.form-group')
  25. $.ajax '/agents/validate',
  26. type: 'POST',
  27. data: form_data
  28. success: (data) ->
  29. form_group.addClass('has-feedback').removeClass('has-error')
  30. form_group.find('span').addClass('hidden')
  31. form_group.find('.glyphicon-ok').removeClass('hidden')
  32. returnedResults = {}
  33. error: (data) ->
  34. form_group.addClass('has-feedback').addClass('has-error')
  35. form_group.find('span').addClass('hidden')
  36. form_group.find('.glyphicon-remove').removeClass('hidden')
  37. returnedResults = {}
  38. $("input[role~=validatable], select[role~=validatable]").trigger('change')
  39. $.each $("input[role~=completable]"), (i, input) ->
  40. $(input).select2(
  41. data: ->
  42. completableDefaultOptions(input)
  43. ).on("change", (e) ->
  44. if e.added && e.added.id == 'manualInput'
  45. $(e.currentTarget).select2("destroy")
  46. $(e.currentTarget).val(e.removed.id)
  47. )
  48. updateDropdownData = (form_data, element, data) ->
  49. returnedResults[form_data.attribute] = {text: 'Options', children: data}
  50. $(element).trigger('change')
  51. $(element).select2('open')
  52. $("input[role~=completable]").on 'select2-open', (e) ->
  53. form_data = getFormData(e.currentTarget)
  54. return if returnedResults[form_data.attribute]
  55. $.ajax '/agents/complete',
  56. type: 'POST',
  57. data: form_data
  58. success: (data) ->
  59. updateDropdownData(form_data, e.currentTarget, data)
  60. error: (data) ->
  61. updateDropdownData(form_data, e.currentTarget, [{id: undefined, text: 'Error loading data.'}])
  62. $("input[type=radio][role~=form-configurable]").change (e) ->
  63. input = $(e.currentTarget).parents().siblings("input[data-attribute=#{$(e.currentTarget).data('attribute')}]")
  64. if $(e.currentTarget).val() == 'manual'
  65. input.removeClass('hidden')
  66. else
  67. input.val($(e.currentTarget).val())
  68. input.addClass('hidden')