ee7b06dd4c99f25b4b89cd40bb748bade52c2bee
[tine20] / tine20 / Tinebase / js / widgets / dialog / EditDialog.js
1 /*
2  * Tine 2.0
3  * 
4  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
5  * @author      Cornelius Weiss <c.weiss@metaways.de>
6  * @copyright   Copyright (c) 2007-2013 Metaways Infosystems GmbH (http://www.metaways.de)
7  */
8 Ext.ns('Tine.widgets.dialog');
9
10 /**
11  * Generic 'Edit Record' dialog
12  * Base class for all 'Edit Record' dialogs
13  * 
14  * @namespace   Tine.widgets.dialog
15  * @class       Tine.widgets.dialog.EditDialog
16  * @extends     Ext.FormPanel
17  * @author      Cornelius Weiss <c.weiss@metaways.de>
18  * @constructor
19  * @param {Object} config The configuration options.
20  */
21
22 Tine.widgets.dialog.EditDialog = Ext.extend(Ext.FormPanel, {
23     /**
24      * @cfg {Tine.Tinebase.Application} app
25      * instance of the app object (required)
26      */
27     app: null,
28     /**
29      * @cfg {String} mode
30      * Set to 'local' if the EditDialog only operates on this.record (defaults to 'remote' which loads and saves using the recordProxy)
31      */
32     mode : 'remote',
33     /**
34      * @cfg {Array} tbarItems
35      * additional toolbar items (defaults to false)
36      */
37     tbarItems: false,
38     /**
39      * internal/untranslated app name (required)
40      * 
41      * @cfg {String} appName
42      */
43     appName: null,
44     /**
45      * the modelName (filled by application starter)
46      * 
47      * @type {String} modelName
48      */
49     modelName: null,
50     
51     /**
52      * record definition class  (required)
53      * 
54      * @cfg {Ext.data.Record} recordClass
55      */
56     recordClass: null,
57     /**
58      * @cfg {Ext.data.DataProxy} recordProxy
59      */
60     recordProxy: null,
61     /**
62      * @cfg {Bool} showContainerSelector
63      * show container selector in bottom area
64      */
65     showContainerSelector: null,
66     /**
67      * @cfg {Bool} evalGrants
68      * should grants of a grant-aware records be evaluated (defaults to true)
69      */
70     evalGrants: true,
71     /**
72      * @cfg {Ext.data.Record} record
73      * record in edit process.
74      */
75     record: null,
76     
77     /**
78      * holds the modelConfig for the handled record (json-encoded object)
79      * will be decoded in initComponent
80      * 
81      * @type 
82      */
83     modelConfig: null,
84     
85     /**
86      * @cfg {String} saveAndCloseButtonText
87      * text of save and close button
88      */
89     saveAndCloseButtonText: '',
90     /**
91      * @cfg {String} cancelButtonText
92      * text of cancel button
93      */
94     cancelButtonText: '',
95     
96     /**
97      * @cfg {Boolean} copyRecord
98      * copy record
99      */
100     copyRecord: false,
101     
102     /**
103      * @cfg {Boolean} doDuplicateCheck
104      * do duplicate check when saving record (mode remote only)
105      */
106     doDuplicateCheck: true,
107     
108     /**
109      * required grant for apply/save
110      * @type String
111      */
112     editGrant: 'editGrant',
113
114     /**
115      * when a record has the relations-property the relations-panel can be disabled here
116      * @cfg {Boolean} hideRelationsPanel
117      */
118     hideRelationsPanel: false,
119     
120     /**
121      * when a record has the attachments-property the attachments-panel can be disabled here
122      * @cfg {Boolean} hideAttachmentsPanel
123      */
124     hideAttachmentsPanel: false,
125     
126     /**
127      * Registry for other relationgridpanels than the generic one,
128      * handling special types of relations the generic one will not.
129      * Panels registered here must have a store with the relation records.
130      * 
131      * @type {Array}
132      */
133     relationPanelRegistry: null,
134     
135     /**
136      * ignore relations to given php-class names in the relation grid
137      * @type {Array}
138      */
139     ignoreRelatedModels: null,
140     
141     /**
142      * dialog is currently saving data
143      * @type Boolean
144      */
145     saving: false,
146     
147     /**
148      * Disable adding cf tab even if model has support for customfields
149      * @type Boolean
150      */
151     disableCfs: false,
152     
153     /**
154      * @property window {Ext.Window|Ext.ux.PopupWindow|Ext.Air.Window}
155      */
156     /**
157      * @property {Number} loadRequest 
158      * transaction id of loadData request
159      */
160     /**
161      * @property loadMask {Ext.LoadMask}
162      */
163     
164     /**
165      * @property containerSelectCombo {Tine.widgets.container.selectionComboBox}
166      */
167     containerSelectCombo: null,
168     
169     /**
170      * If set, these fields are readOnly (when called dependent to related record)
171      * 
172      * @type {Ext.util.MixedCollection}
173      */
174     fixedFields: null,
175
176     /**
177      * Plain Object with additional configuration (JSON-encoded)
178      * 
179      * @type {Object}
180      */
181     additionalConfig: null,
182     
183     // private
184     bodyStyle:'padding:5px',
185     layout: 'fit',
186     border: false,
187     cls: 'tw-editdialog',
188     anchor:'100% 100%',
189     deferredRender: false,
190     buttonAlign: null,
191     bufferResize: 500,
192
193     /**
194      * relations panel
195      * 
196      * @type Tine.widgets.relation.GenericPickerGridPanel
197      */
198     relationsPanel: null,
199     
200     // Array of Relation Pickers
201     relationPickers: null,
202     
203     /**
204      * attachments panel
205      * 
206      * @type Tine.widgets.dialog.AttachmentsGridPanel
207      */
208     attachmentsPanel: null,
209     
210     /**
211      * holds the loadMask
212      * set this to false, if no loadMask should be shown
213      * 
214      * @type {Ext.LoadMask}
215      */
216     loadMask: null,
217
218     /**
219      * hook notes panel into dialog
220      */
221     displayNotes: false,
222
223     //private
224     initComponent: function() {
225         this.relationPanelRegistry = this.relationPanelRegistry ? this.relationPanelRegistry : [];
226         this.addEvents(
227             /**
228              * @event cancel
229              * Fired when user pressed cancel button
230              */
231             'cancel',
232             /**
233              * @event saveAndClose
234              * Fired when user pressed OK button
235              */
236             'saveAndClose',
237             /**
238              * @event update
239              * @desc  Fired when the record got updated
240              * @param {Json String} data data of the entry
241              * @pram  {String} this.mode
242              */
243             'update',
244             /**
245              * @event apply
246              * Fired when user pressed apply button
247              */
248             'apply',
249             /**
250              * @event load
251              * @param {Tine.widgets.dialog.EditDialog} this
252              * @param {Tine.data.Record} record which got loaded
253              * @param {Function} ticket function for async defer
254              * Fired when record is loaded
255              */
256             'load',
257             /**
258              * @event save
259              * @param {Tine.widgets.dialog.EditDialog} this
260              * @param {Tine.data.Record} record which got loaded
261              * @param {Function} ticket function for async defer
262              * Fired when remote record is saving
263              */
264             'save',
265             /**
266              * @event updateDependent
267              * Fired when a subpanel updates the record locally
268              */
269             'updateDependent'
270         );
271
272         if (Ext.isString(this.modelConfig)) {
273             this.modelConfig = Ext.decode(this.modelConfig);
274         }
275         
276         if (Ext.isString(this.additionalConfig)) {
277             Ext.apply(this, Ext.decode(this.additionalConfig));
278         }
279         
280         if (Ext.isString(this.fixedFields)) {
281             var decoded = Ext.decode(this.fixedFields);
282             this.fixedFields = new Ext.util.MixedCollection();
283             this.fixedFields.addAll(decoded);
284         }
285         
286         if (! this.recordClass && this.modelName) {
287             this.recordClass = Tine[this.appName].Model[this.modelName];
288         }
289         
290         if (this.recordClass) {
291             this.appName    = this.appName    ? this.appName    : this.recordClass.getMeta('appName');
292             this.modelName  = this.modelName  ? this.modelName  : this.recordClass.getMeta('modelName');
293         }
294         
295         if (! this.app) {
296             this.app = Tine.Tinebase.appMgr.get(this.appName);
297         }
298         
299         if (! this.windowNamePrefix) {
300             this.windowNamePrefix = this.modelName + 'EditWindow_';
301         }
302         
303         Tine.log.debug('initComponent: appName: ', this.appName);
304         Tine.log.debug('initComponent: modelName: ', this.modelName);
305         Tine.log.debug('initComponent: app: ', this.app);
306         
307         // init some translations
308         if (this.app.i18n && this.recordClass !== null) {
309             this.i18nRecordName = this.app.i18n.n_hidden(this.recordClass.getMeta('recordName'), this.recordClass.getMeta('recordsName'), 1);
310             this.i18nRecordsName = this.app.i18n._hidden(this.recordClass.getMeta('recordsName'));
311         }
312     
313         if (! this.recordProxy && this.recordClass) {
314             Tine.log.debug('no record proxy given, creating a new one...');
315             this.recordProxy = new Tine.Tinebase.data.RecordProxy({
316                 recordClass: this.recordClass
317             });
318         }
319         // init plugins
320         this.plugins = Ext.isString(this.plugins) ? Ext.decode(this.plugins) : Ext.isArray(this.plugins) ? this.plugins.concat(Ext.decode(this.initialConfig.plugins)) : [];
321         
322         this.plugins.push(this.tokenModePlugin = new Tine.widgets.dialog.TokenModeEditDialogPlugin({}));
323         // added possibility to disable using customfield plugin
324         if (this.disableCfs !== true) {
325             this.plugins.push(new Tine.widgets.customfields.EditDialogPlugin({}));
326         }
327         
328         // init actions
329         this.initActions();
330         // init buttons and tbar
331         this.initButtons();
332         // init container selector
333         this.initContainerSelector();
334         // init record 
335         this.initRecord();
336         // get items for this dialog
337         this.items = this.getFormItems();
338
339         // init relations panel if relations are defined
340         this.initRelationsPanel();
341         // init attachments panel
342         this.initAttachmentsPanel();
343         // init notes panel
344         this.initNotesPanel();
345
346         Tine.widgets.dialog.EditDialog.superclass.initComponent.call(this);
347         
348         // set fields readOnly if set
349         this.fixFields();
350         
351         // firefox fix: blur each item before tab changes, so no field  will be focused afterwards
352         if (Ext.isGecko) {
353             this.items.items[0].addListener('beforetabchange', function(tabpanel, newtab, oldtab) {
354                 if (! oldtab) {
355                     return;
356                 }
357                 var form = this.getForm();
358                 
359                 if (form && form.hasOwnProperty('items'))
360                     form.items.each(function(item, index) {
361                         item.blur();
362                     });
363             }, this);
364         }
365     },
366
367     /**
368      * generic form layout
369      */
370     getFormItems: function() {
371         return {
372             xtype: 'tabpanel',
373             border: false,
374             plain:true,
375             activeTab: 0,
376             border: false,
377             defaults: {
378                 hideMode: 'offsets'
379             },
380             plugins: [{
381                 ptype : 'ux.tabpanelkeyplugin'
382             }],
383             items:[
384                 {
385                     title: this.i18nRecordName,
386                     autoScroll: true,
387                     border: false,
388                     frame: true,
389                     layout: 'border',
390                     items: [Ext.applyIf(this.getRecordFormItems(), {
391                         region: 'center',
392                         xtype: 'columnform',
393                         labelAlign: 'top',
394                         formDefaults: {
395                             xtype:'textfield',
396                             anchor: '100%',
397                             labelSeparator: '',
398                             columnWidth: 1/2
399                         },
400                     })].concat(this.getEastPanel())
401                 }, new Tine.widgets.activities.ActivitiesTabPanel({
402                     app: this.appName,
403                     record_id: this.record.id,
404                     record_model: this.modelName
405                 })
406             ]
407         };
408     },
409
410     getEastPanel: function() {
411         var items = [];
412         if (this.recordClass.hasField('description')) {
413             items.push(new Ext.Panel({
414                 title: i18n._('Description'),
415                 iconCls: 'descriptionIcon',
416                 layout: 'form',
417                 labelAlign: 'top',
418                 border: false,
419                 items: [{
420                     style: 'margin-top: -4px; border 0px;',
421                     labelSeparator: '',
422                     xtype: 'textarea',
423                     name: 'description',
424                     hideLabel: true,
425                     grow: false,
426                     preventScrollbars: false,
427                     anchor: '100% 100%',
428                     emptyText: i18n._('Enter description'),
429                     requiredGrant: 'editGrant'
430                 }]
431             }));
432         }
433
434         if (this.recordClass.hasField('tags')) {
435             items.push(new Tine.widgets.tags.TagPanel({
436                 app: this.appName,
437                 border: false,
438                 bodyStyle: 'border:1px solid #B5B8C8;'
439             }));
440         }
441
442         return items.length ? {
443             layout: 'accordion',
444             animate: true,
445             region: 'east',
446             width: 210,
447             split: true,
448             collapsible: true,
449             collapseMode: 'mini',
450             header: false,
451             margins: '0 5 0 5',
452             border: true,
453             items: items
454         } : [];
455     },
456
457     getRecordFormItems: function() {
458         return new Tine.widgets.form.RecordForm({
459             recordClass: this.recordClass
460         });
461     },
462
463     /**
464      * fix fields (used for preselecting form fields when called in dependency to another record)
465      * @return {Boolean}
466      */
467     fixFields: function() {
468         if (this.fixedFields && this.fixedFields.getCount() > 0) {
469             if (! this.rendered) {
470                 this.fixFields.defer(100, this);
471                 return false;
472             }
473             
474             this.fixedFields.each(function(value, index) {
475                 var key = this.fixedFields.keys[index]; 
476                 
477                 var field = this.getForm().findField(key);
478                 
479                 if (field) {
480                     if (Ext.isFunction(this.recordClass.getField(key).type)) {
481                         var foreignRecordClass = this.recordClass.getField(key).type;
482                         var record = new foreignRecordClass(value);
483                         field.selectedRecord = record;
484                         field.setValue(value);
485                         field.fireEvent('select');
486                     } else {
487                         field.setValue(value);
488                     }
489                     field.disable();
490                 }
491             }, this);
492         }
493     },
494
495     /**
496      * Get available model for given application
497      *
498      *  @param {Mixed} application
499      *  @param {Boolean} customFieldModel
500      */
501     getApplicationModels: function (application, customFieldModel) {
502         var models      = [],
503             useModel,
504             appName     = Ext.isString(application) ? application : application.get('name'),
505             app         = Tine.Tinebase.appMgr.get(appName),
506             trans       = app && app.i18n ? app.i18n : i18n,
507             appModels   = Tine[appName].Model;
508
509         if (appModels) {
510             for (var model in appModels) {
511                 if (appModels.hasOwnProperty(model) && typeof appModels[model].getMeta === 'function') {
512                     if (customFieldModel && appModels[model].getField('customfields')) {
513                         useModel = appModels[model].getMeta('appName') + '_Model_' + appModels[model].getMeta('modelName');
514
515                         Tine.log.info('Found model with customfields property: ' + useModel);
516                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
517                     } else if (! customFieldModel) {
518                         useModel = 'Tine.' + appModels[model].getMeta('appName') + '.Model.' + appModels[model].getMeta('modelName');
519
520                         Tine.log.info('Found model: ' + useModel);
521                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
522                     }
523                 }
524             }
525         }
526         return models;
527     },
528
529     /**
530      * init actions
531      */
532     initActions: function() {
533         this.action_saveAndClose = new Ext.Action({
534             requiredGrant: this.editGrant,
535             text: (this.saveAndCloseButtonText != '') ? this.app.i18n._(this.saveAndCloseButtonText) : i18n._('Ok'),
536             minWidth: 70,
537             ref: '../btnSaveAndClose',
538             scope: this,
539             // TODO: remove the defer when all subpanels use the deferByTicket mechanism
540             handler: function() { this.onSaveAndClose.defer(500, this); },
541             iconCls: 'action_saveAndClose'
542         });
543     
544         this.action_applyChanges = new Ext.Action({
545             requiredGrant: this.editGrant,
546             text: i18n._('Apply'),
547             minWidth: 70,
548             ref: '../btnApplyChanges',
549             scope: this,
550             handler: this.onApplyChanges,
551             iconCls: 'action_applyChanges'
552         });
553         
554         this.action_cancel = new Ext.Action({
555             text: (this.cancelButtonText != '') ? this.app.i18n._(this.cancelButtonText) : i18n._('Cancel'),
556             minWidth: 70,
557             scope: this,
558             handler: this.onCancel,
559             iconCls: 'action_cancel'
560         });
561         
562         this.action_delete = new Ext.Action({
563             requiredGrant: 'deleteGrant',
564             text: i18n._('delete'),
565             minWidth: 70,
566             scope: this,
567             handler: this.onDelete,
568             iconCls: 'action_delete',
569             disabled: true
570         });
571     },
572     
573     /**
574      * init buttons
575      * 
576      * use button order from preference
577      */
578     initButtons: function () {
579         this.fbar = [
580             '->'
581         ];
582         
583         if (Tine.Tinebase.registry && Tine.Tinebase.registry.get('preferences') && Tine.Tinebase.registry.get('preferences').get('dialogButtonsOrderStyle') === 'Windows') {
584             this.fbar.push(this.action_saveAndClose, this.action_cancel);
585         } else {
586             this.fbar.push(this.action_cancel, this.action_saveAndClose);
587         }
588        
589         if (this.tbarItems) {
590             this.tbar = new Ext.Toolbar({
591                 items: this.tbarItems
592             });
593         }
594     },
595     
596     /**
597      * init container selector
598      */
599     initContainerSelector: function() {
600         if (this.showContainerSelector) {
601             this.containerSelectCombo = new Tine.widgets.container.selectionComboBox({
602                 id: this.app.appName + 'EditDialogContainerSelector-' + Ext.id(),
603                 fieldLabel: i18n._('Saved in'),
604                 width: 300,
605                 listWidth: 300,
606                 name: this.recordClass.getMeta('containerProperty'),
607                 recordClass: this.recordClass,
608                 containerName: this.app.i18n.n_hidden(this.recordClass.getMeta('containerName'), this.recordClass.getMeta('containersName'), 1),
609                 containersName: this.app.i18n._hidden(this.recordClass.getMeta('containersName')),
610                 appName: this.app.appName,
611                 requiredGrant: this.evalGrants ? 'addGrant' : false,
612                 disabled: this.isContainerSelectorDisabled(),
613                 listeners: {
614                     scope: this,
615                     select: function() {    
616                         // enable or disable save button dependent to containers account grants
617                         // on edit: check editGrant, on add: check addGrant
618                         var grants = this.containerSelectCombo.selectedContainer
619                             ? this.containerSelectCombo.selectedContainer.account_grants : {},
620                             grantToCheck = (this.record.data.id) ? 'editGrant' : 'addGrant',
621                             enabled =  grants.hasOwnProperty(grantToCheck) && grants[grantToCheck]
622                                     || grants.hasOwnProperty('adminGrant') && grants.adminGrant ? true : false;
623
624                         this.action_saveAndClose.setDisabled(! enabled);
625                     }
626                 }
627             });
628             this.on('render', function() { this.getForm().add(this.containerSelectCombo); }, this);
629             
630             this.fbar = [
631                 i18n._('Saved in'),
632                 this.containerSelectCombo
633             ].concat(this.fbar);
634         }
635         
636     },
637     
638     /**
639      * checks if the container selector should be disabled (dependent on account grants of the container itself)
640      * @return {}
641      */
642     isContainerSelectorDisabled: function() {
643         if (this.record) {
644             var cp = this.recordClass.getMeta('containerProperty'),
645                 container = this.record.data[cp],
646                 grants = (container && container.hasOwnProperty('account_grants')) ? container.account_grants : null,
647                 cond = false;
648                 
649             // check grants if record already exists and grants should be evaluated
650             if(this.evalGrants && this.record.data.id && grants) {
651                 cond = ! (grants.hasOwnProperty('editGrant') && grants.editGrant);
652             }
653             
654             return cond;
655         } else {
656             return false;
657         }
658     },
659     
660     /**
661      * init record to edit
662      */
663     initRecord: function() {
664         Tine.log.debug('init record with mode: ' + this.mode);
665         if (! this.record) {
666             Tine.log.debug('creating new default data record');
667             this.record = new this.recordClass(this.recordClass.getDefaultData(), 0);
668         }
669         
670         if (this.mode !== 'local') {
671             if (this.record && this.record.id) {
672                 this.loadRemoteRecord();
673             } else {
674                 this.onRecordLoad();
675             }
676         } else {
677             // note: in local mode we expect a valid record
678             if (! Ext.isFunction(this.record.beginEdit)) {
679                 this.record = this.recordProxy.recordReader({responseText: this.record});
680             }
681             this.onRecordLoad();
682         }
683     },
684     
685     /**
686      * load record via record proxy
687      */
688     loadRemoteRecord: function() {
689         Tine.log.info('initiating record load via proxy');
690         this.loadRequest = this.recordProxy.loadRecord(this.record, {
691             scope: this,
692             success: function(record) {
693                 this.record = record;
694                 this.onRecordLoad();
695             }
696         });
697     },
698
699     /**
700      * copy this.record record
701      */
702     doCopyRecord: function() {
703         this.record = this.doCopyRecordToReturn(this.record);
704     },
705
706     /**
707      * Copy record and returns "new record with same settings"
708      *
709      * @param record
710      */
711     doCopyRecordToReturn: function(record) {
712         var omitFields = this.recordClass.getMeta('copyOmitFields') || [];
713         // always omit id + notes + attachments
714         omitFields = omitFields.concat(['id', 'notes', 'attachments', 'relations']);
715
716         var fieldsToCopy = this.recordClass.getFieldNames().diff(omitFields),
717             recordData = Ext.copyTo({}, record.data, fieldsToCopy);
718
719         var resetProperties = {
720             alarms:    ['id', 'record_id', 'sent_time', 'sent_message'],
721             relations: ['id', 'own_id', 'created_by', 'creation_time', 'last_modified_by', 'last_modified_time']
722         };
723
724         var setProperties = {alarms: {sent_status: 'pending'}};
725
726         Ext.iterate(resetProperties, function(property, properties) {
727             if (recordData.hasOwnProperty(property)) {
728                 var r = recordData[property];
729                 for (var index = 0; index < r.length; index++) {
730                     Ext.each(properties,
731                         function(prop) {
732                             r[index][prop] = null;
733                         }
734                     );
735                 }
736             }
737         });
738
739         Ext.iterate(setProperties, function(property, properties) {
740             if (recordData.hasOwnProperty(property)) {
741                 var r = recordData[property];
742                 for (var index = 0; index < r.length; index++) {
743                     Ext.iterate(properties,
744                         function(prop, value) {
745                             r[index][prop] = value;
746                         }
747                     );
748                 }
749             }
750         });
751
752         return new this.recordClass(recordData, 0);
753     },
754
755     
756     /**
757      * executed after record got updated from proxy
758      */
759     onRecordLoad: function() {
760         // interrupt process flow until dialog is rendered
761         if (! this.rendered) {
762             this.onRecordLoad.defer(250, this);
763             return;
764         }
765         Tine.log.debug('Tine.widgets.dialog.EditDialog::onRecordLoad() - Loading of the following record completed:');
766         Tine.log.debug(this.record);
767         
768         if (this.copyRecord) {
769             this.doCopyRecord();
770             this.window.setTitle(String.format(i18n._('Copy {0}'), this.i18nRecordName));
771         } else {
772             if (! this.record.id) {
773                 this.window.setTitle(String.format(i18n._('Add New {0}'), this.i18nRecordName));
774             } else {
775                 this.window.setTitle(String.format(i18n._('Edit {0} "{1}"'), this.i18nRecordName, this.record.getTitle()));
776             }
777         }
778         
779         var ticketFn = this.onAfterRecordLoad.deferByTickets(this),
780             wrapTicket = ticketFn();
781         
782         this.fireEvent('load', this, this.record, ticketFn);
783         wrapTicket();
784     },
785     
786     // finally load the record into the form
787     onAfterRecordLoad: function() {
788         var form = this.getForm();
789         
790         if (form) {
791             form.loadRecord(this.record);
792             form.clearInvalid();
793         }
794         
795         if (this.record && this.record.hasOwnProperty('data') && Ext.isObject(this.record.data[this.recordClass.getMeta('containerProperty')])) {
796             this.updateToolbars(this.record, this.recordClass.getMeta('containerProperty'));
797         }
798         
799         // add current timestamp as id, if this is a dependent record 
800         if (this.modelConfig && this.modelConfig.isDependent == true && this.record.id == 0) {
801             this.record.set('id', (new Date()).getTime());
802         }
803         
804         if (this.loadMask) {
805             this.loadMask.hide();
806         }
807     },
808     
809     /**
810      * executed when record gets updated from form
811      */
812     onRecordUpdate: function() {
813         var form = this.getForm();
814
815         // merge changes from form into record
816         form.updateRecord(this.record);
817     },
818     
819     /**
820      * @private
821      */
822     onRender : function(ct, position){
823         Tine.widgets.dialog.EditDialog.superclass.onRender.call(this, ct, position);
824         
825         // generalized keybord map for edit dlgs
826         new Ext.KeyMap(this.el, [
827             {
828                 key: [10,13], // ctrl + return
829                 ctrl: true,
830                 scope: this,
831                 fn: function() {
832                     if (this.getForm().hasOwnProperty('items')) {
833                         // force set last selected field
834                         this.getForm().items.each(function(item) {
835                             if (item.hasFocus) {
836                                 item.setValue(item.getRawValue());
837                             }
838                         }, this);
839                     }
840                     this.action_saveAndClose.execute();
841                 }
842             }
843         ]);
844         
845         if (this.loadMask !== false && this.i18nRecordName) {
846             this.loadMask = new Ext.LoadMask(ct, {msg: String.format(i18n._('Transferring {0}...'), this.i18nRecordName)});
847             this.loadMask.show();
848         }
849     },
850     
851     /**
852      * update (action updateer) top and bottom toolbars
853      */
854     updateToolbars: function(record, containerField) {
855         if (! this.evalGrants) {
856             return;
857         }
858         
859         var actions = [
860             this.action_saveAndClose,
861             this.action_applyChanges,
862             this.action_delete,
863             this.action_cancel
864         ];
865         Tine.widgets.actionUpdater(record, actions, containerField);
866         Tine.widgets.actionUpdater(record, this.tbarItems, containerField);
867     },
868     
869     /**
870      * get top toolbar
871      */
872     getToolbar: function() {
873         return this.getTopToolbar();
874     },
875     
876     /**
877      * is form valid?
878      * 
879      * @return {Boolean}
880      */
881     isValid: function() {
882         var me = this;
883         return new Promise(function (fulfill, reject) {
884             if (me.getForm().isValid()) {
885                 fulfill(true);
886             } else {
887                 reject(me.getValidationErrorMessage())
888             }
889         });
890     },
891
892     /**
893      * vaidates on multiple edit
894      * 
895      * @return {Boolean}
896      */
897     isMultipleValid: function() {
898         return true;
899     },
900     
901     /**
902      * @private
903      */
904     onCancel : function(){
905         this.fireEvent('cancel');
906         this.purgeListeners();
907         this.window.close();
908     },
909     
910     /**
911      * @private
912      */
913     onSaveAndClose: function() {
914         this.fireEvent('saveAndClose');
915         this.onApplyChanges(true);
916     },
917     
918     /**
919      * generic apply changes handler
920      * @param {Boolean} closeWindow
921      */
922     onApplyChanges: function(closeWindow) {
923         if (this.saving) {
924             return;
925         }
926         this.saving = true;
927
928         this.loadMask.show();
929
930         var ticketFn = this.doApplyChanges.deferByTickets(this, [closeWindow]),
931             wrapTicket = ticketFn();
932
933         this.fireEvent('save', this, this.record, ticketFn);
934         wrapTicket();
935     },
936     
937     /**
938      * is called from onApplyChanges
939      * @param {Boolean} closeWindow
940      */
941     doApplyChanges: function(closeWindow) {
942         // we need to sync record before validating to let (sub) panels have 
943         // current data of other panels
944         this.onRecordUpdate();
945         
946         // quit copy mode
947         this.copyRecord = false;
948
949         var isValid = this.isValid(),
950             vBool = !! isValid,
951             me = this;
952
953         if (Ext.isDefined(isValid) && ! Ext.isFunction(isValid.then)) {
954             // convert legacy isValid into promise
955             isValid = new Promise(function (fulfill, reject) {;
956                 return vBool ? fulfill(true) : reject(me.getValidationErrorMessage());
957             });
958         }
959
960         isValid.then(function () {
961             if (me.mode !== 'local') {
962                 me.recordProxy.saveRecord(me.record, {
963                     scope: me,
964                     success: function (record) {
965                         // override record with returned data
966                         me.record = record;
967                         if (!Ext.isFunction(me.window.cascade)) {
968                             // update form with this new data
969                             // NOTE: We update the form also when window should be closed,
970                             //       cause sometimes security restrictions might prevent
971                             //       closing of native windows
972                             me.onRecordLoad();
973                         }
974                         var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
975                             wrapTicket = ticketFn();
976
977                         me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
978                         wrapTicket();
979                     },
980                     failure: me.onRequestFailed,
981                     timeout: 300000 // 5 minutes
982                 }, me.getAdditionalSaveParams(me));
983             } else {
984                 me.onRecordLoad();
985                 var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
986                     wrapTicket = ticketFn();
987
988                 me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
989                 wrapTicket();
990             }
991         }, function (message) {
992             me.saving = false;
993             me.loadMask.hide();
994             Ext.MessageBox.alert(i18n._('Errors'), message);
995         });
996     },
997
998     /**
999      * returns additional save params
1000      *
1001      * @param {EditDialog} me
1002      * @returns {{duplicateCheck: boolean}}
1003      */
1004     getAdditionalSaveParams: function(me) {
1005         return {
1006             duplicateCheck: me.doDuplicateCheck
1007         };
1008     },
1009     
1010     onAfterApplyChanges: function(closeWindow) {
1011         this.window.rename(this.windowNamePrefix + this.record.id);
1012         this.loadMask.hide();
1013         this.saving = false;
1014         
1015         if (closeWindow) {
1016             this.window.fireEvent('saveAndClose');
1017             this.purgeListeners();
1018             this.window.close();
1019         }
1020     },
1021     
1022     /**
1023      * get validation error message
1024      * 
1025      * @return {String}
1026      */
1027     getValidationErrorMessage: function() {
1028         return i18n._('Please fix the errors noted.');
1029     },
1030     
1031     /**
1032      * generic delete handler
1033      */
1034     onDelete: function(btn, e) {
1035         Ext.MessageBox.confirm(i18n._('Confirm'), String.format(i18n._('Do you really want to delete this {0}?'), this.i18nRecordName), function(_button) {
1036             if(btn == 'yes') {
1037                 var deleteMask = new Ext.LoadMask(this.getEl(), {msg: String.format(i18n._('Deleting {0}'), this.i18nRecordName)});
1038                 deleteMask.show();
1039                 
1040                 this.recordProxy.deleteRecords(this.record, {
1041                     scope: this,
1042                     success: function() {
1043                         this.purgeListeners();
1044                         this.window.close();
1045                     },
1046                     failure: function () {
1047                         Ext.MessageBox.alert(i18n._('Failed'), String.format(i18n._('Could not delete {0}.'), this.i18nRecordName));
1048                         Ext.MessageBox.hide();
1049                     }
1050                 });
1051             }
1052         });
1053     },
1054     
1055     /**
1056      * duplicate(s) found exception handler
1057      * 
1058      * @param {Object} exception
1059      */
1060     onDuplicateException: function(exception) {
1061         var resolveGridPanel = new Tine.widgets.dialog.DuplicateResolveGridPanel({
1062             app: this.app,
1063             store: new Tine.widgets.dialog.DuplicateResolveStore({
1064                 app: this.app,
1065                 recordClass: this.recordClass,
1066                 recordProxy: this.recordProxy,
1067                 data: {
1068                     clientRecord: exception.clientRecord,
1069                     duplicates: exception.duplicates
1070                 }
1071             }),
1072             fbar: [
1073                 '->',
1074                 this.action_cancel,
1075                 this.action_saveAndClose
1076             ]
1077         });
1078         
1079         // intercept save handler
1080         resolveGridPanel.btnSaveAndClose.setHandler(function(btn, e) {
1081             var resolveStrategy = resolveGridPanel.store.resolveStrategy;
1082             
1083             // action discard -> close window
1084             if (resolveStrategy == 'discard') {
1085                 return this.onCancel();
1086             }
1087             
1088             this.record = resolveGridPanel.store.getResolvedRecord();
1089             
1090             // quit copy mode before populating form with resolved data
1091             this.copyRecord = false;
1092             this.onRecordLoad();
1093             
1094             mainCardPanel.layout.setActiveItem(this.id);
1095             resolveGridPanel.doLayout();
1096             
1097             this.doDuplicateCheck = false;
1098             this.onSaveAndClose();
1099         }, this);
1100         
1101         // place in viewport
1102         this.window.setTitle(String.format(i18n._('Resolve Duplicate {0} Suspicion'), this.i18nRecordName));
1103         var mainCardPanel = this.findParentBy(function(p) {return p.isWindowMainCardPanel });
1104         mainCardPanel.add(resolveGridPanel);
1105         mainCardPanel.layout.setActiveItem(resolveGridPanel.id);
1106         resolveGridPanel.doLayout();
1107     },
1108     
1109     /**
1110      * generic request exception handler
1111      * 
1112      * @param {Object} exception
1113      */
1114     onRequestFailed: function(exception) {
1115         this.saving = false;
1116
1117         if (this.exceptionHandlingMap && this.exceptionHandlingMap[exception.code] && typeof this.exceptionHandlingMap[exception.code] === 'function') {
1118             this.exceptionHandlingMap[exception.code](exception);
1119
1120         } else if (exception.code == 629) {
1121             this.onDuplicateException.apply(this, arguments);
1122
1123         } else {
1124             Tine.Tinebase.ExceptionHandler.handleRequestException(exception);
1125         }
1126
1127         this.loadMask.hide();
1128     },
1129     
1130     /**
1131      * creates the relations panel, if relations are defined
1132      */
1133     initRelationsPanel: function() {
1134         if (! this.hideRelationsPanel && this.recordClass && this.recordClass.hasField('relations')) {
1135             // init relations panel before onRecordLoad
1136             if (! this.relationsPanel) {
1137                 this.relationsPanel = new Tine.widgets.relation.GenericPickerGridPanel({ anchor: '100% 100%', editDialog: this });
1138             }
1139             // interrupt process flow until dialog is rendered
1140             if (! this.rendered) {
1141                 this.initRelationsPanel.defer(250, this);
1142                 return;
1143             }
1144             // add relations panel if this is rendered
1145             if (this.items.items[0]) {
1146                 this.items.items[0].add(this.relationsPanel);
1147             }
1148             
1149             Tine.log.debug('Tine.widgets.dialog.EditDialog::initRelationsPanel() - Initialized relations panel and added to dialog tab items.');
1150         }
1151     },
1152
1153     /**
1154      * create notes panel
1155      */
1156     initNotesPanel: function() {
1157         // This dialog is pretty generic but for some cases it's used in a differend way
1158         if(this.displayNotes == true) {
1159             this.items.items.push(new Tine.widgets.activities.ActivitiesGridPanel({
1160                 anchor: '100% 100%',
1161                 editDialog: this
1162             }));
1163         }
1164     },
1165
1166     /**
1167      * creates attachments panel
1168      */
1169     initAttachmentsPanel: function() {
1170         if (! this.attachmentsPanel && ! this.hideAttachmentsPanel && this.recordClass && this.recordClass.hasField('attachments') && Tine.Tinebase.registry.get('filesystemAvailable')) {
1171             this.attachmentsPanel = new Tine.widgets.dialog.AttachmentsGridPanel({ anchor: '100% 100%', editDialog: this }); 
1172             this.items.items.push(this.attachmentsPanel);
1173         }
1174     }
1175 });