addCollectionWidget.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. (function ($) {
  2. $.fn.addCollection = function() {
  3. function requete(chemin, handleData) {
  4. $.ajax({
  5. url: chemin,
  6. type: 'POST',
  7. dataType: 'json',
  8. success: function (reponse) {
  9. let reponseArray = parseJson(reponse);
  10. handleData(reponseArray);
  11. }
  12. })
  13. }
  14. function parseJson(data) {
  15. let tableau = [];
  16. for (let i = 0; i < data.length; i++) {
  17. let UnObjetJson = data[i];
  18. let obj = JSON.parse(UnObjetJson);
  19. sortie = Object.values(obj)
  20. tableau.push(sortie[0]);
  21. }
  22. return tableau;
  23. }
  24. function addDeleteLink($prototype) {
  25. // Création du lien
  26. let $deleteLink = $('<button type="button" class="btn btn-outline-secondary"><i class="fa fa-trash fa-lg text-danger"></i></button>');
  27. // Ajout du lien
  28. $prototype.find(":input").after($deleteLink);
  29. // Ajout du listener sur le clic du lien pour effectivement supprimer la catégorie
  30. $deleteLink.on("click", function(e) {
  31. $prototype.remove();
  32. e.preventDefault(); // évite qu'un # apparaisse dans l'URL
  33. return false;
  34. });
  35. }
  36. this.each(function() {
  37. // Chemin pour la requête
  38. var chemin = $(this).data('path');
  39. // On récupère le fieldset pour ajouter les delete-link aux éléments existants
  40. var $container = $($(this).attr("data-list-selector"));
  41. $li = $container.find('li');
  42. $li.each(function() {
  43. if (chemin !== "") {
  44. $(this).find(':input').prop("readonly", true);
  45. }
  46. addDeleteLink($(this));
  47. })
  48. $(this).on("click", function(e) {
  49. e.preventDefault();
  50. var list = jQuery(jQuery(this).attr('data-list-selector'));
  51. // Try to find the counter of the list or use the length of the list
  52. var counter = list.data('widget-counter') | list.children().length;
  53. // grab the prototype template
  54. var newWidget = list.attr('data-prototype');
  55. // replace the "__name__" used in the id and name of the prototype
  56. // with a number that's unique to your emails
  57. // end name attribute looks like name="contact[emails][2]"
  58. newWidget = newWidget.replace(/__name__/g, counter);
  59. // Increase the counter
  60. counter++;
  61. // And store it, the length cannot be used if deleting widgets is allowed
  62. list.data('widget-counter', counter);
  63. // create a new list element and add it to the list
  64. var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
  65. if (chemin !== "") {
  66. requete (chemin, function(output) {
  67. newElem.find(':input').autocomplete({
  68. source: output
  69. });
  70. });
  71. }
  72. addDeleteLink(newElem);
  73. newElem.appendTo(list);
  74. })
  75. })
  76. }
  77. })(jQuery);