-
Notifications
You must be signed in to change notification settings - Fork 23.1k
/
relational_fields.js
3475 lines (3272 loc) · 117 KB
/
relational_fields.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
odoo.define('web.relational_fields', function (require) {
"use strict";
/**
* Relational Fields
*
* In this file, we have a collection of various relational field widgets.
* Relational field widgets are more difficult to use/manipulate, because the
* relations add a level of complexity: a value is not a basic type, it can be
* a collection of other records.
*
* Also, the way relational fields are edited is more complex. We can change
* the corresponding record(s), or alter some of their fields.
*/
var AbstractField = require('web.AbstractField');
var basicFields = require('web.basic_fields');
var concurrency = require('web.concurrency');
const ControlPanelX2Many = require('web.ControlPanelX2Many');
var core = require('web.core');
var data = require('web.data');
var Dialog = require('web.Dialog');
var dialogs = require('web.view_dialogs');
var dom = require('web.dom');
const Domain = require('web.Domain');
var KanbanRecord = require('web.KanbanRecord');
var KanbanRenderer = require('web.KanbanRenderer');
var ListRenderer = require('web.ListRenderer');
const { ComponentWrapper, WidgetAdapterMixin } = require('web.OwlCompatibility');
const { sprintf } = require("web.utils");
const { escape } = owl.utils;
var _t = core._t;
var _lt = core._lt;
var qweb = core.qweb;
//------------------------------------------------------------------------------
// Many2one widgets
//------------------------------------------------------------------------------
var M2ODialog = Dialog.extend({
template: "M2ODialog",
init: function (parent, name, value) {
this.name = name;
this.value = value;
this._super(parent, {
title: _.str.sprintf(_t("New %s"), this.name),
size: 'medium',
buttons: [{
text: _t('Create'),
classes: 'btn-primary',
close: true,
click: function () {
this.trigger_up('quick_create', { value: this.value });
},
}, {
text: _t('Create and edit'),
classes: 'btn-primary',
close: true,
click: function () {
this.trigger_up('search_create_popup', {
view_type: 'form',
value: this.value,
});
},
}, {
text: _t('Cancel'),
close: true,
}],
});
},
/**
* @override
* @param {boolean} isSet
*/
close: function (isSet) {
this.isSet = isSet;
this._super.apply(this, arguments);
},
/**
* @override
*/
destroy: function () {
if (!this.isSet) {
this.trigger_up('closed_unset');
}
this._super.apply(this, arguments);
},
});
var FieldMany2One = AbstractField.extend({
description: _lt("Many2one"),
supportedFieldTypes: ['many2one'],
template: 'FieldMany2One',
custom_events: _.extend({}, AbstractField.prototype.custom_events, {
'closed_unset': '_onDialogClosedUnset',
'field_changed': '_onFieldChanged',
'quick_create': '_onQuickCreate',
'search_create_popup': '_onSearchCreatePopup',
}),
events: _.extend({}, AbstractField.prototype.events, {
'click input': '_onInputClick',
'focusout input': '_onInputFocusout',
'keyup input': '_onInputKeyup',
'click .o_external_button': '_onExternalButtonClick',
'click': '_onClick',
}),
AUTOCOMPLETE_DELAY: 200,
SEARCH_MORE_LIMIT: 320,
/**
* @override
* @param {boolean} [options.noOpen=false] if true, there is no external
* button to open the related record in a dialog
* @param {boolean} [options.noCreate=false] if true, the many2one does not
* allow to create records
*/
init: function (parent, name, record, options) {
options = options || {};
this._super.apply(this, arguments);
this.limit = 7;
this.orderer = new concurrency.DropMisordered();
// should normally be set, except in standalone M20
const canCreate = 'can_create' in this.attrs ? JSON.parse(this.attrs.can_create) : true;
this.can_create = canCreate && !this.nodeOptions.no_create && !options.noCreate;
this.can_write = 'can_write' in this.attrs ? JSON.parse(this.attrs.can_write) : true;
this.nodeOptions = _.defaults(this.nodeOptions, {
quick_create: true,
});
this.noOpen = 'noOpen' in options ? options.noOpen : this.nodeOptions.no_open;
this.m2o_value = this._formatValue(this.value);
// 'recordParams' is a dict of params used when calling functions
// 'getDomain' and 'getContext' on this.record
this.recordParams = {fieldName: this.name, viewType: this.viewType};
// We need to know if the widget is dirty (i.e. if the user has changed
// the value, and those changes haven't been acknowledged yet by the
// environment), to prevent erasing that new value on a reset (e.g.
// coming by an onchange on another field)
this.isDirty = false;
this.lastChangeEvent = undefined;
// List of autocomplete sources
this._autocompleteSources = [];
// Add default search method for M20 (name_search)
this._addAutocompleteSource(this._search, {placeholder: _t('Loading...'), order: 1});
// use a DropPrevious to properly handle related record quick creations,
// and store a createDef to be able to notify the environment that there
// is pending quick create operation
this.dp = new concurrency.DropPrevious();
this.createDef = undefined;
},
start: function () {
// booleean indicating that the content of the input isn't synchronized
// with the current m2o value (for instance, the user is currently
// typing something in the input, and hasn't selected a value yet).
this.floating = false;
this.$input = this.$('input');
this.$external_button = this.$('.o_external_button');
return this._super.apply(this, arguments);
},
/**
* @override
*/
destroy: function () {
if (this._onScroll) {
window.removeEventListener('scroll', this._onScroll, true);
}
this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Override to make the caller wait for potential ongoing record creation.
* This ensures that the correct many2one value is set when the main record
* is saved.
*
* @override
* @returns {Promise} resolved as soon as there is no longer record being
* (quick) created
*/
commitChanges: function () {
return Promise.resolve(this.createDef);
},
/**
* @override
* @returns {jQuery}
*/
getFocusableElement: function () {
return this.mode === 'edit' && this.$input || this.$el;
},
/**
* TODO
*/
reinitialize: function (value) {
this.isDirty = false;
this.floating = false;
return this._setValue(value);
},
/**
* Re-renders the widget if it isn't dirty. The widget is dirty if the user
* changed the value, and that change hasn't been acknowledged yet by the
* environment. For example, another field with an onchange has been updated
* and this field is updated before the onchange returns. Two '_setValue'
* are done (this is sequential), the first one returns and this widget is
* reset. However, it has pending changes, so we don't re-render.
*
* @override
*/
reset: function (record, event) {
this._reset(record, event);
if (!event || event === this.lastChangeEvent) {
this.isDirty = false;
}
if (this.isDirty) {
return Promise.resolve();
} else {
return this._render();
}
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Add a source to the autocomplete results
*
* @param {function} method : A function that returns a list of results. If async source, the function should return a promise
* @param {Object} params : Parameters containing placeholder/validation/order
* @private
*/
_addAutocompleteSource: function (method, params) {
this._autocompleteSources.push({
method: method,
placeholder: (params.placeholder ? _t(params.placeholder) : _t('Loading...')) + '<i class="fa fa-spinner fa-spin pull-right"></i>' ,
validation: params.validation,
loading: false,
order: params.order || 999
});
this._autocompleteSources = _.sortBy(this._autocompleteSources, 'order');
},
/**
* @private
*/
_bindAutoComplete: function () {
var self = this;
// avoid ignoring autocomplete="off" by obfuscating placeholder, see #30439
if ($.browser.chrome && this.$input.attr('placeholder')) {
this.$input.attr('placeholder', function (index, val) {
return val.split('').join('\ufeff');
});
}
this.$input.autocomplete({
source: function (req, resp) {
_.each(self._autocompleteSources, function (source) {
// Resets the results for this source
source.results = [];
// Check if this source should be used for the searched term
const search = req.term.trim();
if (!source.validation || source.validation.call(self, search)) {
source.loading = true;
// Wrap the returned value of the source.method with a promise
// So event if the returned value is not async, it will work
Promise.resolve(source.method.call(self, search)).then(function (results) {
source.results = results;
source.loading = false;
resp(self._concatenateAutocompleteResults());
});
}
});
},
select: function (event, ui) {
// we do not want the select event to trigger any additional
// effect, such as navigating to another field.
event.stopImmediatePropagation();
event.preventDefault();
var item = ui.item;
self.floating = false;
if (item.id) {
self.reinitialize({id: item.id, display_name: item.name});
} else if (item.action) {
item.action();
}
return false;
},
focus: function (event) {
event.preventDefault(); // don't automatically select values on focus
},
open: function (event) {
self._onScroll = function (ev) {
if (ev.target !== self.$input.get(0) && self.$input.hasClass('ui-autocomplete-input')) {
self.$input.autocomplete('close');
}
};
window.addEventListener('scroll', self._onScroll, true);
},
close: function (event) {
// it is necessary to prevent ESC key from propagating to field
// root, to prevent unwanted discard operations.
if (event.which === $.ui.keyCode.ESCAPE) {
event.stopPropagation();
}
if (self._onScroll) {
window.removeEventListener('scroll', self._onScroll, true);
}
},
autoFocus: true,
html: true,
minLength: 0,
delay: this.AUTOCOMPLETE_DELAY,
});
this.$input.autocomplete("option", "position", { my : "left top", at: "left bottom" });
this.autocomplete_bound = true;
},
/**
* Concatenate async results for autocomplete.
*
* @returns {Array}
* @private
*/
_concatenateAutocompleteResults: function () {
var results = [];
_.each(this._autocompleteSources, function (source) {
if (source.results && source.results.length) {
results = results.concat(source.results);
} else if (source.loading) {
results.push({
label: source.placeholder
});
}
});
return results;
},
/**
* @private
* @param {string} [name]
* @returns {Object}
*/
_createContext: function (name) {
var tmp = {};
var field = this.nodeOptions.create_name_field;
if (field === undefined) {
field = "name";
}
if (field !== false && name && this.nodeOptions.quick_create !== false) {
tmp["default_" + field] = name;
}
return tmp;
},
/**
* @private
* @returns {Array}
*/
_getSearchBlacklist: function () {
return [];
},
/**
* Returns the display_name from a string which contains it but was altered
* as a result of the show_address option using a horrible hack.
*
* @private
* @param {string} value
* @returns {string} display_name without show_address mess
*/
_getDisplayName: function (value) {
return value.split('\n')[0];
},
/**
* Prepares and returns options for SelectCreateDialog
*
* @private
*/
_getSearchCreatePopupOptions: function(view, ids, context, dynamicFilters) {
var self = this;
return {
res_model: this.field.relation,
domain: this.record.getDomain({fieldName: this.name}),
context: _.extend({}, this.record.getContext(this.recordParams), context || {}),
_createContext: this._createContext.bind(this),
dynamicFilters: dynamicFilters || [],
title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + this.string,
initial_ids: ids,
initial_view: view,
disable_multiple_selection: true,
no_create: !self.can_create,
kanban_view_ref: this.attrs.kanban_view_ref,
on_selected: function (records) {
self.reinitialize(records[0]);
},
on_closed: function () {
self.activate();
},
};
},
/**
* @private
* @param {Object} values
* @param {string} search_val
* @param {Object} domain
* @param {Object} context
* @returns {Object}
*/
_manageSearchMore: function (values, search_val, domain, context) {
var self = this;
values = values.slice(0, this.limit);
values.push({
label: _t("Search More..."),
action: function () {
var prom;
if (search_val !== '') {
prom = self._rpc({
model: self.field.relation,
method: 'name_search',
kwargs: {
name: search_val,
args: domain,
operator: "ilike",
limit: self.SEARCH_MORE_LIMIT,
context: context,
},
});
}
Promise.resolve(prom).then(function (results) {
var dynamicFilters;
if (results) {
var ids = _.map(results, function (x) {
return x[0];
});
dynamicFilters = [{
description: _.str.sprintf(_t('Quick search: %s'), search_val),
domain: [['id', 'in', ids]],
}];
}
self._searchCreatePopup("search", false, {}, dynamicFilters);
});
},
classname: 'o_m2o_dropdown_option',
});
return values;
},
/**
* Listens to events 'field_changed' to keep track of the last event that
* has been trigerred. This allows to detect that all changes have been
* acknowledged by the environment.
*
* @param {OdooEvent} event 'field_changed' event
*/
_onFieldChanged: function (event) {
this.lastChangeEvent = event;
},
/**
* @private
* @param {string} name
* @returns {Promise} resolved after the name_create or when the slowcreate
* modal is closed.
*/
_quickCreate: function (name) {
var self = this;
var createDone;
var def = new Promise(function (resolve, reject) {
self.createDef = new Promise(function (innerResolve) {
// called when the record has been quick created, or when the dialog has
// been closed (in the case of a 'slow' create), meaning that the job is
// done
createDone = function () {
innerResolve();
resolve();
self.createDef = undefined;
};
});
// called if the quick create is disabled on this many2one, or if the
// quick creation failed (probably because there are mandatory fields on
// the model)
var slowCreate = function () {
var dialog = self._searchCreatePopup("form", false, self._createContext(name));
dialog.on('closed', self, createDone);
};
if (self.nodeOptions.quick_create) {
const prom = self.reinitialize({id: false, display_name: name});
prom.guardedCatch(reason => {
reason.event.preventDefault();
slowCreate();
});
self.dp.add(prom).then(createDone).guardedCatch(reject);
} else {
slowCreate();
}
});
return def;
},
/**
* @private
*/
_renderEdit: function () {
var value = this.m2o_value;
// this is a stupid hack necessary to support the always_reload flag.
// the field value has been reread by the basic model. We use it to
// display the full address of a partner, separated by \n. This is
// really a bad way to do it. Now, we need to remove the extra lines
// and hope for the best that no one tries to uses this mechanism to do
// something else.
if (this.nodeOptions.always_reload) {
value = this._getDisplayName(value);
}
this.$input.val(value);
if (!this.autocomplete_bound) {
this._bindAutoComplete();
}
this._updateExternalButton();
},
/**
* @private
*/
_renderReadonly: function () {
var escapedValue = _.escape((this.m2o_value || "").trim());
var value = escapedValue.split('\n').map(function (line) {
return '<span>' + line + '</span>';
}).join('<br/>');
this.$el.html(value);
if (!this.noOpen && this.value) {
this.$el.attr('href', _.str.sprintf('#id=%s&model=%s', this.value.res_id, this.field.relation));
this.$el.addClass('o_form_uri');
}
},
/**
* @private
*/
_reset: function () {
this._super.apply(this, arguments);
this.floating = false;
this.m2o_value = this._formatValue(this.value);
},
/**
* Executes a 'name_search' and returns a list of formatted objects meant to
* be displayed in the autocomplete widget dropdown. These items are either:
* - a formatted version of a 'name_search' result
* - an option meant to display additional information or perform an action
*
* @private
* @param {string} [searchValue=""]
* @returns {Promise<{
* label: string,
* id?: number,
* name?: string,
* value?: string,
* classname?: string,
* action?: () => Promise<any>,
* }[]>}
*/
_search: async function (searchValue = "") {
const value = searchValue.trim();
const domain = this.record.getDomain(this.recordParams);
const context = Object.assign(
this.record.getContext(this.recordParams),
this.additionalContext
);
// Exclude black-listed ids from the domain
const blackListedIds = this._getSearchBlacklist();
if (blackListedIds.length) {
domain.push(['id', 'not in', blackListedIds]);
}
if (this.lastNameSearch) {
this.lastNameSearch.catch((reason) => {
// the last rpc name_search will be aborted, so we want to ignore its rejection
reason.event.preventDefault();
})
this.lastNameSearch.abort(false)
}
this.lastNameSearch = this._rpc({
model: this.field.relation,
method: "name_search",
kwargs: {
name: value,
args: domain,
operator: "ilike",
limit: this.limit + 1,
context,
}
});
const results = await this.orderer.add(this.lastNameSearch);
// Format results to fit the options dropdown
let values = results.map((result) => {
const [id, fullName] = result;
const displayName = this._getDisplayName(fullName).trim();
result[1] = displayName;
return {
id,
label: escape(displayName) || data.noDisplayContent,
value: displayName,
name: displayName,
};
});
// Add "Search more..." option if results count is higher than the limit
if (this.limit < values.length) {
values = this._manageSearchMore(values, value, domain, context);
}
if (!this.can_create) {
return values;
}
// Additional options...
const canQuickCreate = !this.nodeOptions.no_quick_create;
const canCreateEdit = !this.nodeOptions.no_create_edit;
if (value.length) {
// "Quick create" option
const nameExists = results.some((result) => result[1] === value);
if (canQuickCreate && !nameExists) {
values.push({
label: sprintf(
_t(`Create "<strong>%s</strong>"`),
escape(value)
),
action: () => this._quickCreate(value),
classname: 'o_m2o_dropdown_option'
});
}
// "Create and Edit" option
if (canCreateEdit) {
const valueContext = this._createContext(value);
values.push({
label: _t("Create and Edit..."),
action: () => {
// Input value is cleared and the form popup opens
this.el.querySelector(':scope input').value = "";
return this._searchCreatePopup('form', false, valueContext);
},
classname: 'o_m2o_dropdown_option',
});
}
// "No results" option
if (!values.length) {
values.push({
label: _t("No results to show..."),
});
}
} else if (!this.value && (canQuickCreate || canCreateEdit)) {
// "Start typing" option
values.push({
label: _t("Start typing..."),
classname: 'o_m2o_start_typing',
});
}
return values;
},
/**
* all search/create popup handling
*
* TODO: ids argument is no longer used, remove it in master (as well as
* initial_ids param of the dialog)
*
* @private
* @param {any} view
* @param {any} ids
* @param {any} context
* @param {Object[]} [dynamicFilters=[]] filters to add to the search view
* in the dialog (each filter has keys 'description' and 'domain')
*/
_searchCreatePopup: function (view, ids, context, dynamicFilters) {
var options = this._getSearchCreatePopupOptions(view, ids, context, dynamicFilters);
return new dialogs.SelectCreateDialog(this, _.extend({}, this.nodeOptions, options)).open();
},
/**
* @private
*/
_updateExternalButton: function () {
var has_external_button = !this.noOpen && !this.floating && this.isSet();
this.$external_button.toggle(has_external_button);
this.$el.toggleClass('o_with_button', has_external_button); // Should not be required anymore but kept for compatibility
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
* @param {MouseEvent} event
*/
_onClick: function (event) {
var self = this;
if (this.mode === 'readonly' && !this.noOpen) {
event.preventDefault();
event.stopPropagation();
this._rpc({
model: this.field.relation,
method: 'get_formview_action',
args: [[this.value.res_id]],
context: this.record.getContext(this.recordParams),
})
.then(function (action) {
self.trigger_up('do_action', {action: action});
});
}
},
/**
* Reset the input as dialog has been closed without m2o creation.
*
* @private
*/
_onDialogClosedUnset: function () {
this.isDirty = false;
this.floating = false;
this._render();
},
/**
* @private
*/
_onExternalButtonClick: function () {
if (!this.value) {
this.activate();
return;
}
var self = this;
var context = this.record.getContext(this.recordParams);
this._rpc({
model: this.field.relation,
method: 'get_formview_id',
args: [[this.value.res_id]],
context: context,
})
.then(function (view_id) {
new dialogs.FormViewDialog(self, {
res_model: self.field.relation,
res_id: self.value.res_id,
context: context,
title: _t("Open: ") + self.string,
view_id: view_id,
readonly: !self.can_write,
on_saved: function (record, changed) {
if (changed) {
const _setValue = self._setValue.bind(self, self.value.data, {
forceChange: true,
});
self.trigger_up('reload', {
db_id: self.value.id,
onSuccess: _setValue,
onFailure: _setValue,
});
}
},
}).open();
});
},
/**
* @private
*/
_onInputClick: function () {
if (this.$input.autocomplete("widget").is(":visible")) {
this.$input.autocomplete("close");
} else if (this.floating) {
this.$input.autocomplete("search"); // search with the input's content
} else {
this.$input.autocomplete("search", ''); // search with the empty string
}
},
/**
* @private
*/
_onInputFocusout: function () {
if (this.can_create && this.floating) {
new M2ODialog(this, this.string, this.$input.val()).open();
}
},
/**
* @private
*
* @param {OdooEvent} ev
*/
_onInputKeyup: function (ev) {
if (ev.which === $.ui.keyCode.ENTER || ev.which === $.ui.keyCode.TAB) {
// If we pressed enter or tab, we want to prevent _onInputFocusout from
// executing since it would open a M2O dialog to request
// confirmation that the many2one is not properly set.
// It's a case that is already handled by the autocomplete lib.
return;
}
this.isDirty = true;
if (this.$input.val() === "") {
this.reinitialize(false);
} else if (this._getDisplayName(this.m2o_value) !== this.$input.val()) {
this.floating = true;
this._updateExternalButton();
}
},
/**
* @override
* @private
*/
_onKeydown: function () {
this.floating = false;
this._super.apply(this, arguments);
},
/**
* Stops the left/right navigation move event if the cursor is not at the
* start/end of the input element. Stops any navigation move event if the
* user is selecting text.
*
* @private
* @param {OdooEvent} ev
*/
_onNavigationMove: function (ev) {
// TODO Maybe this should be done in a mixin or, better, the m2o field
// should be an InputField (but this requires some refactoring).
basicFields.InputField.prototype._onNavigationMove.apply(this, arguments);
if (this.mode === 'edit' && $(this.$input.autocomplete('widget')).is(':visible')) {
ev.stopPropagation();
}
},
/**
* @private
* @param {OdooEvent} event
*/
_onQuickCreate: function (event) {
this._quickCreate(event.data.value);
},
/**
* @private
* @param {OdooEvent} event
*/
_onSearchCreatePopup: function (event) {
var data = event.data;
this._searchCreatePopup(data.view_type, false, this._createContext(data.value));
},
});
var Many2oneBarcode = FieldMany2One.extend({
// We don't require this widget to be displayed in studio sidebar in
// non-debug mode hence just extended it from its original widget, so that
// description comes from parent and hasOwnProperty based condition fails
});
var ListFieldMany2One = FieldMany2One.extend({
events: _.extend({}, FieldMany2One.prototype.events, {
'focusin input': '_onInputFocusin',
}),
/**
* Should never be allowed to be opened while in readonly mode in a list
*
* @override
*/
init: function () {
this._super.apply(this, arguments);
// when we empty the input, we delay the setValue to prevent from
// triggering the 'fieldChanged' event twice when the user wants set
// another m2o value ; the following attribute is used to determine when
// we skipped the setValue, s.t. we can perform it later on if the user
// didn't select another value
this.mustSetValue = false;
this.m2oDialogFocused = false;
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* If in readonly, will never be considered as an active widget.
*
* @override
*/
activate: function () {
if (this.mode === 'readonly') {
return false;
}
return this._super.apply(this, arguments);
},
/**
* @override
*/
reinitialize: function () {
this.mustSetValue = false;
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
*/
_renderReadonly: function () {
this.$el.text(this.m2o_value);
},
/**
* @override
* @private
*/
_searchCreatePopup: function () {
this.m2oDialogFocused = true;
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
*/
_onInputFocusin: function () {
this.m2oDialogFocused = false;
},
/**
* In case the focus is lost from a mousedown, we want to prevent the click occuring on the
* following mouseup since it might trigger some unwanted list functions.
* If it's not the case, we want to remove the added handler on the next mousedown.
* @see list_editable_renderer._onWindowClicked()
*
* Also, in list views, we don't want to try to trigger a fieldChange when the field
* is being emptied. Instead, it will be triggered as the user leaves the field
* while it is empty.
*
* @override
* @private
*/
_onInputFocusout: function () {
if (this.can_create && this.floating) {
// In case the focus out is due to a mousedown, we want to prevent the next click
var attachedEvents = ['click', 'mousedown'];
var stopNextClick = (function (ev) {
ev.stopPropagation();
attachedEvents.forEach(function (eventName) {
window.removeEventListener(eventName, stopNextClick, true);
});
}).bind(this);
attachedEvents.forEach(function (eventName) {
window.addEventListener(eventName, stopNextClick, true);
});
}
this._super.apply(this, arguments);
if (!this.m2oDialogFocused && this.$input.val() === "" && this.mustSetValue) {
this.reinitialize(false);
}
},
/**
* Prevents the triggering of an immediate _onFieldChanged when emptying the field.
*
* @override
* @private
*/
_onInputKeyup: function () {
if (this.$input.val() !== "") {
this._super.apply(this, arguments);
} else {
this.mustSetValue = true;
}
},
});
var KanbanFieldMany2One = AbstractField.extend({
tagName: 'span',
init: function () {
this._super.apply(this, arguments);
this.m2o_value = this._formatValue(this.value);
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
*/
_render: function () {
this.$el.text(this.m2o_value);
},
});
/**
* Widget Many2OneAvatar is only supported on many2one fields pointing to a
* model which inherits from 'image.mixin'. In readonly, it displays the
* record's image next to the display_name. In edit, it behaves exactly like a
* regular many2one widget.
*/
const Many2OneAvatar = FieldMany2One.extend({
_template: 'web.Many2OneAvatar',