forked from pollen8/fabrik
/
form.js
2901 lines (2648 loc) · 123 KB
/
form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Form
*
* @copyright: Copyright (C) 2005-2013, fabrikar.com - All rights reserved.
* @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
define(['jquery', 'fab/encoder', 'fab/fabrik', 'lib/debounce/jquery.ba-throttle-debounce'],
function (jQuery, Encoder, Fabrik, Debounce) {
var FbForm = new Class({
Implements: [Options, Events],
options: {
'rowid' : '',
'admin' : false,
'ajax' : false,
'primaryKey' : null,
'error' : '',
'submitOnEnter' : false,
'updatedMsg' : 'Form saved',
'pages' : [],
'start_page' : 0,
'multipage_save': 0,
'ajaxValidation': false,
'showLoader' : false,
'customJsAction': '',
'plugins' : {},
'ajaxmethod' : 'post',
'inlineMessage' : true,
'print' : false,
'toggleSubmit' : false,
'toggleSubmitTip': 'must validate',
'mustValidate' : false,
'lang' : false,
'debounceDelay' : 500,
'images' : {
'alert' : '',
'action_check': '',
'ajax_loader' : ''
}
},
initialize: function (id, options) {
// $$$ hugh - seems options.rowid can be null in certain corner cases, so defend against that
if (typeOf(options.rowid) === 'null') {
options.rowid = '';
}
this.id = id;
//set this to false in window.fireEvents to stop current action (e.g. stop form submission)
this.result = true;
this.setOptions(options);
this.options.pages = $H(this.options.pages);
this.subGroups = $H({});
this.currentPage = this.options.start_page;
this.formElements = $H({});
this.hasErrors = $H({});
this.mustValidateEls = $H({});
this.toggleSubmitTipAdded = false;
this.elements = this.formElements;
this.duplicatedGroups = $H({});
this.addingOrDeletingGroup = false;
this.addedGroups = [];
this.watchRepeatNumsDone = false;
this.fx = {};
this.fx.elements = [];
this.fx.hidden = [];
this.fx.validations = {};
this.setUpAll();
this._setMozBoxWidths();
if (this.options.editable) {
(function () {
this.duplicateGroupsToMin();
}.bind(this)).delay(1000);
}
// Delegated element events
this.events = {};
this.submitBroker = new FbFormSubmit();
this.scrollTips();
Fabrik.fireEvent('fabrik.form.loaded', [this]);
},
_setMozBoxWidths: function () {
if (Browser.firefox && this.getForm()) {
//as firefox treats display:-moz-box as display:-moz-box-inline we have to programatically set their widths
this.getForm().getElements('.fabrikElementContainer > .displayBox').each(function (b) {
var computed = b.getParent().getComputedSize();
//remove margins/paddings from width
var x = b.getParent().getSize().x - (computed.computedLeft + computed.computedRight);
var w = b.getParent().getSize().x === 0 ? 400 : x;
b.setStyle('width', w + 'px');
var e = b.getElement('.fabrikElement');
if (typeOf(e) !== 'null') {
x = 0;
b.getChildren().each(function (c) {
if (c !== e) {
x += c.getSize().x;
}
});
e.setStyle('width', w - x - 10 + 'px');
}
});
}
},
setUpAll: function () {
this.setUp();
// add a wrapper if we're going to be using the tooltip, as can't do tooltip on disabled elements
if (this.options.ajaxValidation && this.options.toggleSubmit && this.options.toggleSubmitTip !== '') {
var submit = this._getButton('Submit');
if (typeOf(submit) !== 'null') {
jQuery(submit).wrap('<div data-toggle="tooltip" title="' + Joomla.JText._('COM_FABRIK_MUST_VALIDATE') +
'" class="fabrikSubmitWrapper" style="display: inline-block"></div>div>');
}
}
this.winScroller = new Fx.Scroll(window);
if (this.form) {
if (this.options.ajax || this.options.submitOnEnter === false) {
this.stopEnterSubmitting();
}
this.watchAddOptions();
}
if (this.options.editable) {
$H(this.options.hiddenGroup).each(function (v, k) {
if (v === true && typeOf(document.id('group' + k)) !== 'null') {
var subGroup = document.id('group' + k).getElement('.fabrikSubGroup');
this.subGroups.set(k, subGroup.cloneWithIds());
this.hideLastGroup(k, subGroup);
}
}.bind(this));
this.setupSortable();
}
// get an int from which to start incrementing for each repeated group id
// don't ever decrease this value when deleting a group as it will cause all sorts of
// reference chaos with cascading dropdowns etc.
this.repeatGroupMarkers = $H({});
if (this.form) {
this.form.getElements('.fabrikGroup').each(function (group) {
var id = group.id.replace('group', '');
var c = group.getElements('.fabrikSubGroup').length;
//if no joined repeating data then c should be 0 and not 1
if (c === 1) {
if (group.getElement('.fabrikSubGroupElements').getStyle('display') === 'none') {
c = 0;
}
}
this.repeatGroupMarkers.set(id, c);
}.bind(this));
this.watchGoBackButton();
}
this.watchPrintButton();
this.watchPdfButton();
this.watchTabs();
this.watchRepeatNums();
},
watchRepeatNums: function () {
Fabrik.addEvent('fabrik.form.elements.added', function (form) {
if (form.id === this.id && !this.watchRepeatNumsDone) {
Object.each(this.options.numRepeatEls, function (name, key) {
if (name !== '') {
var el = this.formElements.get(name);
if (el) {
el.addNewEventAux(el.getChangeEvent(), function(event) {
var v = el.getValue();
this.options.minRepeat[key] = v.toInt();
this.options.maxRepeat[key] = v.toInt();
this.duplicateGroupsToMin();
}.bind(this, el, key));
}
}
}.bind(form));
this.watchRepeatNumsDone = true;
}
}.bind(this));
},
/**
* Print button action - either open up the print preview window - or print if already opened
*/
watchPrintButton: function () {
this.form.getElements('a[data-fabrik-print]').addEvent('click', function (e) {
e.stop();
if (this.options.print) {
window.print();
} else {
// Build URL as we could have changed the rowid via ajax pagination
var url = jQuery(e.target).prop('href');
url = url.replace(/&rowid=\d+/, '&rowid=' + this.options.rowid);
if (this.options.lang !== false) {
if (url.test(/\?/)) {
url += '&lang=' + this.options.lang;
}
else {
url += '?lang=' + this.options.lang;
}
}
var width = jQuery(e.target).data('fabrik-print-width');
if (width === 'undefined') {
width = '400';
}
var height = jQuery(e.target).data('fabrik-print-height');
if (height === 'undefined') {
height = '350';
}
var features = 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes';
features += ',width=' + width + ',height=' + height;
features += ',directories=no,location=no;'
window.open(
url,
'win2',
features
);
}
}.bind(this));
},
/**
* PDF button action.
*/
watchPdfButton: function () {
this.form.getElements('*[data-role="open-form-pdf"]').addEvent('click', function (e) {
e.stop();
// Build URL as we could have changed the rowid via ajax pagination.
// @FIXME for SEF
var url = e.event.currentTarget.href.replace(/(rowid=\d*)/, 'rowid=' + this.options.rowid);
if (this.options.lang !== false) {
if (url.test(/\?/)) {
url += '&lang=' + this.options.lang;
}
else {
url += '?lang=' + this.options.lang;
} }
window.location = url;
}.bind(this));
},
/**
* Go back button in ajax pop up window should close the window
*/
watchGoBackButton: function () {
if (this.options.ajax) {
var goback = this._getButton('Goback');
if (typeOf(goback) === 'null') {
return;
}
goback.addEvent('click', function (e) {
e.stop();
if (Fabrik.Windows[this.options.fabrik_window_id]) {
Fabrik.Windows[this.options.fabrik_window_id].close();
}
else {
// $$$ hugh - http://fabrikar.com/forums/showthread.php?p=166140#post166140
window.history.back();
}
}.bind(this));
}
},
watchAddOptions: function () {
this.fx.addOptions = [];
this.getForm().getElements('.addoption').each(function (d) {
var a = d.getParent('.fabrikElementContainer').getElement('.toggle-addoption');
var mySlider = new Fx.Slide(d, {
duration: 500
});
mySlider.hide();
a.addEvent('click', function (e) {
e.stop();
mySlider.toggle();
});
});
},
setUp: function () {
this.form = this.getForm();
this.watchGroupButtons();
// Submit can appear in confirmation plugin even when readonly
this.watchSubmit();
this.createPages();
this.watchClearSession();
},
getForm: function () {
if (typeOf(this.form) === 'null') {
this.form = document.id(this.getBlock());
}
return this.form;
},
getBlock: function () {
if (typeOf(this.block) === 'null') {
this.block = this.options.editable === true ? 'form_' + this.id : 'details_' + this.id;
if (this.options.rowid !== '') {
this.block += '_' + this.options.rowid;
}
}
return this.block;
},
/**
* Attach an effect to an elements
*
* @param {string} id Element or group to apply the fx TO, triggered from another element
* @param {string} method JS event which triggers the effect (click,change etc.)
*
* @return {*} false if no element found or element fx
*/
addElementFX: function (id, method) {
var c, k, fxdiv;
id = id.replace('fabrik_trigger_', '');
// Paul - add sanity checking and error reporting
if (id.slice(0, 6) === 'group_') {
id = id.slice(6, id.length);
k = id;
c = document.id(id);
if (!c) {
fconsole('Fabrik form::addElementFX: Group "' + id + '" does not exist.');
return false;
}
} else if (id.slice(0, 8) === 'element_') {
id = id.slice(8, id.length);
k = 'element' + id;
c = document.id(id);
if (!c) {
fconsole('Fabrik form::addElementFX: Element "' + id + '" does not exist.');
return false;
}
c = c.getParent('.fabrikElementContainer');
if (!c) {
fconsole('Fabrik form::addElementFX: Element "' + id + '.fabrikElementContainer" does not exist.');
return false;
}
} else {
fconsole('Fabrik form::addElementFX: Not an element or group: ' + id);
return false;
}
if (c) {
// c will be the <li> element - you can't apply fx's to this as it makes the
// DOM squiffy with multi column rows, so get the li's content and put it
// inside a div which is injected into c
// apply fx to div rather than li - damn I'm good
var tag = (c).get('tag');
if (tag === 'li' || tag === 'td') {
fxdiv = new Element('div', {'style': 'width:100%'}).adopt(c.getChildren());
c.empty();
fxdiv.inject(c);
} else {
fxdiv = c;
}
var opts = {
duration : 800,
transition: Fx.Transitions.Sine.easeInOut
};
if (typeOf(this.fx.elements[k]) === 'null') {
this.fx.elements[k] = {};
}
this.fx.elements[k].css = new Fx.Morph(fxdiv, opts);
if (typeOf(fxdiv) !== 'null' && (method === 'slide in' || method === 'slide out' || method === 'slide toggle')) {
this.fx.elements[k].slide = new Fx.Slide(fxdiv, opts);
}
return this.fx.elements[k];
}
return false;
},
/**
* An element state has changed, so lets run any associated effects
*
* @param {string} id Element id to run the effect on
* @param {string} method Method to run
* @param {object} elementModel The element JS object which is calling the fx, this is used to work ok which
* repeat group the fx is applied on
*/
doElementFX: function (id, method, elementModel) {
var k, groupfx, fx, fxElement;
// Could be the source element is in a repeat group but the target is not.
var target = this.formElements.get(id.replace('fabrik_trigger_element_', '')),
targetInRepeat = true;
if (target) {
targetInRepeat = target.options.inRepeatGroup;
}
if (id.slice(0, 21) === 'fabrik_trigger_group_') {
groupfx = true;
}
else {
groupfx = false;
}
// Update the element id that we will apply the fx to to be that of the calling elementModels group
// (if in a repeat group)
if (elementModel && targetInRepeat && !groupfx) {
if (elementModel.options.inRepeatGroup) {
var bits = id.split('_');
bits[bits.length - 1] = elementModel.options.repeatCounter;
id = bits.join('_');
}
}
// Create the fx key
id = id.replace('fabrik_trigger_', '');
if (id.slice(0, 6) === 'group_') {
id = id.slice(6, id.length);
// weird fix?
if (id.slice(0, 6) === 'group_') {
id = id.slice(6, id.length);
}
k = id;
} else {
id = id.slice(8, id.length);
k = 'element' + id;
}
// Get the stored fx
fx = this.fx.elements[k];
if (!fx) {
// A group was duplicated but no element FX added, lets try to add it now
fx = this.addElementFX('element_' + id, method);
// If it wasn't added then lets get out of here
if (!fx) {
return;
}
}
// Seems dropdown element fx.css.element is already the container
if (groupfx || fx.css.element.hasClass('fabrikElementContainer')) {
fxElement = fx.css.element;
} else {
fxElement = fx.css.element.getParent('.fabrikElementContainer');
}
// For repeat groups rendered as tables we cant apply fx on td so get child
if (fxElement.get('tag') === 'td') {
fxElement = fxElement.getChildren()[0];
}
switch (method) {
case 'show':
fxElement.fade('show').removeClass('fabrikHide');
if (groupfx) {
// strange fix for ie8
// http://fabrik.unfuddle.com/projects/17220/tickets/by_number/703?cycle=true
document.id(id).getElements('.fabrikinput').setStyle('opacity', '1');
this.showGroupTab(id);
// if it was hidden by group's "Show Group" setting ("Yes, but hidden"), need to show()
fxElement.show();
}
break;
case 'hide':
fxElement.fade('hide').addClass('fabrikHide');
if (groupfx) {
this.hideGroupTab(id);
}
break;
case 'fadein':
fxElement.removeClass('fabrikHide');
if (fx.css.lastMethod !== 'fadein') {
fx.css.element.show();
fx.css.start({'opacity': [0, 1]});
}
if (groupfx) {
this.showGroupTab(id);
fxElement.show();
}
break;
case 'fadeout':
if (fx.css.lastMethod !== 'fadeout') {
fx.css.start({'opacity': [1, 0]}).chain(function () {
fx.css.element.hide();
fxElement.addClass('fabrikHide');
});
}
if (groupfx) {
this.hideGroupTab(id);
}
break;
case 'slide in':
fx.slide.slideIn();
break;
case 'slide out':
fx.slide.slideOut();
fxElement.removeClass('fabrikHide');
break;
case 'slide toggle':
fx.slide.toggle();
break;
case 'clear':
this.formElements.get(id).clear();
break;
case 'disable':
if (!groupfx) {
jQuery('#' + id).prop('disabled', true);
}
break;
case 'enable':
if (!groupfx) {
jQuery('#' + id).prop('disabled', false);
}
break;
case 'readonly':
if (!groupfx) {
// can't "readonly" a select, so disable all but selected option instead
if (jQuery('#' + id).prop('tagName') === 'SELECT') {
jQuery('#' + id).data('readonly', 1);
jQuery('#' + id + ' option:not(:selected)').attr('disabled', true);
}
else {
jQuery('#' + id).prop('readonly', true);
}
}
break;
case 'notreadonly':
if (!groupfx) {
if (jQuery('#' + id).prop('tagName') === 'SELECT') {
jQuery('#' + id + ' option').attr('disabled', false);
jQuery('#' + id).data('readonly', 0);
}
else {
jQuery('#' + id).prop('readonly', false);
}
}
break;
}
fx.lastMethod = method;
Fabrik.fireEvent('fabrik.form.doelementfx', [this, method, id, groupfx]);
},
/**
* Get a group's tab, if it exists
*
* These tab functions are currently just helpers for user scripts
*
* @param {string} groupId group ID
*
* @return tab | false
*/
getGroupTab: function (groupId) {
if (!groupId.test(/^group/)) {
groupId = 'group' + groupId;
}
if (document.id(groupId).getParent().hasClass('tab-pane')) {
var tabid = document.id(groupId).getParent().id;
var tab_anchor = this.form.getElement('a[href=#' + tabid + ']');
return tab_anchor.getParent();
}
return false;
},
/**
* Hide a group's tab, if it exists
*
* @param {string} groupId
*/
hideGroupTab: function (groupId) {
var tab = this.getGroupTab(groupId);
if (tab !== false) {
jQuery(tab).hide();
if (tab.hasClass('active')) {
if (tab.getPrevious()) {
jQuery(tab.getPrevious().getFirst()).tab('show');
}
else if (tab.getNext()) {
jQuery(tab.getNext().getFirst()).tab('show');
}
}
}
},
/**
* Hide a group's tab, if it exists
*
* @param {string} groupId
*/
selectGroupTab: function (groupId) {
var tab = this.getGroupTab(groupId);
if (tab !== false) {
if (!tab.hasClass('active')) {
jQuery(tab.getFirst()).tab('show');
}
}
},
/**
* Hide a group's tab, if it exists
*
* @param {string} groupId
*/
showGroupTab: function (groupId) {
var tab = this.getGroupTab(groupId);
if (tab !== false) {
jQuery(tab).show();
}
},
/**
* Convenience for custom code that needs to fire when a tab is changed
*/
watchTabs: function () {
var self = this;
jQuery(this.form).on('click', '*[data-role=fabrik_tab]', function (event) {
var groupId = event.target.id.match(/group(\d+)_tab/);
if (groupId.length > 1) {
groupId = groupId[1];
}
Fabrik.fireEvent('fabrik.form.tab.click', [self, groupId, event], 500);
});
},
/**
* If a user has previously started a multi-page form, then we will have a .clearSession
* button which resets the form and submits it using the removeSession task.
*/
watchClearSession: function () {
if (this.options.multipage_save === 0) {
return;
}
var self = this,
form = jQuery(this.form);
form.find('.clearSession').on('click', function (e) {
e.preventDefault();
form.find('input[name=task]').val('removeSession');
self.clearForm();
self.form.submit();
});
},
createPages: function () {
var submit, p, firstGroup, tabDiv;
if (this.isMultiPage()) {
// Wrap each page in its own div
this.options.pages.each(function (page, i) {
p = jQuery(document.createElement('div'));
p.attr({
'class': 'page',
'id' : 'page_' + i
});
firstGroup = jQuery('#group' + page[0]);
// Paul - Don't use pages if this is a bootstrap_tab form
tabDiv = firstGroup.closest('div');
if (tabDiv.hasClass('tab-pane')) {
return;
}
p.insertBefore(firstGroup);
page.each(function (group) {
p.append(jQuery('#group' + group));
});
});
submit = this._getButton('Submit');
if (submit && this.options.rowid === '') {
submit.disabled = 'disabled';
submit.setStyle('opacity', 0.5);
}
var self = this;
jQuery(this.form).on('click', '.fabrikPagePrevious', function (e) {
self._doPageNav(e, -1);
});
jQuery(this.form).on('click', '.fabrikPageNext', function (e) {
self._doPageNav(e, 1);
});
this.setPageButtons();
this.hideOtherPages();
}
},
isMultiPage: function () {
return this.options.pages.getKeys().length > 1;
},
/**
* Move forward/backwards in multi-page form
*
* @param {event} e
* @param {int} dir 1/-1
*/
_doPageNav: function (e, dir) {
var self = this, url, d;
if (this.options.editable) {
if (typeOf(this.form.getElement('.fabrikMainError')) !== 'null') {
this.form.getElement('.fabrikMainError').addClass('fabrikHide');
}
// If tip shown at bottom of long page and next page shorter we need to move the tip to
// the top of the page to avoid large space appearing at the bottom of the page.
jQuery('.tool-tip').css('top', 0);
// Don't prepend with Fabrik.liveSite, as it can create cross origin browser errors if
// you are on www and livesite is not on www.
url = 'index.php?option=com_fabrik&format=raw&task=form.ajax_validate&form_id=' + this.id;
if (this.options.lang !== false) {
url += '&lang=' + this.options.lang;
}
Fabrik.loader.start(this.getBlock(), Joomla.JText._('COM_FABRIK_VALIDATING'));
this.clearErrors();
d = jQuery.extend({}, this.getFormData(), {
task: 'form.ajax_validate',
fabrik_ajax: '1',
format : 'raw'
});
d = this._prepareRepeatsForAjax(d);
jQuery.ajax({
'url' : url,
method: this.options.ajaxmethod,
data : d,
}).done(function (r) {
Fabrik.loader.stop(self.getBlock());
r = JSON.parse(r);
// Don't show validation errors if we are going back a page
if (dir === -1 || self._showGroupError(r, d) === false) {
self.changePage(dir);
self.saveGroupsToDb();
}
jQuery('html, body').animate({
scrollTop: jQuery(self.form).offset().top
}, 300);
});
} else {
this.changePage(dir);
}
e.preventDefault();
},
/**
* On a multi-page form save the group data
*/
saveGroupsToDb: function () {
var self = this, orig, origProcess, url, data,
format = this.form.querySelector('input[name=format]'),
task = this.form.querySelector('input[name=task]'),
block = this.getBlock();
if (this.options.multipage_save === 0) {
return;
}
Fabrik.fireEvent('fabrik.form.groups.save.start', [this]);
if (this.result === false) {
this.result = true;
return;
}
orig = format.value;
origProcess = task.value;
this.form.querySelector('input[name=format]').value = 'raw';
this.form.querySelector('input[name=task]').value = 'form.savepage';
url = 'index.php?option=com_fabrik&format=raw&page=' + this.currentPage;
if (this.options.lang !== false) {
url += '&lang=' + this.options.lang;
}
Fabrik.loader.start(block, 'saving page');
data = this.getFormData();
data.fabrik_ajax = 1;
jQuery.ajax({
url : url,
method : this.options.ajaxmethod,
data : data,
}).done(function (r) {
Fabrik.fireEvent('fabrik.form.groups.save.completed', [self]);
if (self.result === false) {
self.result = true;
return;
}
format.value = orig;
task.value = origProcess;
if (self.options.ajax) {
Fabrik.fireEvent('fabrik.form.groups.save.end', [self, r]);
}
Fabrik.loader.stop(block);
});
},
changePage: function (dir) {
this.changePageDir = dir;
Fabrik.fireEvent('fabrik.form.page.change', [this, dir]);
if (this.result === false) {
this.result = true;
return;
}
this.currentPage = this.currentPage.toInt();
if (this.currentPage + dir >= 0 && this.currentPage + dir < this.options.pages.getKeys().length) {
this.currentPage = this.currentPage + dir;
if (!this.pageGroupsVisible()) {
this.changePage(dir);
}
}
this.setPageButtons();
jQuery('#page_' + this.currentPage).css('display', '');
this._setMozBoxWidths();
this.hideOtherPages();
Fabrik.fireEvent('fabrik.form.page.chage.end', [this, dir]);
Fabrik.fireEvent('fabrik.form.page.change.end', [this, dir]);
if (this.result === false) {
this.result = true;
return;
}
},
pageGroupsVisible: function () {
var visible = false;
this.options.pages.get(this.currentPage).each(function (gid) {
var group = jQuery('#group' + gid);
if (group.length > 0) {
if (group.css('display') !== 'none') {
visible = true;
}
}
});
return visible;
},
/**
* Hide all groups except those in the active page
*/
hideOtherPages: function () {
var page, currentPage = parseInt(this.currentPage, 10);
this.options.pages.each(function (gids, i) {
if (parseInt(i, 10) !== currentPage) {
page = jQuery('#page_' + i);
page.hide();
}
});
},
setPageButtons: function () {
var submit = this._getButton('Submit');
var prevs = this.form.getElements('.fabrikPagePrevious');
var nexts = this.form.getElements('.fabrikPageNext');
nexts.each(function (next) {
if (this.currentPage === this.options.pages.getKeys().length - 1) {
if (typeOf(submit) !== 'null') {
submit.disabled = '';
submit.setStyle('opacity', 1);
}
next.disabled = 'disabled';
next.setStyle('opacity', 0.5);
} else {
if (typeOf(submit) !== 'null' && (this.options.rowid === '' ||
this.options.rowid.toString() === '0')) {
submit.disabled = 'disabled';
submit.setStyle('opacity', 0.5);
}
next.disabled = '';
next.setStyle('opacity', 1);
}
}.bind(this));
prevs.each(function (prev) {
if (this.currentPage === 0) {
prev.disabled = 'disabled';
prev.setStyle('opacity', 0.5);
} else {
prev.disabled = '';
prev.setStyle('opacity', 1);
}
}.bind(this));
},
destroyElements: function () {
this.formElements.each(function (el) {
el.destroy();
});
},
/**
* Add elements into the form
*
* @param Hash a Elements to add.
*/
addElements: function (a) {
/*
* Store the newly added elements so we can call attachedToForm only on new elements.
* Avoids issue with cdd in repeat groups resetting themselves when you add a new group
*/
var added = [], i = 0;
a = $H(a);
a.each(function (elements, gid) {
elements.each(function (el) {
if (typeOf(el) === 'array') {
if (typeOf(document.id(el[1])) === 'null') {
fconsole('Fabrik form::addElements: Cannot add element "' + el[1] +
'" because it does not exist in HTML.');
return;
}
try {
var oEl = new window[el[0]](el[1], el[2]);
}
catch (err) {
fconsole('Fabrik form::addElements: Cannot add element "' + el[1] +
'" of type "' + el[0] + '" because: ' + err.message);
return;
}
added.push(this.addElement(oEl, el[1], gid));
}
else if (typeOf(el) === 'object') {
if (typeOf(document.id(el.options.element)) === 'null') {
fconsole('Fabrik form::addElements: Cannot add element "' +
el.options.element + '" because it does not exist in HTML.');
return;
}
added.push(this.addElement(el, el.options.element, gid));
}
else if (typeOf(el) !== 'null') {
fconsole('Fabrik form::addElements: Cannot add unknown element: ' + el);
}
else {
fconsole('Fabrik form::addElements: Cannot add null element.');
}
}.bind(this));
}.bind(this));
// $$$ hugh - moved attachedToForm calls out of addElement to separate loop, to fix forward reference issue,
// i.e. calc element adding events to other elements which come after itself, which won't be in formElements
// yet if we do it in the previous loop ('cos the previous loop is where elements get added to formElements)
for (i = 0; i < added.length; i++) {
if (typeOf(added[i]) !== 'null') {
try {
added[i].attachedToForm();
} catch (err) {
fconsole(added[i].options.element + ' attach to form:' + err);
}
}
}
Fabrik.fireEvent('fabrik.form.elements.added', [this]);
},
addElement: function (oEl, elId, gid) {
elId = oEl.getFormElementsKey(elId);
elId = elId.replace('[]', '');
var ro = elId.substring(elId.length - 3, elId.length) === '_ro';
oEl.form = this;
oEl.groupid = gid;
this.formElements.set(elId, oEl);
Fabrik.fireEvent('fabrik.form.element.added', [this, elId, oEl]);
if (ro) {
elId = elId.substr(0, elId.length - 3);
this.formElements.set(elId, oEl);
}
this.submitBroker.addElement(elId, oEl);
return oEl;
},
/**
* Dispatch an event to an element
*
* @param string elementType Deprecated
* @param string elementId Element key to look up in this.formElements
* @param string action Event change/click etc.
* @param mixed js String or function
*/
dispatchEvent: function (elementType, elementId, action, js) {
if (typeOf(js) === 'string') {
js = Encoder.htmlDecode(js);
}
var el = this.formElements.get(elementId);
if (!el) {
// E.g. db join rendered as chx
var els = Object.each(this.formElements, function (e) {
if (elementId === e.baseElementId) {
el = e;
}
});
}
if (!el) {
fconsole('Fabrik form::dispatchEvent: Cannot find element to add ' + action + ' event to: ' + elementId);
}
else if (js !== '') {
el.addNewEvent(action, js);
}