/
etemplate2.js
1334 lines (1201 loc) · 37.3 KB
/
etemplate2.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
/**
* EGroupware eTemplate2 - JS file which contains the complete et2 module
*
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
* @package etemplate
* @subpackage api
* @link http://www.egroupware.org
* @author Andreas Stöckel
* @copyright Stylite 2011
* @version $Id$
*/
/*egw:uses
// Include all widget classes here
et2_widget_template;
et2_widget_grid;
et2_widget_box;
et2_widget_hbox;
et2_widget_groupbox;
et2_widget_split;
et2_widget_button;
et2_widget_color;
et2_widget_description;
et2_widget_entry;
et2_widget_textbox;
et2_widget_number;
et2_widget_url;
et2_widget_selectbox;
et2_widget_checkbox;
et2_widget_radiobox;
et2_widget_date;
et2_widget_dialog;
et2_widget_diff;
et2_widget_dropdown_button;
et2_widget_styles;
et2_widget_favorites;
et2_widget_html;
et2_widget_htmlarea;
et2_widget_tabs;
et2_widget_taglist;
et2_widget_timestamper;
et2_widget_toolbar;
et2_widget_tree;
et2_widget_historylog;
et2_widget_hrule;
et2_widget_image;
et2_widget_iframe;
et2_widget_file;
et2_widget_link;
et2_widget_progress;
et2_widget_portlet;
et2_widget_selectAccount;
et2_widget_ajaxSelect;
et2_widget_vfs;
et2_widget_video;
et2_widget_barcode;
et2_widget_itempicker;
et2_widget_script;
et2_extension_nextmatch;
et2_extension_customfields;
// Requirements for the etemplate2 object
et2_core_common;
et2_core_xml;
et2_core_arrayMgr;
et2_core_interfaces;
et2_core_legacyJSFunctions;
// Include the client side api core
jsapi.egw_core;
jsapi.egw_json;
*/
/**
* The etemplate2 class manages a certain etemplate2 instance.
*
* @param _container is the DOM-Node into which the DOM-Nodes of this instance
* should be inserted
* @param _menuaction is the URL to which the form data should be submitted.
*/
function etemplate2(_container, _menuaction)
{
if (typeof _menuaction == "undefined")
{
_menuaction = "EGroupware\\Api\\Etemplate::ajax_process_content";
}
// Copy the given parameters
this.DOMContainer = _container;
this.menuaction = _menuaction;
// Unique ID to prevent DOM collisions across multiple templates
this.uniqueId = _container.getAttribute("id") ? _container.getAttribute("id").replace('.','-') : '';
/**
* Preset the object variable
* @type {et2_container}
*/
this.widgetContainer = null;
}
// List of templates (XML) that are known, not always used. Indexed by id.
// We share list of templates with iframes and popups
try {
if (opener && opener.etemplate2)
{
etemplate2.prototype.templates = opener.etemplate2.prototype.templates;
}
else if (top.etemplate2)
{
etemplate2.prototype.templates = top.etemplate2.prototype.templates;
}
}
catch (e) {
// catch security exception if opener is from a different domain
console.log('Security exception accessing etemplate2.prototype of opener or top!');
}
if (typeof etemplate2.prototype.templates == "undefined")
{
etemplate2.prototype.templates = {};
}
/**
* Calls the resize event of all widgets
*
* @param {jQuery.event} e
*/
etemplate2.prototype.resize = function(e)
{
var event = e;
var self = this;
var excess_height = false;
// Check if the framework has an specific excess height calculation
if (typeof window.framework != 'undefined' && typeof window.framework.get_wExcessHeight != 'undefined')
{
excess_height = window.framework.get_wExcessHeight(window);
}
//@TODO implement getaccess height for other framework and remove
if (typeof event != 'undefined' && event.type == 'resize')
{
if(this.resize_timeout)
{
clearTimeout(this.resize_timeout);
}
this.resize_timeout = setTimeout(function(){
self.resize_timeout = false;
if (self.widgetContainer)
{
var appHeader = jQuery('#divAppboxHeader');
//Calculate the excess height
excess_height = egw(window).is_popup()? jQuery(window).height() - jQuery(self.DOMContainer).height() - appHeader.outerHeight()+11: false;
// Recalculate excess height if the appheader is shown
if (appHeader.length > 0 && appHeader.is(':visible')) excess_height -= appHeader.outerHeight()-9;
// Do not resize if the template height is bigger than screen available height
// For templates which have sub templates and they are bigger than screenHeight
if(screen.availHeight < jQuery(self.DOMContainer).height()) excess_height = 0;
// Call the "resize" event of all functions which implement the
// "IResizeable" interface
self.widgetContainer.iterateOver(function(_widget) {
_widget.resize(excess_height);
}, self, et2_IResizeable);
}
},100);
}
// Initial resize needs to be resized immediately (for instance for nextmatch resize)
else if(this.widgetContainer)
{
// Call the "resize" event of all functions which implement the
// "IResizeable" interface
this.widgetContainer.iterateOver(function(_widget) {
_widget.resize(excess_height);
}, this, et2_IResizeable);
}
};
/**
* Clears the current instance.
*/
etemplate2.prototype.clear = function()
{
jQuery(this.DOMContainer).trigger('clear');
// Remove any handlers on window (resize)
if(this.uniqueId)
{
jQuery(window).off("."+this.uniqueId);
}
// call our destroy_session handler, if it is not already unbind, and unbind it after
if (this.destroy_session)
{
this.destroy_session();
this.unbind_unload();
}
if (this.widgetContainer != null)
{
// Un-register handler
this.widgetContainer.egw().unregisterJSONPlugin(etemplate2_handle_assign, this, 'assign');
this.widgetContainer.free();
this.widgetContainer = null;
}
jQuery(this.DOMContainer).empty();
// Remove self from the index
for(var name in this.templates)
{
if(typeof etemplate2._byTemplate[name] == "undefined") continue;
for(var i = 0; i < etemplate2._byTemplate[name].length; i++)
{
if(etemplate2._byTemplate[name][i] == this)
{
etemplate2._byTemplate[name].splice(i,1);
}
}
}
};
/**
* Creates an associative array containing the data array managers for each part
* of the associative data array. A part is something like "content", "readonlys"
* or "sel_options".
*
* @param {object} _data object with values for attributes content, sel_options, readonlys, modifications
*/
etemplate2.prototype._createArrayManagers = function(_data)
{
if (typeof _data == "undefined")
{
_data = {};
}
// Create all neccessary _data entries
var neededEntries = ["content", "sel_options", "readonlys", "modifications",
"validation_errors"];
for (var i = 0; i < neededEntries.length; i++)
{
if (typeof _data[neededEntries[i]] == "undefined" || !_data[neededEntries[i]])
{
egw.debug("log", "Created not passed entry '" + neededEntries[i] +
"' in data array.");
_data[neededEntries[i]] = {};
}
}
var result = {};
// Create an array manager object for each part of the _data array.
for (var key in _data)
{
switch (key) {
case "etemplate_exec_id": // already processed
case "app_header":
break;
case "readonlys":
result[key] = new et2_readonlysArrayMgr(_data[key]);
result[key].perspectiveData.owner = this.widgetContainer;
break;
default:
result[key] = new et2_arrayMgr(_data[key]);
result[key].perspectiveData.owner = this.widgetContainer;
}
}
return result;
};
/**
* Bind our unload handler to notify server that eT session/request no longer needed
*
* We only bind, if we have an etemplate_exec_id: not the case for pure client-side
* calls, eg. via et2_dialog.
*/
etemplate2.prototype.bind_unload = function()
{
if (this.etemplate_exec_id)
{
this.destroy_session = jQuery.proxy(function(ev)
{
var request = egw.json("EGroupware\\Api\\Etemplate::ajax_destroy_session",
[this.etemplate_exec_id], null, null, false);
request.sendRequest();
}, this);
if (!window.onbeforeunload)
{
window.onbeforeunload = this.destroy_session;
}
}
};
/**
* Unbind our unload handler
*/
etemplate2.prototype.unbind_unload = function()
{
if (window.onbeforeunload === this.destroy_session)
{
window.onbeforeunload = null;
}
else
{
var onbeforeunload = window.onbeforeunload;
window.onbeforeunload = null;
// bind unload handler again (can NOT do it direct, as this would be quick enough to be still triggered!)
window.setTimeout(function(){window.onbeforeunload = onbeforeunload;}, 100);
}
delete this.destroy_session;
};
/**
* Download a URL not triggering our unload handler and therefore destroying our et2 request
*
* @param {string} _url
*/
etemplate2.prototype.download = function(_url)
{
// need to unbind unload handler to NOT destroy et2 session
this.unbind_unload();
document.location = _url;
// bind unload handler again (can NOT do it direct, as this would be quick enough to be still triggered!)
window.setTimeout(jQuery.proxy(this.bind_unload, this), 100);
};
/**
* Loads the template from the given URL and sets the data object
*
* @param {string} _name name of template
* @param {string} _url url to load template
* @param {object} _data object with attributes content, langRequire, etemplate_exec_id, ...
* @param {function} _callback called after tempalte is loaded
* @param {object} _app local app object
* @param {boolean} _no_et2_ready true: do not send et2_ready, used by et2_dialog to not overwrite app.js et2 object
*/
etemplate2.prototype.load = function(_name, _url, _data, _callback, _app, _no_et2_ready)
{
var app = _app || window.app;
this.name = _name; // store top-level template name to have it available in widgets
// store template base url, in case initial template is loaded via webdav, to use that for further loads too
// need to split off domain first, as it could contain app-name part of template eg. stylite.report.xet and https://my.stylite.de/egw/...
if (_url && _url[0] != '/')
{
this.template_base_url = _url.match(/https?:\/\/[^/]+/).shift();
_url = _url.split(this.template_base_url)[1];
}
else
{
this.template_base_url = '';
}
this.template_base_url += _url.split(_name.split('.').shift())[0];
egw().debug("info", "Loaded data", _data);
var currentapp = this.app = _data.currentapp || egw().app_name();
var appname = _name.split('.')[0];
// if no app object provided and template app is not currentapp (eg. infolog CRM view)
// create private app object / closure with just classes / prototypes
if (!_app && appname && appname != currentapp && currentapp != 'home' && appname != 'home') app = { classes: window.app.classes };
// remember used app object, to eg. use: onchange="widget.getInstanceMgr().app_object[app].callback()"
this.app_obj = app;
// extract $content['msg'] and call egw.message() with it
var msg = _data.content.msg;
if (typeof msg != 'undefined')
{
egw(window).message(msg);
delete _data.content.msg;
}
// Register a handler for AJAX responses
egw(currentapp, window).registerJSONPlugin(etemplate2_handle_assign, this, 'assign');
if(egw.debug_level() >= 3)
{
if(console.groupCollapsed)
{
egw.window.console.groupCollapsed("Loading %s into ", _name, '#'+this.DOMContainer.id);
}
}
// Timing & profiling on debug level 'log' (4)
if(egw.debug_level() >= 4)
{
if(console.time)
{
console.time(_name);
}
if(console.profile)
{
console.profile(_name);
}
var start_time = (new Date).getTime();
}
// require necessary translations from server, if not already loaded
if (!jQuery.isArray(_data.langRequire)) _data.langRequire = [];
egw(currentapp, window).langRequire(window, _data.langRequire, function()
{
// Initialize application js
var app_callback = null;
// Only initialize once
// new app class with constructor function in app.classes[appname]
if (typeof app[appname] !== 'object' && typeof app.classes[appname] == 'function')
{
app[appname] = new app.classes[appname]();
}
// old app class with constructor function in app[appname] (deprecated)
else if(typeof app[appname] == "function")
{
(function() { new app[appname]();}).call();
}
else if (appname && typeof app[appname] !== "object")
{
egw.debug("warn", "Did not load '%s' JS object",appname);
}
// If etemplate current app does not match app owning the template,
// initialize the current app too
if (typeof app[this.app] !== 'object' && typeof app.classes[this.app] == 'function')
{
app[this.app] = new app.classes[this.app]();
}
if(typeof app[appname] == "object")
{
app_callback = function(_et2, _name) {
app[appname].et2_ready(_et2, _name);
};
}
// Clear any existing instance
this.clear();
// Create the basic widget container and attach it to the DOM
this.widgetContainer = new et2_container(null);
this.widgetContainer.setApiInstance(egw(currentapp, egw.elemWindow(this.DOMContainer)));
this.widgetContainer.setInstanceManager(this);
this.widgetContainer.setParentDOMNode(this.DOMContainer);
// store the id to submit it back to server
if(_data) {
this.etemplate_exec_id = _data.etemplate_exec_id;
// set app_header
if (typeof _data.app_header == 'string')
{
window.egw_app_header(_data.app_header);
}
// bind our unload handler
this.bind_unload();
}
var _load = function() {
egw.debug("log", "Loading template...");
if(egw.debug_level() >= 4 && console.timeStamp)
{
console.timeStamp("Begin rendering template");
}
// Add into indexed list - do this before, so anything looking can find it,
// even if it's not loaded
if(typeof etemplate2._byTemplate[_name] == "undefined")
{
etemplate2._byTemplate[_name] = [];
}
etemplate2._byTemplate[_name].push(this);
// Read the XML structure of the requested template
this.widgetContainer.loadFromXML(this.templates[this.name]);
// List of Promises from widgets that are not quite fully loaded
var deferred = [];
// Inform the widget tree that it has been successfully loaded.
this.widgetContainer.loadingFinished(deferred);
// Connect to the window resize event
jQuery(window).on("resize."+this.uniqueId, this, function(e) {e.data.resize(e);});
if(egw.debug_level() >= 3 && console.groupEnd)
{
egw.window.console.groupEnd();
}
if(deferred.length > 0)
{
var still_deferred = 0;
jQuery(deferred).each(function() {if(this.state() == "pending") still_deferred++;});
if(still_deferred > 0)
{
egw.debug("log", "Template loaded, waiting for %d/%d deferred to finish...",still_deferred, deferred.length);
}
}
// Wait for everything to be loaded, then finish it up
jQuery.when.apply(jQuery, deferred).done(jQuery.proxy(function() {
egw.debug("log", "Finished loading %s, triggering load event", _name);
if (typeof window.framework != 'undefined' && typeof window.framework.et2_loadingFinished != 'undefined')
{
//Call loading finished method of the framework with local window
window.framework.et2_loadingFinished(egw(window).window);
}
// Trigger the "resize" event
this.resize();
// Automatically set focus to first visible input for popups
if(this.widgetContainer._egw.is_popup() && jQuery('[autofocus]',this.DOMContainer).focus().length == 0)
{
var $input = jQuery('input:visible',this.DOMContainer)
// Date fields open the calendar popup on focus
.not('.et2_date')
.filter(function() {
// Skip inputs that are out of tab ordering
var $this = jQuery(this);
return !$this.attr('tabindex') || $this.attr('tabIndex')>=0;
}).first();
// mobile device, focus only if the field is empty (usually means new entry)
// should focus always for non-mobile one
if (egwIsMobile() && $input.val() == "" || !egwIsMobile()) $input.focus();
}
// Tell others about it
if(typeof _callback == "function")
{
_callback.call(window,this,_name);
}
if(app_callback && _callback != app_callback && !_no_et2_ready)
{
app_callback.call(window,this,_name);
}
if(appname && appname != this.app && typeof app[this.app] == "object" && !_no_et2_ready)
{
// Loaded a template from a different application?
// Let the application that loaded it know too
app[this.app].et2_ready(this, this.name);
}
jQuery(this.DOMContainer).trigger('load', this);
if(this.templates[this.name].attributes.onload)
{
var onload = et2_checkType(this.templates[this.name].attributes.onload.value,'js','onload');
if (typeof onload === 'string')
{
onload = et2_compileLegacyJS(onload, this, this.widgetContainer, this.widgetContainer);
}
onload.call(this.widgetContainer);
}
// Profiling
if(egw.debug_level() >= 4)
{
if(console.timeEnd)
{
console.timeEnd(_name);
}
if(console.profileEnd)
{
console.profileEnd(_name);
}
var end_time = (new Date).getTime();
var gen_time_div = jQuery('#divGenTime_'+appname);
if (!gen_time_div.length) gen_time_div = jQuery('.pageGenTime');
gen_time_div.find('.et2RenderTime').remove();
gen_time_div.append('<span class="et2RenderTime">'+egw.lang('eT2 rendering took %1s', (end_time-start_time)/1000)+'</span>');
}
},this));
};
// Load & process
try {
if (this.templates[_name])
{
// Set array managers first, or errors will happen
this.widgetContainer.setArrayMgrs(this._createArrayManagers(_data));
// Already have it
_load.apply(this,[]);
return;
}
}
catch (e) {
// wired security exception in IE denying access to template cache in opener
if (e.message == 'Permission denied')
{
etemplate2.prototype.templates = {};
}
// other error eg. in app.js et2_ready or event handlers --> rethrow it
else
{
throw e;
}
}
// Asynchronously load the XET file
et2_loadXMLFromURL(_url, function(_xmldoc) {
// Scan for templates and store them
for(var i = 0; i < _xmldoc.childNodes.length; i++) {
var template = _xmldoc.childNodes[i];
if(template.nodeName.toLowerCase() != "template") continue;
this.templates[template.getAttribute("id")] = template;
if(!_name) this.name = template.getAttribute("id");
}
_load.apply(this,[]);
}, this);
// Split the given data into array manager objects and pass those to the
// widget container - do this here because file is loaded async
this.widgetContainer.setArrayMgrs(this._createArrayManagers(_data));
}, this);
};
/**
* Check if template contains any dirty (unsaved) content
*
* @returns {Boolean}
*/
etemplate2.prototype.isDirty = function()
{
var dirty = false;
this.widgetContainer.iterateOver(function(_widget) {
if (_widget.isDirty && _widget.isDirty())
{
dirty = true;
}
});
return dirty;
};
/**
* Submit the et2_container form to a blank iframe in order to activate browser autocomplete
*/
etemplate2.prototype.autocomplete_fixer = function ()
{
var self = this;
var form = self.DOMContainer;
// Safari always do the autofill for password field regardless of autocomplete = off
// and since there's no other way to switch the autocomplete of, we should switch the
// form autocomplete off (e.g. compose dialog, attachment password field)
if (navigator.userAgent.match(/safari/i) && !navigator.userAgent.match(/chrome/i)
&& jQuery('input[type="password"]').length > 0)
{
return;
}
if (form)
{
// Stop submit propagation in order to not fire other possible submit events
form.onsubmit = function(e){e.stopPropagation();};
// Firefox give a security warning when transmitting to "about:blank" from a https site
// we work around that by giving existing etemplate/empty.html url
// Safari shows same warning, thought Chrome userAgent also includes Safari
if (navigator.userAgent.match(/(firefox|safari|iceweasel)/i) && !navigator.userAgent.match(/chrome/i))
{
jQuery(form).attr({action: egw.webserverUrl+'/api/templates/default/empty.html',method:'post'});
}
// need to trigger submit because submit() would not trigger onsubmit event
// since the submit does not get fired directly via user interaction.
jQuery(form).trigger('submit');
}
};
etemplate2.prototype._set_button = function (button, values)
{
if (typeof button == 'string')
{
button = this.widgetContainer.getWidgetById(button);
}
// Button parameter used for submit buttons in datagrid
// TODO: This should probably go in nextmatch's getValues(), along with selected rows somehow.
// I'm just not sure how.
if(button && !values.button)
{
values.button = {};
var path = button.getPath();
var target = values;
for(var i = 0; i < path.length; i++)
{
if(!values[path[i]]) values[path[i]] = {};
target = values[path[i]];
}
if(target != values || button.id.indexOf('[') != -1 && path.length == 0)
{
var indexes = button.id.split('[');
if (indexes.length > 1)
{
indexes = [indexes.shift(), indexes.join('[')];
indexes[1] = indexes[1].substring(0,indexes[1].length-1);
var children = indexes[1].split('][');
if(children.length)
{
indexes = jQuery.merge([indexes[0]], children);
}
}
var idx = '';
for(var i = 0; i < indexes.length; i++)
{
idx = indexes[i];
if(!target[idx] || target[idx]['$row_cont']) target[idx] = i < indexes.length -1 ? {} : true;
target = target[idx];
}
}
else if (typeof values.button == 'undefined' || jQuery.isEmptyObject(values.button))
{
delete values.button;
values[button.id] = true;
}
}
};
/**
* Submit form via ajax
*
* @param {(et2_button|string)} button button widget or string with id
* @param {boolean|string} async true: do an asynchronious submit, string: spinner message (please wait...)
* default is asynchronoush with message
* @param {boolean} no_validation - Do not do individual widget validation, just submit their current values
* @param {et2_widget|undefined} _container container to submit, default whole template
* @return {boolean} true if submit was send, false if eg. validation stoped submit
*/
etemplate2.prototype.submit = function(button, async, no_validation, _container)
{
var api = this.widgetContainer.egw();
if(typeof no_validation == 'undefined')
{
no_validation = false;
}
var container = _container || this.widgetContainer;
// Get the form values
var values = this.getValues(container);
// Trigger the submit event
var canSubmit = true;
if(!no_validation)
{
container.iterateOver(function(_widget) {
if (_widget.submit(values) === false)
{
canSubmit = false;
}
}, this, et2_ISubmitListener);
}
if (canSubmit)
{
if (typeof async == 'undefined' || typeof async == 'string')
{
api.loading_prompt('et2_submit_spinner', true, api.lang(typeof async == 'string' ? async : 'Please wait...'));
async = true;
}
if (button) this._set_button(button, values);
// Create the request object
if (this.menuaction)
{
//Autocomplete
this.autocomplete_fixer();
// unbind our session-destroy handler, as we are submitting
this.unbind_unload();
var request = api.json(this.menuaction, [this.etemplate_exec_id, values, no_validation], function(){
api.loading_prompt('et2_submit_spinner', false);
}, this, async);
request.sendRequest();
}
else
{
this.widgetContainer.egw().debug("warn", "Missing menuaction for submit. Values: ", values);
}
}
return canSubmit;
};
/**
* Does a full form post submit necessary for downloads
*
* Only use this one if you need it, use the ajax submit() instead.
* It ensures eT2 session continues to exist on server by unbinding unload handler and rebinding it.
*
* @param {(et2_button|string)} button button widget or string with id
*/
etemplate2.prototype.postSubmit = function(button)
{
// Get the form values
var values = this.getValues(this.widgetContainer);
// Trigger the submit event
var canSubmit = true;
this.widgetContainer.iterateOver(function(_widget) {
if (_widget.submit(values) === false)
{
canSubmit = false;
}
}, this, et2_ISubmitListener);
if (canSubmit)
{
if (button) this._set_button(button, values);
// unbind our session-destroy handler, as we are submitting
this.unbind_unload();
var form = jQuery("<form id='form' action='"+egw().webserverUrl +
"/index.php?menuaction=" + this.widgetContainer.egw().getAppName()+".EGroupware\\Api\\Etemplate.process_exec&ajax=true' method='POST'>");
var etemplate_id = jQuery(document.createElement("input"))
.attr("name",'etemplate_exec_id')
.attr("type",'hidden')
.val(this.etemplate_exec_id)
.appendTo(form);
var input = document.createElement("input");
input.type = "hidden";
input.name = 'value';
input.value = egw().jsonEncode(values);
form.append(input);
form.appendTo(jQuery('body')).submit();
// bind unload handler again (can NOT do it direct, as this would be quick enough to be still triggered!)
window.setTimeout(jQuery.proxy(this.bind_unload, this), 100);
}
};
/**
* Fetches all input element values and returns them in an associative
* array. Widgets which introduce namespacing can use the internal _target
* parameter to add another layer.
*
* @param {et2_widget} _root widget to start iterating
*/
etemplate2.prototype.getValues = function(_root)
{
var result = {};
// Iterate over the widget tree
_root.iterateOver(function(_widget) {
// The widget must have an id to be included in the values array
if (_widget.id == "")
{
return;
}
// Get the path to the node we have to store the value at
var path = _widget.getPath();
// check if id contains a hierachical name, eg. "button[save]"
var id = _widget.id;
var indexes = id.split('[');
if (indexes.length > 1)
{
indexes = [indexes.shift(), indexes.join('[')];
indexes[1] = indexes[1].substring(0,indexes[1].length-1);
var children = indexes[1].split('][');
if(children.length)
{
indexes = jQuery.merge([indexes[0]], children);
}
path = path.concat(indexes);
// Take the last one as the ID
id = path.pop();
}
// Set the _target variable to that node
var _target = result;
for (var i = 0; i < path.length; i++)
{
// Create a new object for not-existing path nodes
if (typeof _target[path[i]] === 'undefined')
{
_target[path[i]] = {};
}
// Check whether the path node is really an object
if (typeof _target[path[i]] === 'object')
{
_target = _target[path[i]];
}
else
{
egw.debug("error", "ID collision while writing at path " +
"node '" + path[i] + "'");
}
}
// Handle arrays, eg radio[]
if(id === "")
{
id = typeof _target == "undefined" ? 0 : Object.keys(_target).length;
}
var value = _widget.getValue();
// Check whether the entry is really undefined
if (typeof _target[id] != "undefined" && (typeof _target[id] != 'object' || typeof value != 'object'))
{
// Don't warn about children of nextmatch header - they're part of nm value
if(!_widget.getParent().instanceOf(et2_nextmatch_header_bar))
{
egw.debug("warn", _widget, "Overwriting value of '" + _widget.id +
"', id exists twice!");
}
}
// Store the value of the widget and reset its dirty flag
if (value !== null)
{
// Merge, if possible (link widget)
if(typeof _target[id] == 'object' && typeof value == 'object')
{
_target[id] = jQuery.extend({},_target[id],value);
}
else
{
_target[id] = value;
}
}
else if (jQuery.isEmptyObject(_target))
{
// Avoid sending back empty sub-arrays
_target = result;
for (var i = 0; i < path.length-1; i++)
{
_target = _target[path[i]];
}
delete _target[path[path.length-1]];
}
_widget.resetDirty();
}, this, et2_IInput);
egw().debug("info", "Value", result);
return result;
};
/**
* "Intelligently" refresh the template based on the given ID
*
* Rather than blindly re-load the entire template, we try to be a little smarter about it.
* If there's a message provided, we try to find where it goes and set it directly. Then
* we look for a nextmatch widget, and tell it to refresh its data based on that ID.
*
* @see egw_message.refresh()
*
* @param {string} msg message to try to display. eg: "Entry added" (not used anymore, handeled by egw_refresh and egw_message)
* @param {string} app app-name
* @param {(string|null)} id application specific entry ID to try to refresh
* @param {(string|null)} type type of change. One of 'update','edit', 'delete', 'add' or null
* @return {boolean} true if nextmatch found and refreshed, false if not
*/
etemplate2.prototype.refresh = function(msg, app, id, type)
{
msg, app; // unused but required by function signature
var refresh_done = false;
// Refresh nextmatches
this.widgetContainer.iterateOver(function(_widget) {
// Trigger refresh
_widget.refresh(id,type);
refresh_done = true;
}, this, et2_nextmatch);
return refresh_done;
};
/**
* "Intelligently" refresh a given app
*
* @see egw_message.refresh()
*
* @param {string} _msg message to try to display. eg: "Entry added" (not used anymore, handeled by egw_refresh and egw_message)
* @param {string} _app app-name
* @param {(string|null)} _id application specific entry ID to try to refresh
* @param {(string|null)} _type type of change. One of 'update','edit', 'delete', 'add' or null
* @return {boolean} true if nextmatch found and refreshed, false if not
*/
etemplate2.app_refresh = function(_msg, _app, _id, _type)
{
var refresh_done = false;
var et2 = etemplate2.getByApplication(_app);
for(var i = 0; i < et2.length; i++)
{
refresh_done = et2[i].refresh(_msg,_app,_id,_type) || refresh_done;
}