/
FormEngine.js
1384 lines (1261 loc) · 48.6 KB
/
FormEngine.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
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* contains all JS functions related to TYPO3 TCEforms/FormEngine
*
* there are separate issues in this main object
* - functions, related to Element Browser ("Popup Window") and select fields
* - filling select fields (by wizard etc) from outside, formerly known via "setFormValueFromBrowseWin"
* - select fields: move selected items up and down via buttons, remove items etc
*/
// add legacy functions to be accessible in the global scope
var setFormValueOpenBrowser, // @deprecated
setFormValueFromBrowseWin, // @deprecated
setHiddenFromList, // @deprecated
setFormValueManipulate, // @deprecated
setFormValue_getFObj; // @deprecated
/**
* Module: TYPO3/CMS/Backend/FormEngine
*/
define(['jquery',
'TYPO3/CMS/Backend/FormEngineValidation',
'TYPO3/CMS/Backend/DocumentSaveActions',
'TYPO3/CMS/Backend/Icons',
'TYPO3/CMS/Backend/Modal',
'TYPO3/CMS/Backend/Utility/MessageUtility',
'TYPO3/CMS/Backend/Severity',
'TYPO3/CMS/Backend/BackendException',
'TYPO3/CMS/Backend/Event/InteractionRequestMap'
], function($, FormEngineValidation, DocumentSaveActions, Icons, Modal, MessageUtility, Severity, BackendException, InteractionRequestMap) {
/**
* @param {InteractionRequest} interactionRequest
* @param {boolean} response
*/
function handleConsumeResponse(interactionRequest, response) {
if (response) {
FormEngine.interactionRequestMap.resolveFor(interactionRequest);
} else {
FormEngine.interactionRequestMap.rejectFor(interactionRequest);
}
}
/**
* @exports TYPO3/CMS/Backend/FormEngine
*/
var FormEngine = {
consumeTypes: ['typo3.setUrl', 'typo3.beforeSetUrl', 'typo3.refresh'],
Validation: FormEngineValidation,
interactionRequestMap: InteractionRequestMap,
formName: TYPO3.settings.FormEngine.formName,
openedPopupWindow: null,
legacyFieldChangedCb: function() {
!$.isFunction(TYPO3.settings.FormEngine.legacyFieldChangedCb) || TYPO3.settings.FormEngine.legacyFieldChangedCb();
},
browserUrl: ''
};
/**
* Opens a popup window with the element browser (browser.php)
*
* @param {string} mode can be "db" or "file"
* @param {string} params additional params for the browser window
* @deprecated since TYPO3 v10.2, will be removed in TYPO3 v11.0. Use FormEngine.openPopupWindow() instead.
*/
setFormValueOpenBrowser = function(mode, params) {
console.warn('setFormValueOpenBrowser() has been marked as deprecated and will be removed in TYPO3 v11. Use FormEngine.openPopupWindow instead.');
return FormEngine.openPopupWindow(mode, params);
};
/**
* Opens a popup window with the element browser (browser.php)
*
* @param {string} mode can be "db" or "file"
* @param {string} params additional params for the browser window
*/
FormEngine.openPopupWindow = function(mode, params) {
return Modal.advanced({
type: Modal.types.iframe,
content: FormEngine.browserUrl + '&mode=' + mode + '&bparams=' + params,
size: Modal.sizes.large
});
};
/**
* properly fills the select field from the popup window (element browser, link browser)
* or from a multi-select (two selects side-by-side)
* previously known as "setFormValueFromBrowseWin"
*
* @param {string} fieldName Formerly known as "fsetFormValueFromBrowseWinName" name of the field, like [tt_content][2387][header]
* @param {string|number} value The value to fill in (could be an integer)
* @param {string} label The visible name in the selector
* @param {string} title The title when hovering over it
* @param {string} exclusiveValues If the select field has exclusive options that are not combine-able
* @param {$} $optionEl The jQuery object of the selected <option> tag
* @deprecated since TYPO3 v10.2, will be removed in TYPO3 v11.0. Use FormEngine.setSelectOptionFromExternalSource() instead.
*/
setFormValueFromBrowseWin = function(fieldName, value, label, title, exclusiveValues, $optionEl) {
console.warn(
'setFormValueFromBrowseWin() has been marked as deprecated and will be removed in TYPO3 v11. '
+ 'Use FormEngine.setSelectOptionFromExternalSource() or send a message instead.'
);
FormEngine.setSelectOptionFromExternalSource(fieldName, value, label, title, exclusiveValues, $optionEl);
};
/**
* properly fills the select field from the popup window (element browser, link browser)
* or from a multi-select (two selects side-by-side)
* previously known as "setFormValueFromBrowseWin"
*
* @param {string} fieldName Formerly known as "fsetFormValueFromBrowseWinName" name of the field, like [tt_content][2387][header]
* @param {string|number} value The value to fill in (could be an integer)
* @param {string} label The visible name in the selector
* @param {string} title The title when hovering over it
* @param {string} exclusiveValues If the select field has exclusive options that are not combine-able
* @param {$} $optionEl The jQuery object of the selected <option> tag
*/
FormEngine.setSelectOptionFromExternalSource = function(fieldName, value, label, title, exclusiveValues, $optionEl) {
exclusiveValues = String(exclusiveValues);
var $fieldEl,
$originalFieldEl,
isMultiple = false,
isList = false;
$originalFieldEl = $fieldEl = FormEngine.getFieldElement(fieldName);
if ($originalFieldEl.length === 0 || value === '--div--') {
return;
}
// Check if the form object has a "_list" element
// The "_list" element exists for multiple selection select types
var $listFieldEl = FormEngine.getFieldElement(fieldName, '_list', true);
if ($listFieldEl.length > 0) {
$fieldEl = $listFieldEl;
isMultiple = ($fieldEl.prop('multiple') && $fieldEl.prop('size') != '1');
isList = true;
}
// clear field before adding value, if configured so (maxitems==1)
// @todo: clean this code
if (typeof TBE_EDITOR.clearBeforeSettingFormValueFromBrowseWin[fieldName] !== 'undefined') {
var clearSettings = TBE_EDITOR.clearBeforeSettingFormValueFromBrowseWin[fieldName];
$fieldEl.empty();
// Clear the upload field
// @todo: Investigate whether we either need to fix this code or we can drop it.
var filesContainer = document.getElementById(clearSettings.itemFormElID_file);
if (filesContainer) {
filesContainer.innerHTML = filesContainer.innerHTML;
}
}
if (isMultiple || isList) {
// If multiple values are not allowed, clear anything that is in the control already
if (!isMultiple) {
var $availableFieldEl = FormEngine.getFieldElement(fieldName, '_avail');
$fieldEl.find('option').each(function() {
$availableFieldEl
.find('option[value="' + $.escapeSelector($(this).attr('value')) + '"]')
.removeClass('hidden')
.prop('disabled', false);
});
$fieldEl.empty();
}
// Clear elements if exclusive values are found
if (exclusiveValues) {
var reenableOptions = false;
var m = new RegExp('(^|,)' + value + '($|,)');
// the new value is exclusive => remove all existing values
if (exclusiveValues.match(m)) {
$fieldEl.empty();
reenableOptions = true;
} else if ($fieldEl.find('option').length == 1) {
// there is an old value and it was exclusive => it has to be removed
m = new RegExp("(^|,)" + $fieldEl.find('option').prop('value') + "($|,)");
if (exclusiveValues.match(m)) {
$fieldEl.empty();
reenableOptions = true;
}
}
if (reenableOptions && typeof $optionEl !== 'undefined') {
$optionEl.closest('select').find('[disabled]').removeClass('hidden').prop('disabled', false)
}
}
// Inserting the new element
var addNewValue = true;
// check if there is a "_mul" field (a field on the right) and if the field was already added
var $multipleFieldEl = FormEngine.getFieldElement(fieldName, '_mul', true);
if ($multipleFieldEl.length == 0 || $multipleFieldEl.val() == 0) {
$fieldEl.find('option').each(function(k, optionEl) {
if ($(optionEl).prop('value') == value) {
addNewValue = false;
return false;
}
});
if (addNewValue && typeof $optionEl !== 'undefined') {
$optionEl.addClass('hidden').prop('disabled', true);
}
}
// element can be added
if (addNewValue) {
// finally add the option
var $option = $('<option></option>');
$option.attr({value: value, title: title}).text(label);
$option.appendTo($fieldEl);
// set the hidden field
FormEngine.updateHiddenFieldValueFromSelect($fieldEl, $originalFieldEl);
// execute the phpcode from $FormEngine->TBE_EDITOR_fieldChanged_func
FormEngine.legacyFieldChangedCb();
FormEngineValidation.markFieldAsChanged($originalFieldEl);
}
} else {
// The incoming value consists of the table name, an underscore and the uid
// or just the uid
// For a single selection field we need only the uid, so we extract it
var pattern = /_(\d+)$/
, result = value.toString().match(pattern);
if (result != null) {
value = result[1];
}
// Change the selected value
$fieldEl.val(value);
}
if (typeof FormEngine.Validation !== 'undefined' && typeof FormEngine.Validation.validate === 'function') {
FormEngine.Validation.validate();
}
};
/**
* sets the value of the hidden field, from the select list, always executed after the select field was updated
* previously known as global function setHiddenFromList()
*
* @param {HTMLElement} selectFieldEl the select field
* @param {HTMLElement} originalFieldEl the hidden form field
* @deprecated since TYPO3 v10.2, will be removed in TYPO3 v11.0. Use FormEngine.updateHiddenFieldValueFromSelect() instead.
*/
setHiddenFromList = function(selectFieldEl, originalFieldEl) {
console.warn('setHiddenFromList() has been marked as deprecated and will be removed in TYPO3 v11. Use FormEngine.updateHiddenFieldValueFromSelect() instead.');
FormEngine.updateHiddenFieldValueFromSelect(selectFieldEl, originalFieldEl);
};
/**
* sets the value of the hidden field, from the select list, always executed after the select field was updated
* previously known as global function setHiddenFromList()
*
* @param {HTMLElement} selectFieldEl the select field
* @param {HTMLElement} originalFieldEl the hidden form field
*/
FormEngine.updateHiddenFieldValueFromSelect = function(selectFieldEl, originalFieldEl) {
var selectedValues = [];
$(selectFieldEl).find('option').each(function() {
selectedValues.push($(this).prop('value'));
});
// make a comma separated list, if it is a multi-select
// set the values to the final hidden field
$(originalFieldEl).val(selectedValues.join(','));
};
/**
* legacy function, can be removed once this function is not in use anymore
*
* @param {String} fName
* @param {String} type
* @param {Number} maxLength
* @deprecated since TYPO3 v10.2, will be removed in TYPO3 v11.0.
*/
setFormValueManipulate = function(fName, type, maxLength) {
console.warn('setFormValueManipulate() has been marked as deprecated and will be removed in TYPO3 v11.');
var $formEl = FormEngine.getFormElement(fName);
if ($formEl.length > 0) {
var formObj = $formEl.get(0);
var localArray_V = [];
var localArray_L = [];
var localArray_S = [];
var localArray_T = [];
var fObjSel = formObj[fName + '_list'];
var l = fObjSel.length;
var c = 0;
var a;
if (type === 'RemoveFirstIfFull') {
if (maxLength == 1) {
for (a = 1; a < l; a++) {
if (fObjSel.options[a].selected != 1) {
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 0;
localArray_T[c] = fObjSel.options[a].title;
c++;
}
}
} else {
return;
}
}
if ((type === "Remove" && fObjSel.size > 1) || type === "Top" || type === "Bottom") {
if (type === "Top") {
for (a = 0; a < l; a++) {
if (fObjSel.options[a].selected == 1) {
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[a].title;
c++;
}
}
}
for (a = 0; a < l; a++) {
if (fObjSel.options[a].selected != 1) {
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 0;
localArray_T[c] = fObjSel.options[a].title;
c++;
}
}
if (type === "Bottom") {
for (a = 0; a < l; a++) {
if (fObjSel.options[a].selected == 1) {
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[a].title;
c++;
}
}
}
}
if (type === "Down") {
var tC = 0;
var tA = [];
var aa = 0;
for (a = 0; a < l; a++) {
if (fObjSel.options[a].selected != 1) {
// Add non-selected element:
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 0;
localArray_T[c] = fObjSel.options[a].title;
c++;
// Transfer any accumulated and reset:
if (tA.length > 0) {
for (aa = 0; aa < tA.length; aa++) {
localArray_V[c] = fObjSel.options[tA[aa]].value;
localArray_L[c] = fObjSel.options[tA[aa]].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[tA[aa]].title;
c++;
}
tC = 0;
tA = [];
}
} else {
tA[tC] = a;
tC++;
}
}
// Transfer any remaining:
if (tA.length > 0) {
for (aa = 0; aa < tA.length; aa++) {
localArray_V[c] = fObjSel.options[tA[aa]].value;
localArray_L[c] = fObjSel.options[tA[aa]].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[tA[aa]].title;
c++;
}
}
}
if (type === "Up") {
var tC = 0;
var tA = [];
var aa = 0;
c = l - 1;
for (a = l - 1; a >= 0; a--) {
if (fObjSel.options[a].selected != 1) {
// Add non-selected element:
localArray_V[c] = fObjSel.options[a].value;
localArray_L[c] = fObjSel.options[a].text;
localArray_S[c] = 0;
localArray_T[c] = fObjSel.options[a].title;
c--;
// Transfer any accumulated and reset:
if (tA.length > 0) {
for (aa = 0; aa < tA.length; aa++) {
localArray_V[c] = fObjSel.options[tA[aa]].value;
localArray_L[c] = fObjSel.options[tA[aa]].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[tA[aa]].title;
c--;
}
tC = 0;
tA = [];
}
} else {
tA[tC] = a;
tC++;
}
}
// Transfer any remaining:
if (tA.length > 0) {
for (aa = 0; aa < tA.length; aa++) {
localArray_V[c] = fObjSel.options[tA[aa]].value;
localArray_L[c] = fObjSel.options[tA[aa]].text;
localArray_S[c] = 1;
localArray_T[c] = fObjSel.options[tA[aa]].title;
c--;
}
}
c = l; // Restore length value in "c"
}
// Transfer items in temporary storage to list object:
fObjSel.length = c;
for (a = 0; a < c; a++) {
fObjSel.options[a].value = localArray_V[a];
fObjSel.options[a].text = localArray_L[a];
fObjSel.options[a].selected = localArray_S[a];
fObjSel.options[a].title = localArray_T[a];
}
FormEngine.updateHiddenFieldValueFromSelect(fObjSel, formObj[fName]);
FormEngine.legacyFieldChangedCb();
}
};
/**
* Legacy function
* returns the DOM object for the given form name of the current form,
* but only if the given field name is valid, legacy function, use "getFormElement" instead
*
* @param {String} fieldName the name of the field name
* @returns {*|HTMLElement}
* @deprecated since TYPO3 v10.2, will be removed in TYPO3 v11.0. Use FormEngine.getFormElement() instead.
*/
setFormValue_getFObj = function(fieldName) {
console.warn('setFormValue_getFObj() has been marked as deprecated and will be removed in TYPO3 v11. Use FormEngine.getFormElement() instead.');
var $formEl = FormEngine.getFormElement(fieldName);
if ($formEl.length > 0) {
// return the DOM element of the form object
return $formEl.get(0);
}
return null;
};
/**
* returns a jQuery object for the given form name of the current form,
* if the parameter "fieldName" is given, then the form element is only returned if the field name is available
* the latter behaviour mirrors the one of the function "setFormValue_getFObj"
*
* @param {String} fieldName the field name to check for, optional
* @returns {*|HTMLElement}
*/
FormEngine.getFormElement = function(fieldName) {
var $formEl = $('form[name="' + FormEngine.formName + '"]:first');
if (fieldName) {
var $fieldEl = FormEngine.getFieldElement(fieldName)
, $listFieldEl = FormEngine.getFieldElement(fieldName, '_list');
// Take the form object if it is either of type select-one or of type-multiple and it has a "_list" element
if ($fieldEl.length > 0 &&
(
($fieldEl.prop('type') === 'select-one') ||
($listFieldEl.length > 0 && $listFieldEl.prop('type').match(/select-(one|multiple)/))
)
) {
return $formEl;
} else {
console.error('Form fields missing: form: ' + FormEngine.formName + ', field name: ' + fieldName);
alert('Form field is invalid');
}
} else {
return $formEl;
}
};
/**
* Returns a jQuery object of the field DOM element of the current form, can also be used to
* request an alternative field like "_hr", "_list" or "_mul"
*
* @param {String} fieldName the name of the field (<input name="fieldName">)
* @param {String} appendix optional
* @param {Boolean} noFallback if set, then the appendix value is returned no matter if it exists or not
* @returns {*|HTMLElement}
*/
FormEngine.getFieldElement = function(fieldName, appendix, noFallback) {
var $formEl = $('form[name="' + FormEngine.formName + '"]:first');
// if an appendix is set, return the field with the appendix (like _mul or _list)
if (appendix) {
var $fieldEl;
switch (appendix) {
case '_list':
$fieldEl = $(':input.tceforms-multiselect[data-formengine-input-name="' + fieldName + '"]', $formEl);
break;
case '_avail':
$fieldEl = $(':input[data-relatedfieldname="' + fieldName + '"]', $formEl);
break;
case '_mul':
case '_hr':
$fieldEl = $(':input[type=hidden][data-formengine-input-name="' + fieldName + '"]', $formEl);
break;
}
if (($fieldEl && $fieldEl.length > 0) || noFallback === true) {
return $fieldEl;
}
}
return $(':input[name="' + fieldName + '"]', $formEl);
};
/**
* Initialize events for all form engine relevant tasks.
* This function only needs to be called once on page load,
* as it using deferrer methods only
*/
FormEngine.initializeEvents = function() {
if (top.TYPO3 && typeof top.TYPO3.Backend !== 'undefined') {
top.TYPO3.Backend.consumerScope.attach(FormEngine);
$(window).on('unload', function() {
top.TYPO3.Backend.consumerScope.detach(FormEngine);
});
}
$(document).on('click', '.t3js-editform-close', function(e) {
e.preventDefault();
FormEngine.preventExitIfNotSaved(
FormEngine.preventExitIfNotSavedCallback
);
}).on('click', '.t3js-editform-view', function(e) {
e.preventDefault();
FormEngine.previewAction(e, FormEngine.previewActionCallback);
}).on('click', '.t3js-editform-new', function(e) {
e.preventDefault();
FormEngine.newAction(e, FormEngine.newActionCallback);
}).on('click', '.t3js-editform-duplicate', function(e) {
e.preventDefault();
FormEngine.duplicateAction(e, FormEngine.duplicateActionCallback);
}).on('click', '.t3js-editform-delete-record', function(e) {
e.preventDefault();
FormEngine.deleteAction(e, FormEngine.deleteActionCallback);
}).on('click', '.t3js-editform-submitButton', function(event) {
var $me = $(this),
name = $me.data('name') || this.name,
$elem = $('<input />').attr('type', 'hidden').attr('name', name).attr('value', '1');
$me.parents('form').append($elem);
}).on('change', '.t3-form-field-eval-null-checkbox input[type="checkbox"]', function(e) {
// Null checkboxes without placeholder click event handler
$(this).closest('.t3js-formengine-field-item').toggleClass('disabled');
}).on('change', '.t3js-form-field-eval-null-placeholder-checkbox input[type="checkbox"]', function(e) {
FormEngine.toggleCheckboxField($(this));
FormEngineValidation.markFieldAsChanged($(this));
}).on('change', function(event) {
$('.module-docheader-bar .btn').removeClass('disabled').prop('disabled', false);
}).on('click', '.t3js-element-browser', function(e) {
e.preventDefault();
e.stopPropagation();
const $me = $(e.currentTarget);
const mode = $me.data('mode');
const params = $me.data('params');
FormEngine.openPopupWindow(mode, params);
});
document.editform.addEventListener('submit', function () {
if (document.editform.closeDoc.value) {
return;
}
const elements = [
'button[form]',
'button[name^="_save"]',
'a[data-name^="_save"]',
'button[name="CMD"][value^="save"]',
'a[data-name="CMD"][data-value^="save"]',
].join(',');
const button = document.querySelector(elements);
if (button !== null) {
button.disabled = true;
Icons.getIcon('spinner-circle-dark', Icons.sizes.small).then(function (markup) {
button.querySelector('.t3js-icon').outerHTML = markup;
});
}
});
window.addEventListener('message', FormEngine.handlePostMessage);
};
/**
* @param {InteractionRequest} interactionRequest
* @return {jQuery.Deferred}
*/
FormEngine.consume = function(interactionRequest) {
if (!interactionRequest) {
throw new BackendException('No interaction request given', 1496589980);
}
if (interactionRequest.concernsTypes(FormEngine.consumeTypes)) {
var outerMostRequest = interactionRequest.outerMostRequest;
var deferred = $.Deferred();
FormEngine.interactionRequestMap.attachFor(
outerMostRequest,
deferred
);
// resolve or reject deferreds with previous user choice
if (outerMostRequest.isProcessed()) {
handleConsumeResponse(
outerMostRequest,
outerMostRequest.getProcessedData().response
);
// show confirmation dialog
} else if (FormEngine.hasChange()) {
FormEngine.preventExitIfNotSaved(function(response) {
outerMostRequest.setProcessedData(
{response: response}
);
handleConsumeResponse(outerMostRequest, response);
});
// resolve directly
} else {
FormEngine.interactionRequestMap.resolveFor(outerMostRequest);
}
return deferred;
}
};
FormEngine.handlePostMessage = function (e) {
if (!MessageUtility.MessageUtility.verifyOrigin(e.origin)) {
throw 'Denied message sent by ' + e.origin;
}
if (e.data.actionName === 'typo3:elementBrowser:elementAdded') {
if (typeof e.data.fieldName === 'undefined') {
throw 'fieldName not defined in message';
}
if (typeof e.data.value === 'undefined') {
throw 'value not defined in message';
}
const label = e.data.label || e.data.value;
const title = e.data.title || label;
const exclusiveValues = e.data.exclusiveValues || '';
FormEngine.setSelectOptionFromExternalSource(e.data.fieldName, e.data.value, label, title, exclusiveValues);
}
};
/**
* Initializes the remaining character views based on the fields' maxlength attribute
*/
FormEngine.initializeRemainingCharacterViews = function() {
// all fields with a "maxlength" attribute
var $maxlengthElements = $('[maxlength]').not('.t3js-datetimepicker').not('.t3js-charcounter-initialized');
$maxlengthElements.on('focus', function(e) {
var $field = $(this),
$parent = $field.parents('.t3js-formengine-field-item:first'),
maxlengthProperties = FormEngine.getCharacterCounterProperties($field);
// append the counter only at focus to avoid cluttering the DOM
$parent.append($('<div />', {'class': 't3js-charcounter'}).append(
$('<span />', {'class': maxlengthProperties.labelClass}).text(TYPO3.lang['FormEngine.remainingCharacters'].replace('{0}', maxlengthProperties.remainingCharacters))
));
}).on('blur', function() {
var $field = $(this),
$parent = $field.parents('.t3js-formengine-field-item:first');
$parent.find('.t3js-charcounter').remove();
}).on('keyup', function() {
var $field = $(this),
$parent = $field.parents('.t3js-formengine-field-item:first'),
maxlengthProperties = FormEngine.getCharacterCounterProperties($field);
// change class and value
$parent.find('.t3js-charcounter span').removeClass().addClass(maxlengthProperties.labelClass).text(TYPO3.lang['FormEngine.remainingCharacters'].replace('{0}', maxlengthProperties.remainingCharacters))
});
$maxlengthElements.addClass('t3js-charcounter-initialized');
$(':password').on('focus', function() {
$(this).attr({'type':'text', 'data-active-password':'true'}).select();
}).on('blur', function() {
$(this).attr('type', 'password').removeAttr('data-active-password');
});
};
/**
* Get the properties required for proper rendering of the character counter
*
* @param {Object} $field
* @returns {{remainingCharacters: number, labelClass: string}}
*/
FormEngine.getCharacterCounterProperties = function($field) {
var fieldText = $field.val(),
maxlength = $field.attr('maxlength'),
currentFieldLength = fieldText.length,
numberOfLineBreaks = (fieldText.match(/\n/g) || []).length, // count line breaks
remainingCharacters = maxlength - currentFieldLength - numberOfLineBreaks,
threshold = 15, // hard limit of remaining characters when the label class changes
labelClass = '';
if (remainingCharacters < threshold) {
labelClass = 'label-danger';
} else if (remainingCharacters < threshold * 2) {
labelClass = 'label-warning';
} else {
labelClass = 'label-info';
}
return {
remainingCharacters: remainingCharacters,
labelClass: 'label ' + labelClass
};
};
/**
* Initialize input / text field "null" checkbox CSS overlay if no placeholder is set.
*/
FormEngine.initializeNullNoPlaceholderCheckboxes = function() {
$('.t3-form-field-eval-null-checkbox').each(function() {
// Add disabled class to "t3js-formengine-field-item" if the null checkbox is NOT set,
// This activates a CSS overlay "disabling" the input field and everything around.
var $checkbox = $(this).find('input[type="checkbox"]');
var $fieldItem = $(this).closest('.t3js-formengine-field-item');
if (!$checkbox.attr('checked')) {
$fieldItem.addClass('disabled');
}
});
};
/**
* Initialize input / text field "null" checkbox placeholder / real field if placeholder is set.
*/
FormEngine.initializeNullWithPlaceholderCheckboxes = function() {
$('.t3js-form-field-eval-null-placeholder-checkbox').each(function() {
FormEngine.toggleCheckboxField($(this).find('input[type="checkbox"]'));
});
};
/**
* Set initial state of both div's (one containing actual field, other containing placeholder field)
* depending on whether checkbox is checked or not
* @param $checkbox
*/
FormEngine.toggleCheckboxField = function($checkbox) {
var $item = $checkbox.closest('.t3js-formengine-field-item');
if ($checkbox.prop('checked')) {
$item.find('.t3js-formengine-placeholder-placeholder').hide();
$item.find('.t3js-formengine-placeholder-formfield').show();
$item.find('.t3js-formengine-placeholder-formfield').find(':input').focus();
} else {
$item.find('.t3js-formengine-placeholder-placeholder').show();
$item.find('.t3js-formengine-placeholder-formfield').hide();
}
};
/**
* This is the main function that is called on page load, but also after elements are asynchronously
* called e.g. after inline elements are loaded, or a new flexform section is added.
* Use this function in your extension like this "TYPO3.FormEngine.initialize()"
* if you add new fields dynamically.
*/
FormEngine.reinitialize = function() {
// Apply "close" button to all input / datetime fields
const clearables = Array.from(document.querySelectorAll('.t3js-clearable')).filter(inputElement => {
// Filter input fields being a date time picker and a color picker
return !inputElement.classList.contains('t3js-datetimepicker') && !inputElement.classList.contains('t3js-color-picker');
});
if (clearables.length > 0) {
require(['TYPO3/CMS/Backend/Input/Clearable'], function() {
clearables.forEach(clearableField => clearableField.clearable());
});
}
FormEngine.initializeNullNoPlaceholderCheckboxes();
FormEngine.initializeNullWithPlaceholderCheckboxes();
FormEngine.initializeLocalizationStateSelector();
FormEngine.initializeRemainingCharacterViews();
};
/**
* Disable the input field on load if localization state selector is set to "parent" or "source"
*/
FormEngine.initializeLocalizationStateSelector = function() {
$('.t3js-l10n-state-container').each(function() {
var $input = $(this).closest('.t3js-formengine-field-item').find('[data-formengine-input-name]');
var currentState = $(this).find('input[type="radio"]:checked').val();
if (currentState === 'parent' || currentState === 'source') {
$input.attr('disabled', 'disabled');
}
});
};
/**
* @return {boolean}
*/
FormEngine.hasChange = function() {
var formElementChanges = $('form[name="' + FormEngine.formName + '"] .has-change').length > 0,
inlineRecordChanges = $('[name^="data["].has-change').length > 0;
return formElementChanges || inlineRecordChanges;
};
/**
* @param {boolean} response
*/
FormEngine.preventExitIfNotSavedCallback = function(response) {
FormEngine.closeDocument();
};
/**
* Show modal to confirm following a clicked link to confirm leaving the document without saving
*
* @param {String} href
* @returns {Boolean}
*/
FormEngine.preventFollowLinkIfNotSaved = function(href) {
FormEngine.preventExitIfNotSaved(
function () {
window.location.href = href;
}
);
return false;
};
/**
* Show modal to confirm closing the document without saving.
*
* @param {Function} callback
*/
FormEngine.preventExitIfNotSaved = function(callback) {
callback = callback || FormEngine.preventExitIfNotSavedCallback;
if (FormEngine.hasChange()) {
var title = TYPO3.lang['label.confirm.close_without_save.title'] || 'Do you want to close without saving?';
var content = TYPO3.lang['label.confirm.close_without_save.content'] || 'You currently have unsaved changes. Are you sure you want to discard these changes?';
var $elem = $('<input />').attr('type', 'hidden').attr('name', '_saveandclosedok').attr('value', '1');
var buttons = [
{
text: TYPO3.lang['buttons.confirm.close_without_save.no'] || 'No, I will continue editing',
btnClass: 'btn-default',
name: 'no'
},
{
text: TYPO3.lang['buttons.confirm.close_without_save.yes'] || 'Yes, discard my changes',
btnClass: 'btn-default',
name: 'yes'
}
];
if ($('.has-error').length === 0) {
buttons.push({
text: TYPO3.lang['buttons.confirm.save_and_close'] || 'Save and close',
btnClass: 'btn-warning',
name: 'save',
active: true
});
}
var $modal = Modal.confirm(title, content, Severity.warning, buttons);
$modal.on('button.clicked', function(e) {
if (e.target.name === 'no') {
Modal.dismiss();
} else if (e.target.name === 'yes') {
Modal.dismiss();
callback.call(null, true);
} else if (e.target.name === 'save') {
$('form[name=' + FormEngine.formName + ']').append($elem);
Modal.dismiss();
FormEngine.saveDocument();
}
});
} else {
callback.call(null, true);
}
};
/**
* Show modal to confirm closing the document without saving
*/
FormEngine.preventSaveIfHasErrors = function() {
if ($('.has-error').length > 0) {
var title = TYPO3.lang['label.alert.save_with_error.title'] || 'You have errors in your form!';
var content = TYPO3.lang['label.alert.save_with_error.content'] || 'Please check the form, there is at least one error in your form.';
var $modal = Modal.confirm(title, content, Severity.error, [
{
text: TYPO3.lang['buttons.alert.save_with_error.ok'] || 'OK',
btnClass: 'btn-danger',
name: 'ok'
}
]);
$modal.on('button.clicked', function(e) {
if (e.target.name === 'ok') {
Modal.dismiss();
}
});
return false;
}
return true;
};
FormEngine.requestConfirmationOnFieldChange = function(fieldName, showConfirmation) {
const $field = FormEngine.getFieldElement(fieldName);
$field.on('change', function() {
if (showConfirmation) {
const $modal = Modal.confirm(
TYPO3.lang['FormEngine.refreshRequiredTitle'],
TYPO3.lang['FormEngine.refreshRequiredContent']
);
$modal.on('button.clicked', function(e) {
if (e.target.name === 'ok') {
FormEngine.saveDocument();
}
Modal.dismiss();
});
} else {
FormEngine.saveDocument();
}
});
};
/**
* Preview action
*
* When there are changes:
* Will take action based on local storage preset
* If preset is not available, a modal will open
*
* @param {Event} event
* @param {Function} callback
*/
FormEngine.previewAction = function(event, callback) {
callback = callback || FormEngine.previewActionCallback;
var previewUrl = event.target.href;
var isNew = event.target.dataset.hasOwnProperty('isNew');
var $actionElement = $('<input />').attr('type', 'hidden').attr('name', '_savedokview').attr('value', '1');
if (FormEngine.hasChange()) {
FormEngine.showPreviewModal(previewUrl, isNew, $actionElement, callback);
} else {
$('form[name=' + FormEngine.formName + ']').append($actionElement);
window.open('', 'newTYPO3frontendWindow');
document.editform.submit();
}
};
/**
* The callback for the preview action
*
* @param {string} modalButtonName
* @param {string} previewUrl
* @param {element} $actionElement
*/
FormEngine.previewActionCallback = function(modalButtonName, previewUrl, $actionElement) {
Modal.dismiss();
switch(modalButtonName) {
case 'discard':
var previewWin = window.open(previewUrl, 'newTYPO3frontendWindow');
previewWin.focus();
if (previewWin.location.href === previewUrl) {
previewWin.location.reload();
}