forked from vitmalina/w2ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
w2form.js
1209 lines (1170 loc) · 59 KB
/
w2form.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
/************************************************************************
* Library: Web 2.0 UI for jQuery (using prototypical inheritance)
* - Following objects defined
* - w2form - form widget
* - $().w2form - jQuery wrapper
* - Dependencies: jQuery, w2utils, w2fields, w2tabs, w2toolbar, w2alert
*
* == NICE TO HAVE ==
* - refresh(field) - would refresh only one field
* - include delta on save
* - form should read <select> <options> into items
* - two way data bindings
* - verify validation of fields
* - added getChanges() - not complete
* - nested record object
*
* == 1.5 changes
* - $('#form').w2form() - if called w/o argument then it returns form object
* - added onProgress
* - added field.html.style (for the whole field)
* - added enable/disable, show/hide
* - added field.disabled, field.hidden
* - when field is blank, set record.field = null
* - action: { caption: 'Limpiar', style: '', class: '', onClick: function () {} }
* - added ability to generate radio and select html in generateHTML()
*
************************************************************************/
(function () {
var w2form = function(options) {
// public properties
this.name = null;
this.header = '';
this.box = null; // HTML element that hold this element
this.url = '';
this.routeData = {}; // data for dynamic routes
this.formURL = ''; // url where to get form HTML
this.formHTML = ''; // form HTML (might be loaded from the url)
this.page = 0; // current page
this.recid = 0; // can be null or 0
this.fields = [];
this.actions = {};
this.record = {};
this.original = {};
this.postData = {};
this.toolbar = {}; // if not empty, then it is toolbar
this.tabs = {}; // if not empty, then it is tabs object
this.style = '';
this.focus = 0; // focus first or other element
// events
this.onRequest = null;
this.onLoad = null;
this.onValidate = null;
this.onSubmit = null;
this.onProgress = null;
this.onSave = null;
this.onChange = null;
this.onRender = null;
this.onRefresh = null;
this.onResize = null;
this.onDestroy = null;
this.onAction = null;
this.onToolbar = null;
this.onError = null;
// internal
this.isGenerated = false;
this.last = {
xhr: null // jquery xhr requests
};
$.extend(true, this, w2obj.form, options);
};
// ====================================================
// -- Registers as a jQuery plugin
$.fn.w2form = function(method) {
if ($.isPlainObject(method)) {
var obj = this;
// check name parameter
if (!w2utils.checkName(method, 'w2form')) return;
// remember items
var record = method.record;
var original = method.original;
var fields = method.fields;
var toolbar = method.toolbar;
var tabs = method.tabs;
// extend items
var object = new w2form(method);
$.extend(object, { record: {}, original: {}, fields: [], tabs: {}, toolbar: {}, handlers: [] });
if ($.isArray(tabs)) {
$.extend(true, object.tabs, { tabs: [] });
for (var t = 0; t < tabs.length; t++) {
var tmp = tabs[t];
if (typeof tmp === 'object') object.tabs.tabs.push(tmp); else object.tabs.tabs.push({ id: tmp, caption: tmp });
}
} else {
$.extend(true, object.tabs, tabs);
}
$.extend(true, object.toolbar, toolbar);
// reassign variables
if (fields) for (var p = 0; p < fields.length; p++) {
var field = $.extend(true, {}, fields[p]);
if (typeof field.name == 'undefined' && typeof field.field != 'undefined') field.name = field.field;
if (typeof field.field == 'undefined' && typeof field.name != 'undefined') field.field = field.name;
object.fields[p] = field;
}
for (var p in record) { // it is an object
if ($.isPlainObject(record[p])) {
object.record[p] = $.extend(true, {}, record[p]);
} else {
object.record[p] = record[p];
}
}
for (var p in original) { // it is an object
if ($.isPlainObject(original[p])) {
object.original[p] = $.extend(true, {}, original[p]);
} else {
object.original[p] = original[p];
}
}
if (obj.length > 0) object.box = obj[0];
// render if necessary
if (object.formURL != '') {
$.get(object.formURL, function (data) { // should always be $.get as it is template
object.formHTML = data;
object.isGenerated = true;
if ($(object.box).length != 0 || data.length != 0) {
$(object.box).html(data);
object.render(object.box);
}
});
} else if (object.formHTML != '') {
// it is already loaded into formHTML
} else if ($(this).length != 0 && $.trim($(this).html()) != '') {
object.formHTML = $(this).html();
} else { // try to generate it
object.formHTML = object.generateHTML();
}
// register new object
w2ui[object.name] = object;
// render if not loaded from url
if (object.formURL == '') {
if (String(object.formHTML).indexOf('w2ui-page') == -1) {
object.formHTML = '<div class="w2ui-page page-0">'+ object.formHTML +'</div>';
}
$(object.box).html(object.formHTML);
object.isGenerated = true;
object.render(object.box);
}
return object;
} else {
var obj = w2ui[$(this).attr('name')];
if (!obj) return null;
if (arguments.length > 0) {
if (obj[method]) obj[method].apply(obj, Array.prototype.slice.call(arguments, 1));
return this;
} else {
return obj;
}
}
};
// ====================================================
// -- Implementation of core functionality
w2form.prototype = {
msgNotJSON : w2utils.lang('Return data is not in JSON format.'),
msgAJAXerror : w2utils.lang('AJAX error. See console for more details.'),
msgRefresh : w2utils.lang('Refreshing...'),
msgSaving : w2utils.lang('Saving...'),
get: function (field, returnIndex) {
if (arguments.length === 0) {
var all = [];
for (var f1 = 0; f1 < this.fields.length; f1++) {
if (this.fields[f1].name != null) all.push(this.fields[f1].name);
}
return all;
} else {
for (var f2 = 0; f2 < this.fields.length; f2++) {
if (this.fields[f2].name == field) {
if (returnIndex === true) return f2; else return this.fields[f2];
}
}
return null;
}
},
set: function (field, obj) {
for (var f = 0; f < this.fields.length; f++) {
if (this.fields[f].name == field) {
$.extend(this.fields[f] , obj);
this.refresh();
return true;
}
}
return false;
},
show: function () {
var affected = 0;
for (var a = 0; a < arguments.length; a++) {
var fld = this.get(arguments[a]);
if (fld && fld.hidden) {
fld.hidden = false;
affected++;
}
}
if (affected > 0) this.refresh();
return affected;
},
hide: function () {
var affected = 0;
for (var a = 0; a < arguments.length; a++) {
var fld = this.get(arguments[a]);
if (fld && !fld.hidden) {
fld.hidden = true;
affected++;
}
}
if (affected > 0) this.refresh();
return affected;
},
enable: function () {
var affected = 0;
for (var a = 0; a < arguments.length; a++) {
var fld = this.get(arguments[a]);
if (fld && fld.disabled) {
fld.disabled = false;
affected++;
}
}
if (affected > 0) this.refresh();
return affected;
},
disable: function () {
var affected = 0;
for (var a = 0; a < arguments.length; a++) {
var fld = this.get(arguments[a]);
if (fld && !fld.disabled) {
fld.disabled = true;
affected++;
}
}
if (affected > 0) this.refresh();
return affected;
},
reload: function (callBack) {
var url = (typeof this.url != 'object' ? this.url : this.url.get);
if (url && this.recid != 0 && this.recid != null) {
// this.clear();
this.request(callBack);
} else {
// this.refresh(); // no need to refresh
if (typeof callBack == 'function') callBack();
}
},
clear: function () {
this.recid = 0;
this.record = {};
$().w2tag();
this.refresh();
},
error: function (msg) {
var obj = this;
// let the management of the error outside of the grid
var eventData = this.trigger({ target: this.name, type: 'error', message: msg , xhr: this.last.xhr });
if (eventData.isCancelled === true) {
if (typeof callBack == 'function') callBack();
return;
}
// need a time out because message might be already up)
setTimeout(function () { w2alert(msg, 'Error'); }, 1);
// event after
this.trigger($.extend(eventData, { phase: 'after' }));
},
validate: function (showErrors) {
if (typeof showErrors == 'undefined') showErrors = true;
$().w2tag(); // hide all tags before validating
// validate before saving
var errors = [];
for (var f = 0; f < this.fields.length; f++) {
var field = this.fields[f];
if (this.record[field.name] == null) this.record[field.name] = '';
switch (field.type) {
case 'int':
if (this.record[field.name] && !w2utils.isInt(this.record[field.name])) {
errors.push({ field: field, error: w2utils.lang('Not an integer') });
}
break;
case 'float':
if (this.record[field.name] && !w2utils.isFloat(this.record[field.name])) {
errors.push({ field: field, error: w2utils.lang('Not a float') });
}
break;
case 'money':
if (this.record[field.name] && !w2utils.isMoney(this.record[field.name])) {
errors.push({ field: field, error: w2utils.lang('Not in money format') });
}
break;
case 'color':
case 'hex':
if (this.record[field.name] && !w2utils.isHex(this.record[field.name])) {
errors.push({ field: field, error: w2utils.lang('Not a hex number') });
}
break;
case 'email':
if (this.record[field.name] && !w2utils.isEmail(this.record[field.name])) {
errors.push({ field: field, error: w2utils.lang('Not a valid email') });
}
break;
case 'checkbox':
// convert true/false
if (this.record[field.name] == true) this.record[field.name] = 1; else this.record[field.name] = 0;
break;
case 'date':
// format date before submit
if (!field.options.format) field.options.format = w2utils.settings.date_format;
if (this.record[field.name] && !w2utils.isDate(this.record[field.name], field.options.format)) {
errors.push({ field: field, error: w2utils.lang('Not a valid date') + ': ' + field.options.format });
} else {
}
break;
case 'list':
case 'combo':
break;
case 'enum':
break;
}
// === check required - if field is '0' it should be considered not empty
var val = this.record[field.name];
if (field.required && (val === '' || ($.isArray(val) && val.length == 0) || ($.isPlainObject(val) && $.isEmptyObject(val)))) {
errors.push({ field: field, error: w2utils.lang('Required field') });
}
if (field.equalto && this.record[field.name] != this.record[field.equalto]) {
errors.push({ field: field, error: w2utils.lang('Field should be equal to ') + field.equalto });
}
}
// event before
var eventData = this.trigger({ phase: 'before', target: this.name, type: 'validate', errors: errors });
if (eventData.isCancelled === true) return;
// show error
if (showErrors) for (var e in eventData.errors) {
var err = eventData.errors[e];
if (err.field.type == 'radio') { // for radio and checkboxes
$($(err.field.el).parents('div')[0]).w2tag(err.error, { "class": 'w2ui-error' });
} else if (['enum', 'file'].indexOf(err.field.type) != -1) {
(function (err) {
setTimeout(function () {
var fld = $(err.field.el).data('w2field').helpers.multi;
$(err.field.el).w2tag(err.error);
$(fld).addClass('w2ui-error');
}, 1);
})(err);
} else {
$(err.field.el).w2tag(err.error, { "class": 'w2ui-error' });
}
this.goto(errors[0].field.page);
}
// event after
this.trigger($.extend(eventData, { phase: 'after' }));
return errors;
},
getChanges: function () {
var differ = function(record, original, result) {
for (var i in record) {
if (typeof record[i] == "object") {
result[i] = differ(record[i], original[i] || {}, {});
if (!result[i] || $.isEmptyObject(result[i])) delete result[i];
} else if (record[i] != original[i]) {
result[i] = record[i];
}
}
return result;
};
return differ(this.record, this.original, {});
},
request: function (postData, callBack) { // if (1) param then it is call back if (2) then postData and callBack
var obj = this;
// check for multiple params
if (typeof postData == 'function') {
callBack = postData;
postData = null;
}
if (typeof postData == 'undefined' || postData == null) postData = {};
if (!this.url || (typeof this.url == 'object' && !this.url.get)) return;
if (this.recid == null || typeof this.recid == 'undefined') this.recid = 0;
// build parameters list
var params = {};
// add list params
params['cmd'] = 'get-record';
params['recid'] = this.recid;
// append other params
$.extend(params, this.postData);
$.extend(params, postData);
// event before
var eventData = this.trigger({ phase: 'before', type: 'request', target: this.name, url: this.url, postData: params });
if (eventData.isCancelled === true) { if (typeof callBack == 'function') callBack({ status: 'error', message: 'Request aborted.' }); return; }
// default action
this.record = {};
this.original = {};
// call server to get data
this.lock(this.msgRefresh);
var url = eventData.url;
if (typeof eventData.url == 'object' && eventData.url.get) url = eventData.url.get;
if (this.last.xhr) try { this.last.xhr.abort(); } catch (e) {}
// process url with routeData
if (!$.isEmptyObject(obj.routeData)) {
var info = w2utils.parseRoute(url);
if (info.keys.length > 0) {
for (var k = 0; k < info.keys.length; k++) {
if (obj.routeData[info.keys[k].name] == null) continue;
url = url.replace((new RegExp(':'+ info.keys[k].name, 'g')), obj.routeData[info.keys[k].name]);
}
}
}
var ajaxOptions = {
type : 'POST',
url : url,
data : eventData.postData,
dataType : 'text' // expected from server
};
if (w2utils.settings.dataType == 'HTTP') {
ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
if (w2utils.settings.dataType == 'RESTFULL') {
ajaxOptions.type = 'GET';
ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
if (w2utils.settings.dataType == 'JSON') {
ajaxOptions.type = 'POST';
ajaxOptions.data = JSON.stringify(ajaxOptions.data);
ajaxOptions.contentType = 'application/json';
}
this.last.xhr = $.ajax(ajaxOptions)
.done(function (data, status, xhr) {
obj.unlock();
// event before
var eventData = obj.trigger({ phase: 'before', target: obj.name, type: 'load', xhr: xhr });
if (eventData.isCancelled === true) {
if (typeof callBack == 'function') callBack({ status: 'error', message: 'Request aborted.' });
return;
}
// parse server response
var data;
var responseText = obj.last.xhr.responseText;
if (status != 'error') {
// default action
if (typeof responseText != 'undefined' && responseText != '') {
// check if the onLoad handler has not already parsed the data
if (typeof responseText == "object") {
data = responseText;
} else {
// $.parseJSON or $.getJSON did not work because those expect perfect JSON data - where everything is in double quotes
//
// TODO: avoid (potentially malicious) code injection from the response.
try { eval('data = '+ responseText); } catch (e) { }
}
if (typeof data == 'undefined') {
data = {
status : 'error',
message : obj.msgNotJSON,
responseText : responseText
}
}
if (data['status'] == 'error') {
obj.error(data['message']);
} else {
obj.record = $.extend({}, data.record);
obj.original = $.extend({}, data.record);
}
}
} else {
obj.error('AJAX Error ' + xhr.status + ': '+ xhr.statusText);
data = {
status : 'error',
message : obj.msgAJAXerror,
responseText : responseText
};
}
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
obj.refresh();
// call back
if (typeof callBack == 'function') callBack(data);
})
.fail(function (xhr, status, error) {
// trigger event
var errorObj = { status: status, error: error, rawResponseText: xhr.responseText };
var eventData2 = obj.trigger({ phase: 'before', type: 'error', error: errorObj, xhr: xhr });
if (eventData2.isCancelled === true) return;
// default behavior
if (status != 'abort') {
var data;
try { data = $.parseJSON(xhr.responseText) } catch (e) {}
console.log('ERROR: Server communication failed.',
'\n EXPECTED:', { status: 'success', items: [{ id: 1, text: 'item' }] },
'\n OR:', { status: 'error', message: 'error message' },
'\n RECEIVED:', typeof data == 'object' ? data : xhr.responseText);
}
// event after
obj.trigger($.extend(eventData2, { phase: 'after' }));
});
// event after
this.trigger($.extend(eventData, { phase: 'after' }));
},
submit: function (postData, callBack) {
return this.save(postData, callBack);
},
save: function (postData, callBack) {
var obj = this;
$(this.box).find(':focus').change(); // trigger onchange
// check for multiple params
if (typeof postData == 'function') {
callBack = postData;
postData = null;
}
// validation
var errors = obj.validate(true);
if (errors.length !== 0) return;
// submit save
if (typeof postData == 'undefined' || postData == null) postData = {};
if (!obj.url || (typeof obj.url == 'object' && !obj.url.save)) {
console.log("ERROR: Form cannot be saved because no url is defined.");
return;
}
obj.lock(obj.msgSaving + ' <span id="'+ obj.name +'_progress"></span>');
// need timer to allow to lock
setTimeout(function () {
// build parameters list
var params = {};
// add list params
params['cmd'] = 'save-record';
params['recid'] = obj.recid;
// append other params
$.extend(params, obj.postData);
$.extend(params, postData);
params.record = $.extend(true, {}, obj.record);
// event before
var eventData = obj.trigger({ phase: 'before', type: 'submit', target: obj.name, url: obj.url, postData: params });
if (eventData.isCancelled === true) return;
// default action
var url = eventData.url;
if (typeof eventData.url == 'object' && eventData.url.save) url = eventData.url.save;
if (obj.last.xhr) try { obj.last.xhr.abort(); } catch (e) {}
// process url with routeData
if (!$.isEmptyObject(obj.routeData)) {
var info = w2utils.parseRoute(url);
if (info.keys.length > 0) {
for (var k = 0; k < info.keys.length; k++) {
if (obj.routeData[info.keys[k].name] == null) continue;
url = url.replace((new RegExp(':'+ info.keys[k].name, 'g')), obj.routeData[info.keys[k].name]);
}
}
}
var ajaxOptions = {
type : 'POST',
url : url,
data : eventData.postData,
dataType : 'text', // expected from server
xhr : function() {
var xhr = new window.XMLHttpRequest();
// upload
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var eventData3 = obj.trigger({ phase: 'before', type: 'progress', total: evt.total, loaded: evt.loaded, originalEvent: evt });
if (eventData3.isCancelled === true) return;
// default behavior
var percent = Math.round(evt.loaded / evt.total * 100);
$('#'+ obj.name + '_progress').text(''+ percent + '%');
// event after
obj.trigger($.extend(eventData3, { phase: 'after' }));
}
}, false);
return xhr;
}
};
if (w2utils.settings.dataType == 'HTTP') {
ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
if (w2utils.settings.dataType == 'RESTFULL') {
if (obj.recid != 0 && obj.recid != null) ajaxOptions.type = 'PUT';
ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
if (w2utils.settings.dataType == 'JSON') {
ajaxOptions.type = 'POST';
ajaxOptions.data = JSON.stringify(ajaxOptions.data);
ajaxOptions.contentType = 'application/json';
}
obj.last.xhr = $.ajax(ajaxOptions)
.done(function (data, status, xhr) {
obj.unlock();
// event before
var eventData = obj.trigger({ phase: 'before', target: obj.name, type: 'save', xhr: xhr, status: status });
if (eventData.isCancelled === true) return;
// parse server response
var data;
var responseText = xhr.responseText;
if (status != 'error') {
// default action
if (typeof responseText != 'undefined' && responseText != '') {
// check if the onLoad handler has not already parsed the data
if (typeof responseText == "object") {
data = responseText;
} else {
// $.parseJSON or $.getJSON did not work because those expect perfect JSON data - where everything is in double quotes
//
// TODO: avoid (potentially malicious) code injection from the response.
try { eval('data = '+ responseText); } catch (e) { }
}
if (typeof data == 'undefined') {
data = {
status : 'error',
message : obj.msgNotJSON,
responseText : responseText
}
}
if (data['status'] == 'error') {
obj.error(data['message']);
} else {
obj.original = $.extend({}, obj.record);
}
}
} else {
obj.error('AJAX Error ' + xhr.status + ': '+ xhr.statusText);
data = {
status : 'error',
message : obj.msgAJAXerror,
responseText : responseText
};
}
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
obj.refresh();
// call back
if (data.status == 'success' && typeof callBack == 'function') callBack(data);
})
.fail(function (xhr, status, error) {
// trigger event
var errorObj = { status: status, error: error, rawResponseText: xhr.responseText };
var eventData2 = obj.trigger({ phase: 'before', type: 'error', error: errorObj, xhr: xhr });
if (eventData2.isCancelled === true) return;
// default behavior
console.log('ERROR: server communication failed. The server should return',
{ status: 'success' }, 'OR', { status: 'error', message: 'error message' },
', instead the AJAX request produced this: ', errorObj);
// event after
obj.trigger($.extend(eventData2, { phase: 'after' }));
});
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}, 50);
},
lock: function (msg, showSpinner) {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(this.box);
setTimeout(function () { w2utils.lock.apply(window, args); }, 10);
},
unlock: function (speed) {
var box = this.box;
setTimeout(function () { w2utils.unlock(box, speed); }, 25); // needed timer so if server fast, it will not flash
},
goto: function (page) {
if (typeof page != 'undefined') this.page = page;
// if it was auto size, resize it
if ($(this.box).data('auto-size') === true) $(this.box).height(0);
this.refresh();
},
generateHTML: function () {
var pages = []; // array for each page
var group = '';
var page;
for (var f = 0; f < this.fields.length; f++) {
var html = '';
var field = this.fields[f];
if (typeof field.html == 'undefined') field.html = {};
if (typeof field.options == 'undefined') field.options = {};
field.html = $.extend(true, { caption: '', span: 6, attr: '', text: '', style: '', page: 0 }, field.html);
if (typeof page == 'undefined') page = field.html.page;
if (field.html.caption == '') field.html.caption = field.name;
// input control
var input = '<input name="'+ field.name +'" type="text" '+ field.html.attr +'/>';
switch (field.type) {
case 'pass':
case 'password':
input = '<input name="' + field.name + '" type = "password" ' + field.html.attr + '/>';
break;
case 'checkbox':
input = '<input name="'+ field.name +'" type="checkbox" '+ field.html.attr +'/>';
break;
case 'radio':
input = '';
// normalized options
var items = field.options.items ? field.options.items : field.html.items;
if (!$.isArray(items)) items = [];
if (items.length > 0) {
items = w2obj.field.prototype.normMenu(items);
}
// generate
for (var i = 0; i < items.length; i++) {
input += '<label><input name="' + field.name + '" type = "radio" ' + field.html.attr + ' value="'+ items[i].id + '"/>' +
' ' + items[i].text + '</label><br>';
}
break;
case 'select':
input = '<select name="' + field.name + '" ' + field.html.attr + '>';
// normalized options
var items = field.options.items ? field.options.items : field.html.items;
if (!$.isArray(items)) items = [];
if (items.length > 0) {
items = w2obj.field.prototype.normMenu(items);
}
// generate
for (var i = 0; i < items.length; i++) {
input += '<option value="'+ items[i].id + '">' + items[i].text + '</option>';
}
input += '</select>';
break;
case 'textarea':
input = '<textarea name="'+ field.name +'" '+ field.html.attr +'></textarea>';
break;
case 'toggle':
input = '<input name="'+ field.name +'" type="checkbox" '+ field.html.attr +' class="w2ui-toggle"/><div><div></div></div>';
break;
}
if (field.html.group) {
if (group != '') html += '\n </div>';
html += '\n <div class="w2ui-group-title">'+ field.html.group + '</div>\n <div class="w2ui-group">';
group = field.html.group;
}
if (field.html.page != page && group != '') {
pages[pages.length-1] += '\n </div>';
group = '';
}
html += '\n <div class="w2ui-field '+ (typeof field.html.span != 'undefined' ? 'w2ui-span'+ field.html.span : '') +'" style="'+ field.html.style +'">'+
'\n <label>' + w2utils.lang(field.html.caption) +'</label>'+
'\n <div>'+ input + w2utils.lang(field.html.text) + '</div>'+
'\n </div>';
if (typeof pages[field.html.page] == 'undefined') pages[field.html.page] = '';
pages[field.html.page] += html;
page = field.html.page;
}
if (group != '') pages[pages.length-1] += '\n </div>';
if (this.tabs.tabs) {
for (var i = 0; i < this.tabs.tabs.length; i++) if (typeof pages[i] == 'undefined') pages[i] = '';
}
for (var p = 0; p < pages.length; p++) pages[p] = '<div class="w2ui-page page-'+ p +'">' + pages[p] + '\n</div>';
// buttons if any
var buttons = '';
if (!$.isEmptyObject(this.actions)) {
var addClass = '';
buttons += '\n<div class="w2ui-buttons">';
for (var a in this.actions) { // it is an object
var act = this.actions[a];
var info = { caption: '', style: '', "class": '' };
if ($.isPlainObject(act)) {
if (act.caption) info.caption = act.caption;
if (act.style) info.style = act.style;
if (act["class"]) info['class'] = act['class'];
} else {
info.caption = a;
if (['save', 'update', 'create'].indexOf(a.toLowerCase()) != -1) info['class'] = 'w2ui-btn-green'; else info['class'] = '';
}
buttons += '\n <button name="'+ a +'" class="w2ui-btn '+ info['class'] +'" style="'+ info.style +'">'+
w2utils.lang(info.caption) +'</button>';
}
buttons += '\n</div>';
}
return pages.join('') + buttons;
},
action: function (action, event) {
var click = null;
var act = this.actions[action];
var click = act;
if ($.isPlainObject(act) && act.onClick) click = act.onClick;
// event before
var eventData = this.trigger({ phase: 'before', target: action, type: 'action', click: click, originalEvent: event });
if (eventData.isCancelled === true) return;
// default actions
if (typeof click == 'function') click.call(this, event);
// event after
this.trigger($.extend(eventData, { phase: 'after' }));
},
resize: function () {
var obj = this;
// event before
var eventData = this.trigger({ phase: 'before', target: this.name, type: 'resize' });
if (eventData.isCancelled === true) return;
// default behaviour
var main = $(this.box).find('> div');
var header = $(this.box).find('> div .w2ui-form-header');
var toolbar = $(this.box).find('> div .w2ui-form-toolbar');
var tabs = $(this.box).find('> div .w2ui-form-tabs');
var page = $(this.box).find('> div .w2ui-page');
var cpage = $(this.box).find('> div .w2ui-page.page-'+ this.page);
var dpage = $(this.box).find('> div .w2ui-page.page-'+ this.page + ' > div');
var buttons = $(this.box).find('> div .w2ui-buttons');
// if no height, calculate it
resizeElements();
if (parseInt($(this.box).height()) == 0 || $(this.box).data('auto-size') === true) {
$(this.box).height(
(header.length > 0 ? w2utils.getSize(header, 'height') : 0) +
((typeof this.tabs === 'object' && $.isArray(this.tabs.tabs) && this.tabs.tabs.length > 0) ? w2utils.getSize(tabs, 'height') : 0) +
((typeof this.toolbar == 'object' && $.isArray(this.toolbar.items) && this.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') : 0) +
(page.length > 0 ? w2utils.getSize(dpage, 'height') + w2utils.getSize(cpage, '+height') + 12 : 0) + // why 12 ???
(buttons.length > 0 ? w2utils.getSize(buttons, 'height') : 0)
);
$(this.box).data('auto-size', true);
}
resizeElements();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
function resizeElements() {
// resize elements
main.width($(obj.box).width()).height($(obj.box).height());
toolbar.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0));
tabs.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0)
+ ((typeof obj.toolbar == 'object' && $.isArray(obj.toolbar.items) && obj.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') : 0));
page.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0)
+ ((typeof obj.toolbar == 'object' && $.isArray(obj.toolbar.items) && obj.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') + 5 : 0)
+ ((typeof obj.tabs === 'object' && $.isArray(obj.tabs.tabs) && obj.tabs.tabs.length > 0) ? w2utils.getSize(tabs, 'height') + 5 : 0));
page.css('bottom', (buttons.length > 0 ? w2utils.getSize(buttons, 'height') : 0));
}
},
refresh: function () {
var time = (new Date()).getTime();
var obj = this;
if (!this.box) return;
if (!this.isGenerated || typeof $(this.box).html() == 'undefined') return;
// update what page field belongs
$(this.box).find('input, textarea, select').each(function (index, el) {
var name = (typeof $(el).attr('name') != 'undefined' ? $(el).attr('name') : $(el).attr('id'));
var field = obj.get(name);
if (field) {
// find page
var div = $(el).parents('.w2ui-page');
if (div.length > 0) {
for (var i = 0; i < 100; i++) {
if (div.hasClass('page-'+i)) { field.page = i; break; }
}
}
}
});
// event before
var eventData = this.trigger({ phase: 'before', target: this.name, type: 'refresh', page: this.page })
if (eventData.isCancelled === true) return;
// default action
$(this.box).find('.w2ui-page').hide();
$(this.box).find('.w2ui-page.page-' + this.page).show();
$(this.box).find('.w2ui-form-header').html(this.header);
// refresh tabs if needed
if (typeof this.tabs === 'object' && $.isArray(this.tabs.tabs) && this.tabs.tabs.length > 0) {
$('#form_'+ this.name +'_tabs').show();
this.tabs.active = this.tabs.tabs[this.page].id;
this.tabs.refresh();
} else {
$('#form_'+ this.name +'_tabs').hide();
}
// refresh tabs if needed
if (typeof this.toolbar == 'object' && $.isArray(this.toolbar.items) && this.toolbar.items.length > 0) {
$('#form_'+ this.name +'_toolbar').show();
this.toolbar.refresh();
} else {
$('#form_'+ this.name +'_toolbar').hide();
}
// refresh values of all fields
for (var f = 0; f < this.fields.length; f++) {
var field = this.fields[f];
if (typeof field.name == 'undefined' && typeof field.field != 'undefined') field.name = field.field;
if (typeof field.field == 'undefined' && typeof field.name != 'undefined') field.field = field.name;
field.$el = $(this.box).find('[name="'+ String(field.name).replace(/\\/g, '\\\\') +'"]');
field.el = field.$el[0];
if (typeof field.el == 'undefined') {
console.log('ERROR: Cannot associate field "'+ field.name + '" with html control. Make sure html control exists with the same name.');
//return;
}
if (field.el) field.el.id = field.name;
var tmp = $(field).data('w2field');
if (tmp) tmp.clear();
$(field.$el).off('change').on('change', function () {
var value_new = this.value;
var value_previous = obj.record[this.name] ? obj.record[this.name] : '';
var field = obj.get(this.name);
if (['list', 'enum', 'file'].indexOf(field.type) != -1 && $(this).data('selected')) {
var nv = $(this).data('selected');
var cv = obj.record[this.name];
if ($.isArray(nv)) {
value_new = [];
for (var i = 0; i < nv.length; i++) value_new[i] = $.extend(true, {}, nv[i]); // clone array
}
if ($.isPlainObject(nv)) {
value_new = $.extend(true, {}, nv); // clone object
}
if ($.isArray(cv)) {
value_previous = [];
for (var i = 0; i < cv.length; i++) value_previous[i] = $.extend(true, {}, cv[i]); // clone array
}
if ($.isPlainObject(cv)) {
value_previous = $.extend(true, {}, cv); // clone object
}
}
if (field.type == 'toggle') value_new = ($(this).prop('checked') ? 1 : 0);
// clean extra chars
if (['int', 'float', 'percent', 'money', 'currency'].indexOf(field.type) != -1) {
value_new = $(this).data('w2field').clean(value_new);
}
if (value_new === value_previous) return;
// event before
var eventData = obj.trigger({ phase: 'before', target: this.name, type: 'change', value_new: value_new, value_previous: value_previous });
if (eventData.isCancelled === true) {
$(this).val(obj.record[this.name]); // return previous value
return;
}
// default action
var val = this.value;
if (this.type == 'select') val = this.value;
if (this.type == 'checkbox') val = this.checked ? true : false;
if (this.type == 'radio') {
field.$el.each(function (index, el) {
if (el.checked) val = el.value;
});
}
if (['int', 'float', 'percent', 'money', 'currency', 'list', 'combo', 'enum', 'file', 'toggle'].indexOf(field.type) != -1) {
val = value_new;
}
if (['enum', 'file'].indexOf(field.type) != -1) {
if (val.length > 0) {
var fld = $(field.el).data('w2field').helpers.multi;
$(fld).removeClass('w2ui-error');
}
}
if (val == '' || ($.isArray(val) && val.length == 0) || ($.isPlainObject(val) && $.isEmptyObject(val))) val = null;
obj.record[this.name] = val;
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
});
// required
if (field.required) {
$(field.el).parent().parent().addClass('w2ui-required');
} else {
$(field.el).parent().parent().removeClass('w2ui-required');
}
// disabled
if (field.disabled != null) {
if (field.disabled) {
$(field.el).prop('readonly', true);
} else {
$(field.el).prop('readonly', false);
}
}
// hidden
if (field.hidden) {
$(field.el).parent().parent().hide();
} else {
$(field.el).parent().parent().show();
}
}
// attach actions on buttons
$(this.box).find('button, input[type=button]').each(function (index, el) {
$(el).off('click').on('click', function (event) {
var action = this.value;
if (this.id) action = this.id;
if (this.name) action = this.name;
obj.action(action, event);
});
});
// init controls with record
for (var f = 0; f < this.fields.length; f++) {
var field = this.fields[f];
var value = (typeof this.record[field.name] != 'undefined' ? this.record[field.name] : '');
if (!field.el) continue;
field.type = String(field.type).toLowerCase();
if (!field.options) field.options = {};
switch (field.type) {