Admin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. This file is part of the Sonata package.
  3. (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  4. For the full copyright and license information, please view the LICENSE
  5. file that was distributed with this source code.
  6. */
  7. jQuery(document).ready(function() {
  8. jQuery('html').removeClass('no-js');
  9. if (window.SONATA_CONFIG && window.SONATA_CONFIG.CONFIRM_EXIT) {
  10. jQuery('.sonata-ba-form form').each(function () { jQuery(this).confirmExit(); });
  11. }
  12. Admin.setup_per_page_switcher(document);
  13. Admin.shared_setup(document);
  14. });
  15. jQuery(document).on('sonata-admin-append-form-element', function(e) {
  16. Admin.setup_select2(e.target);
  17. Admin.setup_icheck(e.target);
  18. });
  19. var Admin = {
  20. /**
  21. * This function must called when a ajax call is done, to ensure
  22. * retrieve html is properly setup
  23. *
  24. * @param subject
  25. */
  26. shared_setup: function(subject) {
  27. Admin.log("[core|shared_setup] Register services on", subject);
  28. Admin.setup_collection_buttons(subject);
  29. Admin.set_object_field_value(subject);
  30. Admin.setup_select2(subject);
  31. Admin.setup_icheck(subject);
  32. Admin.add_filters(subject);
  33. Admin.setup_xeditable(subject);
  34. Admin.add_pretty_errors(subject);
  35. Admin.setup_form_tabs_for_errors(subject);
  36. Admin.setup_inline_form_errors(subject);
  37. Admin.setup_tree_view(subject);
  38. // Admin.setup_list_modal(subject);
  39. },
  40. setup_list_modal: function(modal) {
  41. Admin.log('[core|setup_list_modal] configure modal on', modal);
  42. // this will force relation modal to open list of entity in a wider modal
  43. // to improve readability
  44. jQuery('div.modal-dialog', modal).css({
  45. width: '90%', //choose your width
  46. height: '85%',
  47. padding: 0
  48. });
  49. jQuery('div.modal-content', modal).css({
  50. 'border-radius':'0',
  51. height: '100%',
  52. padding: 0
  53. });
  54. jQuery('.modal-body', modal).css({
  55. width: 'auto',
  56. height: '90%',
  57. padding: 5,
  58. overflow: 'scroll'
  59. });
  60. },
  61. setup_select2: function(subject) {
  62. if (window.SONATA_CONFIG && window.SONATA_CONFIG.USE_SELECT2 && window.Select2) {
  63. Admin.log('[core|setup_select2] configure Select2 on', subject);
  64. jQuery('select:not([data-sonata-select2="false"])', subject).each(function() {
  65. var select = jQuery(this);
  66. var allowClearEnabled = false;
  67. if (select.find('option[value=""]').length) {
  68. allowClearEnabled = true;
  69. }
  70. if (select.attr('data-sonata-select2-allow-clear')==='true') {
  71. allowClearEnabled = true;
  72. } else if (select.attr('data-sonata-select2-allow-clear')==='false') {
  73. allowClearEnabled = false;
  74. }
  75. ereg = /width:(auto|(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc)))/i;
  76. select.select2({
  77. width: function() {
  78. // this code is an adaptation of select2 code (initContainerWidth function)
  79. style = this.element.attr('style');
  80. //console.log("main style", style);
  81. if (style !== undefined) {
  82. attrs = style.split(';');
  83. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  84. matches = attrs[i].replace(/\s/g, '').match(ereg);
  85. if (matches !== null && matches.length >= 1)
  86. return matches[1];
  87. }
  88. }
  89. style = this.element.css('width');
  90. if (style.indexOf("%") > 0) {
  91. return style;
  92. }
  93. return '100%';
  94. },
  95. dropdownAutoWidth: true,
  96. minimumResultsForSearch: 10,
  97. allowClear: allowClearEnabled
  98. });
  99. var popover = select.data('popover');
  100. if (undefined !== popover) {
  101. select
  102. .select2('container')
  103. .popover(popover.options)
  104. ;
  105. }
  106. });
  107. }
  108. },
  109. setup_icheck: function(subject) {
  110. if (window.SONATA_CONFIG && window.SONATA_CONFIG.USE_ICHECK) {
  111. Admin.log('[core|setup_icheck] configure iCheck on', subject);
  112. jQuery("input[type='checkbox']:not('label.btn>input'), input[type='radio']:not('label.btn>input')", subject).iCheck({
  113. checkboxClass: 'icheckbox_minimal',
  114. radioClass: 'iradio_minimal'
  115. });
  116. }
  117. },
  118. setup_xeditable: function(subject) {
  119. Admin.log('[core|setup_xeditable] configure xeditable on', subject);
  120. jQuery('.x-editable', subject).editable({
  121. emptyclass: 'editable-empty btn btn-sm',
  122. emptytext: '<i class="glyphicon glyphicon-edit"></i>',
  123. container: 'body',
  124. success: function(response) {
  125. if('KO' === response.status) {
  126. return response.message;
  127. }
  128. var html = jQuery(response.content);
  129. Admin.setup_xeditable(html);
  130. jQuery(this)
  131. .closest('td')
  132. .replaceWith(html)
  133. ;
  134. }
  135. });
  136. },
  137. /**
  138. * render log message
  139. * @param mixed
  140. */
  141. log: function() {
  142. var msg = '[Sonata.Admin] ' + Array.prototype.join.call(arguments,', ');
  143. if (window.console && window.console.log) {
  144. window.console.log(msg);
  145. } else if (window.opera && window.opera.postError) {
  146. window.opera.postError(msg);
  147. }
  148. },
  149. /**
  150. * display related errors messages
  151. *
  152. * @param subject
  153. */
  154. add_pretty_errors: function(subject) {
  155. Admin.log('[core|add_pretty_errors] configure pretty errors on', subject);
  156. jQuery('div.sonata-ba-field-error', subject).each(function(index, element) {
  157. var input = jQuery(':input', element);
  158. if (!input.length) {
  159. return;
  160. }
  161. var message = jQuery('div.sonata-ba-field-error-messages', element).html();
  162. jQuery('div.sonata-ba-field-error-messages', element).remove();
  163. if (!message || message.length == 0) {
  164. return;
  165. }
  166. var target = input,
  167. fieldShortDescription = input.closest('.field-container').find('.field-short-description'),
  168. select2 = input.closest('.select2-container')
  169. ;
  170. if (fieldShortDescription.length) {
  171. target = fieldShortDescription;
  172. } else if (select2.length) {
  173. target= select2;
  174. }
  175. target.popover({
  176. content: message,
  177. trigger: 'hover',
  178. html: true,
  179. placement: 'top',
  180. template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content alert-error"><p></p></div></div></div>'
  181. });
  182. });
  183. },
  184. stopEvent: function(event) {
  185. // https://github.com/sonata-project/SonataAdminBundle/issues/151
  186. //if it is a standard browser use preventDefault otherwise it is IE then return false
  187. if(event.preventDefault) {
  188. event.preventDefault();
  189. } else {
  190. event.returnValue = false;
  191. }
  192. //if it is a standard browser get target otherwise it is IE then adapt syntax and get target
  193. if (typeof event.target != 'undefined') {
  194. targetElement = event.target;
  195. } else {
  196. targetElement = event.srcElement;
  197. }
  198. return targetElement;
  199. },
  200. add_filters: function(subject) {
  201. Admin.log('[core|add_filters] configure filters on', subject);
  202. jQuery('a.sonata-toggle-filter', subject).on('click', function(e) {
  203. e.preventDefault();
  204. e.stopPropagation();
  205. if (jQuery(e.target).attr('sonata-filter') == 'false') {
  206. return;
  207. }
  208. Admin.log('[core|add_filters] handle filter container: ', jQuery(e.target).attr('filter-container'))
  209. var filters_container = jQuery('#' + jQuery(e.target).attr('filter-container'));
  210. if (jQuery('div.form-group:visible', filters_container).length == 0) {
  211. jQuery(filters_container).slideDown();
  212. }
  213. var target = jQuery('div[id="' + jQuery(e.target).attr('filter-target') + '"]', filters_container);
  214. if (jQuery(target).is(":visible")) {
  215. jQuery('i', this).removeClass('fa-check-square-o');
  216. jQuery('i', this).addClass('fa-square-o');
  217. target.hide();
  218. } else {
  219. jQuery('i', this).removeClass('fa-square-o');
  220. jQuery('i', this).addClass('fa-check-square-o');
  221. target.show();
  222. }
  223. if (jQuery('div.form-group:visible', filters_container).length > 0) {
  224. jQuery(filters_container).slideDown();
  225. } else {
  226. jQuery(filters_container).slideUp();
  227. }
  228. });
  229. },
  230. /**
  231. * Change object field value
  232. * @param subject
  233. */
  234. set_object_field_value: function(subject) {
  235. Admin.log('[core|set_object_field_value] set value field on', subject);
  236. this.log(jQuery('a.sonata-ba-edit-inline', subject));
  237. jQuery('a.sonata-ba-edit-inline', subject).click(function(event) {
  238. Admin.stopEvent(event);
  239. var subject = jQuery(this);
  240. jQuery.ajax({
  241. url: subject.attr('href'),
  242. type: 'POST',
  243. success: function(json) {
  244. if(json.status === "OK") {
  245. var elm = jQuery(subject).parent();
  246. elm.children().remove();
  247. // fix issue with html comment ...
  248. elm.html(jQuery(json.content.replace(/<!--[\s\S]*?-->/g, "")).html());
  249. elm.effect("highlight", {'color' : '#57A957'}, 2000);
  250. Admin.set_object_field_value(elm);
  251. } else {
  252. jQuery(subject).parent().effect("highlight", {'color' : '#C43C35'}, 2000);
  253. }
  254. }
  255. });
  256. });
  257. },
  258. setup_collection_buttons: function(subject) {
  259. Admin.log('[core|setup_collection_buttons] setup collection buttons', subject);
  260. jQuery(subject).on('click', '.sonata-collection-add', function(event) {
  261. Admin.stopEvent(event);
  262. var container = jQuery(this).closest('[data-prototype]');
  263. var proto = container.attr('data-prototype');
  264. var protoName = container.attr('data-prototype-name') || '__name__';
  265. // Set field id
  266. var idRegexp = new RegExp(container.attr('id')+'_'+protoName,'g');
  267. proto = proto.replace(idRegexp, container.attr('id')+'_'+(container.children().length - 1));
  268. // Set field name
  269. var parts = container.attr('id').split('_');
  270. var nameRegexp = new RegExp(parts[parts.length-1]+'\\]\\['+protoName,'g');
  271. proto = proto.replace(nameRegexp, parts[parts.length-1]+']['+(container.children().length - 1));
  272. jQuery(proto)
  273. .insertBefore(jQuery(this).parent())
  274. .trigger('sonata-admin-append-form-element')
  275. ;
  276. jQuery(this).trigger('sonata-collection-item-added');
  277. });
  278. jQuery(subject).on('click', '.sonata-collection-delete', function(event) {
  279. Admin.stopEvent(event);
  280. jQuery(this).trigger('sonata-collection-item-deleted');
  281. jQuery(this).closest('.sonata-collection-row').remove();
  282. });
  283. },
  284. setup_per_page_switcher: function(subject) {
  285. Admin.log('[core|setup_per_page_switcher] setup page switcher', subject);
  286. jQuery('select.per-page').change(function(event) {
  287. jQuery('input[type=submit]').hide();
  288. window.top.location.href=this.options[this.selectedIndex].value;
  289. });
  290. },
  291. setup_form_tabs_for_errors: function(subject) {
  292. Admin.log('[core|setup_form_tabs_for_errors] setup form tab\'s errors', subject);
  293. // Switch to first tab with server side validation errors on page load
  294. jQuery('form', subject).each(function() {
  295. Admin.show_form_first_tab_with_errors(jQuery(this), '.sonata-ba-field-error');
  296. });
  297. // Switch to first tab with HTML5 errors on form submit
  298. jQuery(subject)
  299. .on('click', 'form [type="submit"]', function() {
  300. Admin.show_form_first_tab_with_errors(jQuery(this).closest('form'), ':invalid');
  301. })
  302. .on('keypress', 'form [type="text"]', function(e) {
  303. if (13 === e.which) {
  304. Admin.show_form_first_tab_with_errors(jQuery(this), ':invalid');
  305. }
  306. })
  307. ;
  308. },
  309. show_form_first_tab_with_errors: function(form, errorSelector) {
  310. Admin.log('[core|show_form_first_tab_with_errors] show first tab with errors', form);
  311. var tabs = form.find('.nav-tabs a'), firstTabWithErrors;
  312. tabs.each(function() {
  313. var id = jQuery(this).attr('href'),
  314. tab = jQuery(this),
  315. icon = tab.find('.has-errors');
  316. if (jQuery(id).find(errorSelector).length > 0) {
  317. // Only show first tab with errors
  318. if (!firstTabWithErrors) {
  319. tab.tab('show');
  320. firstTabWithErrors = tab;
  321. }
  322. icon.removeClass('hide');
  323. } else {
  324. icon.addClass('hide');
  325. }
  326. });
  327. },
  328. setup_inline_form_errors: function(subject) {
  329. Admin.log('[core|setup_inline_form_errors] show first tab with errors', subject);
  330. var deleteCheckboxSelector = '.sonata-ba-field-inline-table [id$="_delete"][type="checkbox"]';
  331. jQuery(deleteCheckboxSelector, subject).each(function() {
  332. Admin.switch_inline_form_errors(jQuery(this));
  333. });
  334. jQuery(subject).on('change', deleteCheckboxSelector, function() {
  335. Admin.switch_inline_form_errors(jQuery(this));
  336. });
  337. },
  338. /**
  339. * Disable inline form errors when the row is marked for deletion
  340. */
  341. switch_inline_form_errors: function(subject) {
  342. Admin.log('[core|switch_inline_form_errors] switch_inline_form_errors', subject);
  343. var row = subject.closest('.sonata-ba-field-inline-table'),
  344. errors = row.find('.sonata-ba-field-error-messages')
  345. ;
  346. if (subject.is(':checked')) {
  347. row
  348. .find('[required]')
  349. .removeAttr('required')
  350. .attr('data-required', 'required')
  351. ;
  352. errors.hide();
  353. } else {
  354. row
  355. .find('[data-required]')
  356. .attr('required', 'required')
  357. ;
  358. errors.show();
  359. }
  360. },
  361. setup_tree_view: function(subject) {
  362. Admin.log('[core|setup_tree_view] setup tree view', subject);
  363. jQuery('ul.js-treeview', subject).treeView();
  364. }
  365. };