1 openerp.web.form = function (openerp) {
3 var _t = openerp.web._t,
5 var QWeb = openerp.web.qweb;
7 openerp.web.views.add('form', 'openerp.web.FormView');
8 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
10 * Indicates that this view is not searchable, and thus that no search
11 * view should be displayed (if there is one active).
15 form_template: "FormView",
16 display_name: _lt('Form'),
18 * @constructs openerp.web.FormView
19 * @extends openerp.web.View
21 * @param {openerp.web.Session} session the current openerp session
22 * @param {openerp.web.DataSet} dataset the dataset this view will work with
23 * @param {String} view_id the identifier of the OpenERP view object
24 * @param {Object} options
25 * - sidebar : [true|false]
26 * - resize_textareas : [true|false|max_height]
28 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
30 init: function(parent, dataset, view_id, options) {
32 this.set_default_options(options);
33 this.dataset = dataset;
34 this.model = dataset.model;
35 this.view_id = view_id || false;
36 this.fields_view = {};
38 this.widgets_counter = 0;
40 this.fields_order = [];
42 this.default_focus_field = null;
43 this.default_focus_button = null;
44 this.registry = openerp.web.form.widgets;
45 this.has_been_loaded = $.Deferred();
46 this.$form_header = null;
47 this.translatable_fields = [];
48 _.defaults(this.options, {
49 "not_interactible_on_create": false
51 this.is_initialized = $.Deferred();
52 this.mutating_mutex = new $.Mutex();
53 this.on_change_mutex = new $.Mutex();
54 this.reload_mutex = new $.Mutex();
58 return this.init_view();
60 init_view: function() {
61 if (this.embedded_view) {
62 var def = $.Deferred().then(this.on_loaded);
64 $.async_when().then(function() {def.resolve(self.embedded_view);});
67 var context = new openerp.web.CompoundContext(this.dataset.get_context());
68 return this.rpc("/web/view/load", {
70 "view_id": this.view_id,
72 toolbar: this.options.sidebar,
79 this.sidebar.attachments.stop();
82 _.each(this.widgets, function(w) {
87 reposition: function ($e) {
91 on_loaded: function(data) {
94 throw "No data provided.";
96 if (this.root_frame) {
97 throw "Form view does not support multiple calls to on_loaded";
99 this.fields_order = [];
100 this.fields_view = data;
102 this.rendered = QWeb.render(this.form_template, {'widget': this});
103 this.$element.html(this.rendered);
105 this.root_frame = instanciate_widget(this.registry.get_object('frame'), this, this.fields_view.arch);
106 var to_append = $(".oe_form_header", this.$element);
107 this.root_frame.appendTo(to_append.length > 0 ? to_append : this.$element);
108 this.root_frame.$element.children().unwrap();
110 this.$form_header = this.$element.find('.oe_form_header:first');
111 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
112 var action = $(this).data('pager-action');
113 self.on_pager_action(action);
116 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
117 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
119 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
120 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
121 this.sidebar.start();
122 this.sidebar.do_unfold();
123 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
124 this.sidebar.add_toolbar(this.fields_view.toolbar);
125 this.set_common_sidebar_sections(this.sidebar);
127 this.sidebar.add_section(_t('Customize'), 'customize');
128 this.sidebar.add_items('customize', [{
129 label: _t('Set Default'),
131 callback: function (item) {
132 item.form.open_defaults_dialog();
136 this.has_been_loaded.resolve();
139 do_load_state: function(state, warm) {
140 if (state.id && this.datarecord.id != state.id) {
141 if (!this.dataset.get_id_index(state.id)) {
142 this.dataset.ids.push(state.id);
144 this.dataset.select_id(state.id);
151 do_show: function () {
153 this.$element.show().css('visibility', 'hidden');
154 this.$element.removeClass('oe_form_dirty');
155 return this.has_been_loaded.pipe(function() {
157 if (self.dataset.index === null) {
158 // null index means we should start a new record
159 result = self.on_button_new();
161 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
162 context : { 'bin_size' : true }
163 }).pipe(self.on_record_loaded);
165 result.pipe(function() {
166 self.$element.css('visibility', 'visible');
169 self.sidebar.$element.show();
174 do_hide: function () {
177 this.sidebar.$element.hide();
180 on_record_loaded: function(record) {
181 var self = this, set_values = [];
183 this.do_warn("Form", "The record could not be found in the database.", true);
184 return $.Deferred().reject();
186 this.datarecord = record;
188 _(this.fields).each(function (field, f) {
190 var result = field.set_value(self.datarecord[f] || false);
191 set_values.push(result);
192 $.when(result).then(function() {
196 return $.when.apply(null, set_values).pipe(function() {
198 // New record: Second pass in order to trigger the onchanges
199 // respecting the fields order defined in the view
200 _.each(self.fields_order, function(field_name) {
201 if (record[field_name] !== undefined) {
202 var field = self.fields[field_name];
204 self.do_onchange(field);
208 self.on_form_changed();
209 self.is_initialized.resolve();
210 self.do_update_pager(record.id == null);
212 self.sidebar.attachments.do_update();
214 if (self.default_focus_field && !self.embedded_view) {
215 self.default_focus_field.focus();
218 self.do_push_state({id:record.id});
220 self.$element.removeClass('oe_form_dirty');
223 on_form_changed: function() {
224 for (var w in this.widgets) {
226 w.process_modifiers();
233 do_notify_change: function() {
234 this.$element.addClass('oe_form_dirty');
236 on_pager_action: function(action) {
237 if (this.can_be_discarded()) {
240 this.dataset.index = 0;
243 this.dataset.previous();
249 this.dataset.index = this.dataset.ids.length - 1;
255 do_update_pager: function(hide_index) {
256 var $pager = this.$form_header.find('div.oe_form_pager');
257 var index = hide_index ? '-' : this.dataset.index + 1;
258 $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
259 $pager.find('span.oe_pager_index').html(index);
260 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
262 parse_on_change: function (on_change, widget) {
264 var onchange = _.str.trim(on_change);
265 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
270 var method = call[1];
271 if (!_.str.trim(call[2])) {
272 return {method: method, args: [], context_index: null}
275 var argument_replacement = {
276 'False': function () {return false;},
277 'True': function () {return true;},
278 'None': function () {return null;},
279 'context': function (i) {
281 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
285 var parent_fields = null, context_index = null;
286 var args = _.map(call[2].split(','), function (a, i) {
287 var field = _.str.trim(a);
289 // literal constant or context
290 if (field in argument_replacement) {
291 return argument_replacement[field](i);
294 if (/^-?\d+(\.\d+)?$/.test(field)) {
295 return Number(field);
298 if (self.fields[field]) {
299 var value = self.fields[field].get_on_change_value();
300 return value == null ? false : value;
303 var splitted = field.split('.');
304 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
305 if (parent_fields === null) {
306 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
308 var p_val = parent_fields[_.str.trim(splitted[1])];
309 if (p_val !== undefined) {
310 return p_val == null ? false : p_val;
314 var first_char = field[0], last_char = field[field.length-1];
315 if ((first_char === '"' && last_char === '"')
316 || (first_char === "'" && last_char === "'")) {
317 return field.slice(1, -1);
320 throw new Error("Could not get field with name '" + field +
321 "' for onchange '" + onchange + "'");
327 context_index: context_index
330 do_onchange: function(widget, processed) {
332 return this.on_change_mutex.exec(function() {
334 var response = {}, can_process_onchange = $.Deferred();
335 processed = processed || [];
336 processed.push(widget.name);
337 var on_change = widget.node.attrs.on_change;
339 var change_spec = self.parse_on_change(on_change, widget);
342 url: '/web/dataset/onchange',
345 can_process_onchange = self.rpc(ajax, {
346 model: self.dataset.model,
347 method: change_spec.method,
348 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
349 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
350 }).then(function(r) {
351 _.extend(response, r);
354 console.warn("Wrong on_change format", on_change);
357 // fail if onchange failed
358 if (can_process_onchange.isRejected()) {
359 return can_process_onchange;
362 if (widget.field['change_default']) {
363 var fieldname = widget.name, value;
364 if (response.value && (fieldname in response.value)) {
365 // Use value from onchange if onchange executed
366 value = response.value[fieldname];
368 // otherwise get form value for field
369 value = self.fields[fieldname].get_on_change_value();
371 var condition = fieldname + '=' + value;
374 can_process_onchange = self.rpc({
375 url: '/web/dataset/call',
379 method: 'get_defaults',
380 args: [self.model, condition]
381 }).then(function (results) {
382 if (!results.length) { return; }
383 if (!response.value) {
386 for(var i=0; i<results.length; ++i) {
387 // [whatever, key, value]
388 var triplet = results[i];
389 response.value[triplet[1]] = triplet[2];
394 if (can_process_onchange.isRejected()) {
395 return can_process_onchange;
398 return self.on_processed_onchange(response, processed);
401 return $.Deferred().reject();
405 on_processed_onchange: function(response, processed) {
407 var result = response;
409 for (var f in result.value) {
410 if (!result.value.hasOwnProperty(f)) { continue; }
411 var field = this.fields[f];
412 // If field is not defined in the view, just ignore it
414 var value = result.value[f];
415 if (field.get_value() != value) {
416 field.set_value(value);
418 if (!_.contains(processed, field.name)) {
419 this.do_onchange(field, processed);
424 this.on_form_changed();
426 if (!_.isEmpty(result.warning)) {
427 openerp.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
430 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
435 function edit_domain(node) {
436 var new_domain = result.domain[node.attrs.name];
438 node.attrs.domain = new_domain;
440 _(node.children).each(edit_domain);
442 edit_domain(this.fields_view.arch);
444 return $.Deferred().resolve();
447 return $.Deferred().reject();
450 on_button_save: function() {
452 return this.do_save().then(function(result) {
453 self.do_prev_view({'created': result.created, 'default': 'page'});
456 on_button_cancel: function() {
457 if (this.can_be_discarded()) {
458 return this.do_prev_view({'default': 'page'});
461 on_button_new: function() {
463 var def = $.Deferred();
464 $.when(this.has_been_loaded).then(function() {
465 if (self.can_be_discarded()) {
466 var keys = _.keys(self.fields_view.fields);
468 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
472 self.on_record_loaded({}).then(function() {
478 return def.promise();
480 can_be_discarded: function() {
481 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
484 * Triggers saving the form's record. Chooses between creating a new
485 * record or saving an existing one depending on whether the record
486 * already has an id property.
488 * @param {Function} success callback on save success
489 * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
491 do_save: function(success, prepend_on_create) {
493 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
495 var form_invalid = false,
497 first_invalid_field = null;
498 for (var f in self.fields) {
503 if (!first_invalid_field) {
504 first_invalid_field = f;
506 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
507 // Special case 'id' field, do not save this field
508 // on 'create' : save all non readonly fields
509 // on 'edit' : save non readonly modified fields
510 values[f.name] = f.get_value();
514 first_invalid_field.focus();
516 return $.Deferred().reject();
519 if (!self.datarecord.id) {
520 //console.log("FormView(", self, ") : About to create", values);
521 save_deferral = self.dataset.create(values).pipe(function(r) {
522 return self.on_created(r, undefined, prepend_on_create);
524 } else if (_.isEmpty(values)) {
525 //console.log("FormView(", self, ") : Nothing to save");
526 save_deferral = $.Deferred().resolve({}).promise();
528 //console.log("FormView(", self, ") : About to save", values);
529 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
530 return self.on_saved(r);
533 return save_deferral.then(success);
537 return $.Deferred().reject();
541 on_invalid: function() {
543 _.each(this.fields, function(f) {
545 msg += "<li>" + f.string + "</li>";
549 this.do_warn("The following fields are invalid :", msg);
551 on_saved: function(r, success) {
553 // should not happen in the server, but may happen for internal purpose
554 return $.Deferred().reject();
556 return $.when(this.reload()).pipe(function () {
557 return $.when(r).then(success); }, null);
561 * Updates the form' dataset to contain the new record:
563 * * Adds the newly created record to the current dataset (at the end by
565 * * Selects that record (sets the dataset's index to point to the new
567 * * Updates the pager and sidebar displays
570 * @param {Function} success callback to execute after having updated the dataset
571 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
573 on_created: function(r, success, prepend_on_create) {
575 // should not happen in the server, but may happen for internal purpose
576 return $.Deferred().reject();
578 this.datarecord.id = r.result;
579 if (!prepend_on_create) {
580 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
581 this.dataset.index = this.dataset.ids.length - 1;
583 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
584 this.dataset.index = 0;
586 this.do_update_pager();
588 this.sidebar.attachments.do_update();
590 //openerp.log("The record has been created with id #" + this.datarecord.id);
592 return $.when(_.extend(r, {created: true})).then(success);
595 on_action: function (action) {
596 console.debug('Executing action', action);
600 return this.reload_mutex.exec(function() {
601 if (self.dataset.index == null || self.dataset.index < 0) {
602 return $.when(self.on_button_new());
604 return self.dataset.read_index(_.keys(self.fields_view.fields), {
605 context : { 'bin_size' : true }
606 }).pipe(self.on_record_loaded);
610 get_fields_values: function(blacklist) {
611 blacklist = blacklist || [];
613 var ids = this.get_selected_ids();
614 values["id"] = ids.length > 0 ? ids[0] : false;
615 _.each(this.fields, function(value, key) {
616 if (_.include(blacklist, key))
618 var val = value.get_value();
623 get_selected_ids: function() {
624 var id = this.dataset.ids[this.dataset.index];
625 return id ? [id] : [];
627 recursive_save: function() {
629 return $.when(this.do_save()).pipe(function(res) {
630 if (self.dataset.parent_view)
631 return self.dataset.parent_view.recursive_save();
634 is_dirty: function() {
635 return _.any(this.fields, function (value) {
636 return value.is_dirty();
639 is_interactible_record: function() {
640 var id = this.datarecord.id;
642 if (this.options.not_interactible_on_create)
644 } else if (typeof(id) === "string") {
645 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
650 sidebar_context: function () {
651 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
653 open_defaults_dialog: function () {
655 var fields = _.chain(this.fields)
656 .map(function (field, name) {
657 var value = field.get_value();
658 // ignore fields which are empty, invisible, readonly, o2m
663 || field.field.type === 'one2many'
664 || field.field.type === 'many2many') {
668 switch(field.field.type) {
670 displayed = _(field.values).find(function (option) {
671 return option[0] === value;
675 displayed = field.value[1] || value;
683 string: field.string,
685 displayed: displayed,
686 // convert undefined to false
687 change_default: !!field.field.change_default
691 .sortBy(function (field) { return field.string; })
693 var conditions = _.chain(fields)
694 .filter(function (field) { return field.change_default; })
697 var d = new openerp.web.Dialog(this, {
698 title: _t("Set Default"),
701 conditions: conditions
704 {text: _t("Close"), click: function () { d.close(); }},
705 {text: _t("Save default"), click: function () {
706 var $defaults = d.$element.find('#formview_default_fields');
707 var field_to_set = $defaults.val();
709 $defaults.parent().addClass('invalid');
712 var condition = d.$element.find('#formview_default_conditions').val(),
713 all_users = d.$element.find('#formview_default_all').is(':checked');
714 new openerp.web.DataSet(self, 'ir.values').call(
718 self.fields[field_to_set].get_value(),
722 ]).then(function () { d.close(); });
726 d.template = 'FormView.set_default';
730 openerp.web.FormDialog = openerp.web.Dialog.extend({
731 init: function(parent, options, view_id, dataset) {
732 this._super(parent, options);
733 this.dataset = dataset;
734 this.view_id = view_id;
739 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
743 this.form.appendTo(this.$element);
744 this.form.on_created.add_last(this.on_form_dialog_saved);
745 this.form.on_saved.add_last(this.on_form_dialog_saved);
748 select_id: function(id) {
749 if (this.form.dataset.select_id(id)) {
750 return this.form.do_show();
752 this.do_warn("Could not find id in dataset");
753 return $.Deferred().reject();
756 on_form_dialog_saved: function(r) {
762 openerp.web.form = {};
764 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
765 init: function(parent, form_view) {
766 var $section = parent.add_section(_t('Attachments'), 'attachments');
767 this.$div = $('<div class="oe-sidebar-attachments"></div>');
768 $section.append(this.$div);
770 this._super(parent, $section.attr('id'));
771 this.view = form_view;
773 do_update: function() {
774 if (!this.view.datarecord.id) {
775 this.on_attachments_loaded([]);
777 (new openerp.web.DataSetSearch(
778 this, 'ir.attachment', this.view.dataset.get_context(),
780 ['res_model', '=', this.view.dataset.model],
781 ['res_id', '=', this.view.datarecord.id],
782 ['type', 'in', ['binary', 'url']]
783 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
786 on_attachments_loaded: function(attachments) {
787 this.attachments = attachments;
788 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
789 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
790 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
792 on_attachment_changed: function(e) {
793 window[this.element_id + '_iframe'] = this.do_update;
794 var $e = $(e.target);
795 if ($e.val() != '') {
796 this.$element.find('form.oe-binary-form').submit();
797 $e.parent().find('input[type=file]').prop('disabled', true);
798 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
801 on_attachment_delete: function(e) {
802 var self = this, $e = $(e.currentTarget);
803 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
804 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
805 this.rpc('/web/dataset/unlink', {
806 model: 'ir.attachment',
807 ids: [parseInt($e.attr('data-id'))]
809 $e.parent().remove();
810 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
816 openerp.web.form.compute_domain = function(expr, fields) {
818 for (var i = expr.length - 1; i >= 0; i--) {
820 if (ex.length == 1) {
821 var top = stack.pop();
824 stack.push(stack.pop() || top);
827 stack.push(stack.pop() && top);
833 throw new Error(_.str.sprintf(
834 _t("Unknown operator %s in domain %s"),
835 ex, JSON.stringify(expr)));
839 var field = fields[ex[0]];
841 throw new Error(_.str.sprintf(
842 _t("Unknown field %s in domain %s"),
843 ex[0], JSON.stringify(expr)));
845 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
849 switch (op.toLowerCase()) {
852 stack.push(field_value == val);
856 stack.push(field_value != val);
859 stack.push(field_value < val);
862 stack.push(field_value > val);
865 stack.push(field_value <= val);
868 stack.push(field_value >= val);
871 if (!_.isArray(val)) val = [val];
872 stack.push(_(val).contains(field_value));
875 if (!_.isArray(val)) val = [val];
876 stack.push(!_(val).contains(field_value));
880 _t("Unsupported operator %s in domain %s"),
881 op, JSON.stringify(expr));
884 return _.all(stack, _.identity);
887 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
888 form_template: 'Widget',
890 * @constructs openerp.web.form.Widget
891 * @extends openerp.web.OldWidget
896 init: function(view, node) {
899 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
900 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
901 this.type = this.type || node.tag;
902 this.element_name = this.element_name || this.type;
906 this.children = node.children;
907 this.colspan = parseInt(node.attrs.colspan || 1, 10);
908 this.decrease_max_width = 0;
910 this.string = this.string || node.attrs.string;
911 this.help = this.help || node.attrs.help;
912 this.invisible = this.modifiers['invisible'] === true;
913 this.classname = 'oe_form_' + this.type;
915 this.align = parseFloat(this.node.attrs.align);
916 if (isNaN(this.align) || this.align === 1) {
917 this.align = 'right';
918 } else if (this.align === 0) {
921 this.align = 'center';
924 this.width = this.node.attrs.width;
927 this._super.apply(this, arguments);
930 process_modifiers: function() {
931 var compute_domain = openerp.web.form.compute_domain;
932 for (var a in this.modifiers) {
933 this[a] = compute_domain(this.modifiers[a], this.view.fields);
936 update_dom: function() {
937 this.$element.toggle(!this.invisible);
939 render_element: function() {
940 this.$element.html(QWeb.render(this.form_template, { "widget": this }));
942 do_attach_tooltip: function(widget, trigger, options) {
943 widget = widget || this;
944 trigger = trigger || this.$element;
950 var template = widget.form_template + '.tooltip';
951 if (!QWeb.has_template(template)) {
952 template = 'WidgetLabel.tooltip';
954 return QWeb.render(template, {
955 debug: openerp.connection.debug,
958 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
963 trigger.tipsy(options);
965 _build_view_fields_values: function(blacklist) {
966 var a_dataset = this.view.dataset;
967 var fields_values = this.view.get_fields_values(blacklist);
968 var active_id = a_dataset.ids[a_dataset.index];
969 _.extend(fields_values, {
970 active_id: active_id || false,
971 active_ids: active_id ? [active_id] : [],
972 active_model: a_dataset.model,
975 if (a_dataset.parent_view) {
976 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
978 return fields_values;
980 _build_eval_context: function(blacklist) {
981 var a_dataset = this.view.dataset;
982 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
985 * Builds a new context usable for operations related to fields by merging
986 * the fields'context with the action's context.
988 build_context: function(blacklist) {
989 // only use the model's context if there is not context on the node
990 var v_context = this.node.attrs.context;
992 v_context = (this.field || {}).context || {};
995 if (v_context.__ref || true) { //TODO: remove true
996 var fields_values = this._build_eval_context(blacklist);
997 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1001 build_domain: function() {
1002 var f_domain = this.field.domain || [];
1003 var n_domain = this.node.attrs.domain || null;
1004 // if there is a domain on the node, overrides the model's domain
1005 var final_domain = n_domain !== null ? n_domain : f_domain;
1006 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1007 var fields_values = this._build_eval_context();
1008 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1010 return final_domain;
1014 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1015 form_template: 'WidgetFrame',
1016 init: function(view, node) {
1017 this._super(view, node);
1018 this.columns = parseInt(node.attrs.col || 4, 10);
1023 for (var i = 0; i < node.children.length; i++) {
1024 var n = node.children[i];
1025 if (n.tag == "newline") {
1028 this.handle_node(n);
1031 this.set_row_cells_with(this.table[this.table.length - 1]);
1033 render_element: function() {
1036 _.each(this.table, function(row) {
1037 _.each(row, function(td) {
1038 td.$element = self.$element.find('.' + td.element_class);
1039 td.render_element();
1044 _.each(this.table, function(row) {
1045 _.each(row, function(td) {
1050 add_row: function(){
1051 if (this.table.length) {
1052 this.set_row_cells_with(this.table[this.table.length - 1]);
1055 this.table.push(row);
1060 set_row_cells_with: function(row) {
1063 row_length = row.length;
1064 for (var i = 0; i < row.length; i++) {
1065 if (row[i].always_invisible) {
1068 bypass += row[i].width === undefined ? 0 : 1;
1069 max_width -= row[i].decrease_max_width;
1072 var size_unit = Math.round(max_width / (this.columns - bypass)),
1074 for (var i = 0; i < row.length; i++) {
1076 if (w.always_invisible) {
1079 colspan_sum += w.colspan;
1080 if (w.width === undefined) {
1081 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1083 w.width = width + '%';
1087 handle_node: function(node) {
1089 if (node.tag == 'field') {
1090 type = this.view.fields_view.fields[node.attrs.name] || {};
1091 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1092 // This way we can retain backward compatibility between addons and old clients
1093 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1094 node.attrs.nolabel = '1';
1097 var widget = instanciate_widget(this.view.registry.get_any(
1098 [node.attrs.widget, type.type, node.tag]), this.view, node);
1099 if (node.tag == 'field') {
1100 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1101 this.view.default_focus_field = widget;
1103 if (node.attrs.nolabel != '1') {
1104 var label = instanciate_widget(this.view.registry.get_object('label'), this.view, node);
1105 label["for"] = widget;
1106 this.add_widget(label, widget.colspan + 1);
1109 this.add_widget(widget);
1111 add_widget: function(widget, colspan) {
1112 var current_row = this.table[this.table.length - 1];
1113 if (!widget.always_invisible) {
1114 colspan = colspan || widget.colspan;
1115 if (current_row.length && (this.x + colspan) > this.columns) {
1116 current_row = this.add_row();
1118 this.x += widget.colspan;
1120 current_row.push(widget);
1125 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1126 form_template: 'WidgetGroup'
1129 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1130 form_template: 'WidgetNotebook',
1131 init: function(view, node) {
1132 this._super(view, node);
1134 for (var i = 0; i < node.children.length; i++) {
1135 var n = node.children[i];
1136 if (n.tag == "page") {
1137 var page = instanciate_widget(this.view.registry.get_object('notebookpage'),
1138 this.view, n, this, this.pages.length);
1139 this.pages.push(page);
1143 render_element: function() {
1146 _.each(this.pages, function(page) {
1147 page.$element = self.$element.find('.' + page.element_class);
1148 page.render_element();
1153 this._super.apply(this, arguments);
1154 this.$element.find('> ul > li').each(function (index, tab_li) {
1155 var page = self.pages[index],
1156 id = _.uniqueId(self.element_name + '-');
1157 page.element_id = id;
1158 $(tab_li).find('a').attr('href', '#' + id);
1160 this.$element.find('> div').each(function (index, page) {
1161 page.id = self.pages[index].element_id;
1163 this.$element.tabs();
1164 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1165 if (openerp.connection.debug) {
1166 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1170 _.each(this.pages, function(page) {
1174 do_select_first_visible_tab: function() {
1175 for (var i = 0; i < this.pages.length; i++) {
1176 var page = this.pages[i];
1177 if (page.invisible === false) {
1178 this.$element.tabs('select', page.index);
1185 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1186 form_template: 'WidgetNotebookPage',
1187 init: function(view, node, notebook, index) {
1188 this.notebook = notebook;
1190 this.element_name = 'page_' + index;
1191 this._super(view, node);
1194 this._super.apply(this, arguments);
1195 this.$element_tab = this.notebook.$element.find(
1196 '> ul > li:eq(' + this.index + ')');
1198 update_dom: function() {
1199 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1200 this.notebook.do_select_first_visible_tab();
1202 this.$element_tab.toggle(!this.invisible);
1203 this.$element.toggle(!this.invisible);
1207 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1208 form_template: 'WidgetSeparator',
1209 init: function(view, node) {
1210 this._super(view, node);
1211 this.orientation = node.attrs.orientation || 'horizontal';
1212 if (this.orientation === 'vertical') {
1215 this.classname += '_' + this.orientation;
1219 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1220 form_template: 'WidgetButton',
1221 init: function(view, node) {
1222 this._super(view, node);
1223 this.force_disabled = false;
1225 // We don't have button key bindings in the webclient
1226 this.string = this.string.replace(/_/g, '');
1228 if (node.attrs.default_focus == '1') {
1229 // TODO fme: provide enter key binding to widgets
1230 this.view.default_focus_button = this;
1234 this._super.apply(this, arguments);
1235 this.$element.find("button").click(this.on_click);
1236 if (this.help || openerp.connection.debug) {
1237 this.do_attach_tooltip();
1240 on_click: function() {
1242 this.force_disabled = true;
1243 this.check_disable();
1244 this.execute_action().always(function() {
1245 self.force_disabled = false;
1246 self.check_disable();
1249 execute_action: function() {
1251 var exec_action = function() {
1252 if (self.node.attrs.confirm) {
1253 var def = $.Deferred();
1254 var dialog = openerp.web.dialog($('<div>' + self.node.attrs.confirm + '</div>'), {
1255 title: _t('Confirm'),
1258 {text: _t("Cancel"), click: function() {
1260 $(this).dialog("close");
1263 {text: _t("Ok"), click: function() {
1264 self.on_confirmed().then(function() {
1267 $(this).dialog("close");
1272 return def.promise();
1274 return self.on_confirmed();
1277 if (!this.node.attrs.special) {
1278 return this.view.recursive_save().pipe(exec_action);
1280 return exec_action();
1283 on_confirmed: function() {
1286 var context = this.node.attrs.context;
1287 if (context && context.__ref) {
1288 context = new openerp.web.CompoundContext(context);
1289 context.set_eval_context(this._build_eval_context());
1292 return this.view.do_execute_action(
1293 _.extend({}, this.node.attrs, {context: context}),
1294 this.view.dataset, this.view.datarecord.id, function () {
1298 update_dom: function() {
1299 this._super.apply(this, arguments);
1300 this.check_disable();
1302 check_disable: function() {
1303 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1304 this.$element.find('button').prop('disabled', disabled);
1305 this.$element.find("button").css('color', disabled ? 'grey' : '');
1309 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1310 form_template: 'WidgetLabel',
1311 init: function(view, node) {
1312 this.element_name = 'label_' + node.attrs.name;
1314 this._super(view, node);
1316 if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1317 this.string = this.node.children[0];
1318 this.align = 'left';
1321 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1322 this.form_template = "WidgetParagraph";
1323 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1324 // Widgets default to right-aligned, but paragraph defaults to
1326 if (isNaN(parseFloat(this.node.attrs.align))) {
1327 this.align = 'left';
1330 this.multilines = this.string && _.str.lines(this.string).length > 1;
1334 this.decrease_max_width = 1;
1338 render_element: function() {
1340 if (this['for'] && this.type !== 'label') {
1341 rendered = QWeb.render(this.form_template, {widget: this['for']});
1343 // Actual label widgets should not have a false and have type label
1344 rendered = QWeb.render(this.form_template, {widget: this});
1346 this.$element.html(rendered);
1351 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1352 this.do_attach_tooltip(self['for']);
1354 this.$element.find("label").dblclick(function() {
1355 var widget = self['for'] || self;
1356 openerp.log(widget.element_class , widget);
1362 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1364 * @constructs openerp.web.form.Field
1365 * @extends openerp.web.form.Widget
1370 init: function(view, node) {
1371 this.name = node.attrs.name;
1372 this.value = undefined;
1373 view.fields[this.name] = this;
1374 view.fields_order.push(this.name);
1375 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1376 this.element_name = "field_" + this.name + "_" + this.type;
1378 this._super(view, node);
1380 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1383 this.field = view.fields_view.fields[node.attrs.name] || {};
1384 this.string = node.attrs.string || this.field.string;
1385 this.help = node.attrs.help || this.field.help;
1386 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1387 this.readonly = this.modifiers['readonly'] === true;
1388 this.required = this.modifiers['required'] === true;
1389 this.invalid = this.dirty = false;
1391 this.classname = 'oe_form_field_' + this.type;
1394 this._super.apply(this, arguments);
1395 if (this.field.translate) {
1396 this.view.translatable_fields.push(this);
1397 this.$element.addClass('oe_form_field_translatable');
1398 this.$element.find('.oe_field_translate').click(this.on_translate);
1400 if (this.nolabel && openerp.connection.debug) {
1401 this.do_attach_tooltip(this, this.$element);
1404 set_value: function(value) {
1406 this.invalid = false;
1408 this.on_value_changed();
1410 set_value_from_ui: function() {
1411 this.on_value_changed();
1413 on_value_changed: function() {
1415 on_translate: function() {
1416 this.view.open_translate_dialog(this);
1418 get_value: function() {
1421 is_valid: function() {
1422 return !this.invalid;
1424 is_dirty: function() {
1425 return this.dirty && !this.readonly;
1427 get_on_change_value: function() {
1428 return this.get_value();
1430 update_dom: function(show_invalid) {
1431 this._super.apply(this, arguments);
1432 if (this.field.translate) {
1433 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1435 if (!this.disable_utility_classes) {
1436 this.$element.toggleClass('disabled', this.readonly);
1437 this.$element.toggleClass('required', this.required);
1439 this.$element.toggleClass('invalid', !this.is_valid());
1443 on_ui_change: function() {
1446 if (this.is_valid()) {
1447 this.set_value_from_ui();
1448 this.view.do_onchange(this);
1449 this.view.on_form_changed(true);
1450 this.view.do_notify_change();
1452 this.update_dom(true);
1455 validate: function() {
1456 this.invalid = false;
1458 focus: function($element) {
1460 setTimeout(function() {
1468 get_definition_options: function() {
1469 if (!this.definition_options) {
1470 var str = this.node.attrs.options || '{}';
1471 this.definition_options = JSON.parse(str);
1473 return this.definition_options;
1477 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1478 form_template: 'FieldChar',
1479 init: function (view, node) {
1480 this._super(view, node);
1481 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1484 this._super.apply(this, arguments);
1485 this.$element.find('input').change(this.on_ui_change);
1487 set_value: function(value) {
1488 this._super.apply(this, arguments);
1489 var show_value = openerp.web.format_value(value, this, '');
1490 this.$element.find('input').val(show_value);
1493 update_dom: function() {
1494 this._super.apply(this, arguments);
1495 this.$element.find('input').prop('readonly', this.readonly);
1497 set_value_from_ui: function() {
1498 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1501 validate: function() {
1502 this.invalid = false;
1504 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1505 this.invalid = this.required && value === '';
1507 this.invalid = true;
1510 focus: function($element) {
1511 this._super($element || this.$element.find('input:first'));
1515 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1516 update_dom: function() {
1517 this._super.apply(this, arguments);
1518 this.$element.find('input').prop('readonly', true);
1522 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1523 form_template: 'FieldEmail',
1525 this._super.apply(this, arguments);
1526 this.$element.find('button').click(this.on_button_clicked);
1528 on_button_clicked: function() {
1529 if (!this.value || !this.is_valid()) {
1530 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1532 location.href = 'mailto:' + this.value;
1537 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1538 form_template: 'FieldUrl',
1540 this._super.apply(this, arguments);
1541 this.$element.find('button').click(this.on_button_clicked);
1543 on_button_clicked: function() {
1545 this.do_warn("Resource error", "This resource is empty");
1547 window.open(this.value);
1552 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1553 init: function (view, node) {
1554 this._super(view, node);
1555 if (node.attrs.digits) {
1556 this.parse_digits(node.attrs.digits);
1558 this.digits = view.fields_view.fields[node.attrs.name].digits;
1561 parse_digits: function (digits_attr) {
1562 // could use a Python parser instead.
1563 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1564 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1566 set_value: function(value) {
1567 if (value === false || value === undefined) {
1568 // As in GTK client, floats default to 0
1571 this._super.apply(this, [value]);
1575 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1576 template: "web.datetimepicker",
1577 jqueryui_object: 'datetimepicker',
1578 type_of_date: "datetime",
1579 init: function(parent) {
1580 this._super(parent);
1581 this.name = parent.name;
1585 this.$input = this.$element.find('input.oe_datepicker_master');
1586 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1587 this.$input.change(this.on_change);
1589 onSelect: this.on_picker_select,
1593 showButtonPanel: true
1595 this.$element.find('img.oe_datepicker_trigger').click(function() {
1596 if (!self.readonly && !self.picker('widget').is(':visible')) {
1597 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1598 self.$input_picker.show();
1599 self.picker('show');
1600 self.$input_picker.hide();
1603 this.set_readonly(false);
1606 picker: function() {
1607 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1609 on_picker_select: function(text, instance) {
1610 var date = this.picker('getDate');
1611 this.$input.val(date ? this.format_client(date) : '').change();
1613 set_value: function(value) {
1615 this.$input.val(value ? this.format_client(value) : '');
1617 get_value: function() {
1620 set_value_from_ui: function() {
1621 var value = this.$input.val() || false;
1622 this.value = this.parse_client(value);
1624 set_readonly: function(readonly) {
1625 this.readonly = readonly;
1626 this.$input.prop('readonly', this.readonly);
1627 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1629 is_valid: function(required) {
1630 var value = this.$input.val();
1635 this.parse_client(value);
1642 parse_client: function(v) {
1643 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1645 format_client: function(v) {
1646 return openerp.web.format_value(v, {"widget": this.type_of_date});
1648 on_change: function() {
1649 if (this.is_valid()) {
1650 this.set_value_from_ui();
1655 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1656 jqueryui_object: 'datepicker',
1657 type_of_date: "date"
1660 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1661 form_template: "EmptyComponent",
1662 build_widget: function() {
1663 return new openerp.web.DateTimeWidget(this);
1667 this._super.apply(this, arguments);
1668 this.datewidget = this.build_widget();
1669 this.datewidget.on_change.add_last(this.on_ui_change);
1670 this.datewidget.appendTo(this.$element);
1672 set_value: function(value) {
1674 this.datewidget.set_value(value);
1676 get_value: function() {
1677 return this.datewidget.get_value();
1679 update_dom: function() {
1680 this._super.apply(this, arguments);
1681 this.datewidget.set_readonly(this.readonly);
1683 validate: function() {
1684 this.invalid = !this.datewidget.is_valid(this.required);
1686 focus: function($element) {
1687 this._super($element || this.datewidget.$input);
1691 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1692 build_widget: function() {
1693 return new openerp.web.DateWidget(this);
1697 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1698 form_template: 'FieldText',
1700 this._super.apply(this, arguments);
1701 this.$element.find('textarea').change(this.on_ui_change);
1702 this.resized = false;
1704 set_value: function(value) {
1705 this._super.apply(this, arguments);
1706 var show_value = openerp.web.format_value(value, this, '');
1707 this.$element.find('textarea').val(show_value);
1708 if (!this.resized && this.view.options.resize_textareas) {
1709 this.do_resize(this.view.options.resize_textareas);
1710 this.resized = true;
1713 update_dom: function() {
1714 this._super.apply(this, arguments);
1715 this.$element.find('textarea').prop('readonly', this.readonly);
1717 set_value_from_ui: function() {
1718 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1721 validate: function() {
1722 this.invalid = false;
1724 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1725 this.invalid = this.required && value === '';
1727 this.invalid = true;
1730 focus: function($element) {
1731 this._super($element || this.$element.find('textarea:first'));
1733 do_resize: function(max_height) {
1734 max_height = parseInt(max_height, 10);
1735 var $input = this.$element.find('textarea'),
1736 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1738 $div.text($input.val());
1739 _.each('font-family,font-size,white-space'.split(','), function(style) {
1740 $div.css(style, $input.css(style));
1742 $div.appendTo($('body'));
1743 new_height = $div.height();
1744 if (new_height < 90) {
1747 if (!isNaN(max_height) && new_height > max_height) {
1748 new_height = max_height;
1751 $input.height(new_height);
1754 this.resized = false;
1758 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1759 form_template: 'FieldBoolean',
1762 this._super.apply(this, arguments);
1763 this.$element.find('input').click(self.on_ui_change);
1765 set_value: function(value) {
1766 this._super.apply(this, arguments);
1767 this.$element.find('input')[0].checked = value;
1769 set_value_from_ui: function() {
1770 this.value = this.$element.find('input').is(':checked');
1773 update_dom: function() {
1774 this._super.apply(this, arguments);
1775 this.$element.find('input').prop('disabled', this.readonly);
1777 focus: function($element) {
1778 this._super($element || this.$element.find('input:first'));
1782 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1783 form_template: 'FieldProgressBar',
1785 this._super.apply(this, arguments);
1786 this.$element.find('div').progressbar({
1788 disabled: this.readonly
1791 set_value: function(value) {
1792 this._super.apply(this, arguments);
1793 var show_value = Number(value);
1794 if (isNaN(show_value)) {
1797 var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1798 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1802 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1803 // to replace view editor
1806 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1807 form_template: 'FieldSelection',
1808 init: function(view, node) {
1810 this._super(view, node);
1811 this.values = _.clone(this.field.selection);
1812 _.each(this.values, function(v, i) {
1813 if (v[0] === false && v[1] === '') {
1814 self.values.splice(i, 1);
1817 this.values.unshift([false, '']);
1820 // Flag indicating whether we're in an event chain containing a change
1821 // event on the select, in order to know what to do on keyup[RETURN]:
1822 // * If the user presses [RETURN] as part of changing the value of a
1823 // selection, we should just let the value change and not let the
1824 // event broadcast further (e.g. to validating the current state of
1825 // the form in editable list view, which would lead to saving the
1826 // current row or switching to the next one)
1827 // * If the user presses [RETURN] with a select closed (side-effect:
1828 // also if the user opened the select and pressed [RETURN] without
1829 // changing the selected value), takes the action as validating the
1831 var ischanging = false;
1832 this._super.apply(this, arguments);
1833 this.$element.find('select')
1834 .change(this.on_ui_change)
1835 .change(function () { ischanging = true; })
1836 .click(function () { ischanging = false; })
1837 .keyup(function (e) {
1838 if (e.which !== 13 || !ischanging) { return; }
1839 e.stopPropagation();
1843 set_value: function(value) {
1844 value = value === null ? false : value;
1845 value = value instanceof Array ? value[0] : value;
1848 for (var i = 0, ii = this.values.length; i < ii; i++) {
1849 if (this.values[i][0] === value) index = i;
1851 this.$element.find('select')[0].selectedIndex = index;
1853 set_value_from_ui: function() {
1854 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1857 update_dom: function() {
1858 this._super.apply(this, arguments);
1859 this.$element.find('select').prop('disabled', this.readonly);
1861 validate: function() {
1862 var value = this.values[this.$element.find('select')[0].selectedIndex];
1863 this.invalid = !(value && !(this.required && value[0] === false));
1865 focus: function($element) {
1866 this._super($element || this.$element.find('select:first'));
1870 // jquery autocomplete tweak to allow html
1872 var proto = $.ui.autocomplete.prototype,
1873 initSource = proto._initSource;
1875 function filter( array, term ) {
1876 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1877 return $.grep( array, function(value) {
1878 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1883 _initSource: function() {
1884 if ( this.options.html && $.isArray(this.options.source) ) {
1885 this.source = function( request, response ) {
1886 response( filter( this.options.source, request.term ) );
1889 initSource.call( this );
1893 _renderItem: function( ul, item) {
1894 return $( "<li></li>" )
1895 .data( "item.autocomplete", item )
1896 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1902 openerp.web.form.dialog = function(content, options) {
1903 options = _.extend({
1908 var dialog = new openerp.web.Dialog(null, options, content).open();
1909 return dialog.$element;
1912 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1913 form_template: 'FieldMany2One',
1914 init: function(view, node) {
1915 this._super(view, node);
1918 this.cm_id = _.uniqueId('m2o_cm_');
1919 this.last_search = [];
1920 this.tmp_value = undefined;
1925 this.$input = this.$element.find("input");
1926 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1927 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1930 var init_context_menu_def = $.Deferred().then(function(e) {
1931 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1932 rdataset.call("get", ['action', 'client_action_relate',
1933 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1934 .then(function(result) {
1935 self.related_entries = result;
1937 var $cmenu = $("#" + self.cm_id);
1938 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1940 bindings[self.cm_id + "_search"] = function() {
1941 self._search_create_popup("search");
1943 bindings[self.cm_id + "_create"] = function() {
1944 self._search_create_popup("form");
1946 bindings[self.cm_id + "_open"] = function() {
1950 var pop = new openerp.web.form.FormOpenPopup(self.view);
1952 self.field.relation,
1954 self.build_context(),
1956 title: _t("Open: ") + (self.string || self.name)
1959 pop.on_write_completed.add_last(function() {
1960 self.set_value(self.value[0]);
1963 _.each(_.range(self.related_entries.length), function(i) {
1964 bindings[self.cm_id + "_related_" + i] = function() {
1965 self.open_related(self.related_entries[i]);
1968 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1969 bindings: bindings, itemStyle: {"color": ""},
1970 onContextMenu: function() {
1972 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1974 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1976 if (!self.readonly) {
1977 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1979 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1982 }, menuStyle: {width: "200px"}
1984 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1987 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1988 this.$menu_btn.click(ctx_callback);
1990 // some behavior for input
1991 this.$input.keyup(function() {
1992 if (self.$input.val() === "") {
1993 self._change_int_value(null);
1994 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1995 self._change_int_value(undefined);
1998 this.$drop_down.click(function() {
2001 if (self.$input.autocomplete("widget").is(":visible")) {
2002 self.$input.autocomplete("close");
2005 self.$input.autocomplete("search", "");
2007 self.$input.autocomplete("search");
2009 self.$input.focus();
2012 var anyoneLoosesFocus = function() {
2013 if (!self.$input.is(":focus") &&
2014 !self.$input.autocomplete("widget").is(":visible") &&
2016 if (self.value === undefined && self.last_search.length > 0) {
2017 self._change_int_ext_value(self.last_search[0]);
2019 self._change_int_ext_value(null);
2023 this.$input.focusout(anyoneLoosesFocus);
2025 var isSelecting = false;
2027 this.$input.autocomplete({
2028 source: function(req, resp) { self.get_search_result(req, resp); },
2029 select: function(event, ui) {
2033 self._change_int_value([item.id, item.name]);
2034 } else if (item.action) {
2035 self._change_int_value(undefined);
2040 focus: function(e, ui) {
2044 close: anyoneLoosesFocus,
2048 this.$input.autocomplete("widget").addClass("openerp");
2049 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2050 this.$input.keyup(function(e) {
2051 if (e.which === 13) {
2053 e.stopPropagation();
2055 isSelecting = false;
2058 // autocomplete component content handling
2059 get_search_result: function(request, response) {
2060 var search_val = request.term;
2063 if (this.abort_last) {
2065 delete this.abort_last;
2067 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2069 dataset.name_search(search_val, self.build_domain(), 'ilike',
2070 this.limit + 1, function(data) {
2071 self.last_search = data;
2072 // possible selections for the m2o
2073 var values = _.map(data, function(x) {
2075 label: _.str.escapeHTML(x[1]),
2082 // search more... if more results that max
2083 if (values.length > self.limit) {
2084 values = values.slice(0, self.limit);
2085 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2086 dataset.name_search(search_val, self.build_domain(), 'ilike'
2087 , false, function(data) {
2088 self._change_int_value(null);
2089 self._search_create_popup("search", data);
2094 var raw_result = _(data.result).map(function(x) {return x[1];});
2095 if (search_val.length > 0 &&
2096 !_.include(raw_result, search_val) &&
2097 (!self.value || search_val !== self.value[1])) {
2098 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2099 $('<span />').text(search_val).html()), action: function() {
2100 self._quick_create(search_val);
2104 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2105 self._change_int_value(null);
2106 self._search_create_popup("form", undefined, {"default_name": search_val});
2111 this.abort_last = dataset.abort_last;
2113 _quick_create: function(name) {
2115 var slow_create = function () {
2116 self._change_int_value(null);
2117 self._search_create_popup("form", undefined, {"default_name": name});
2119 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2120 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2121 dataset.name_create(name, function(data) {
2122 self._change_int_ext_value(data);
2123 }).fail(function(error, event) {
2124 event.preventDefault();
2130 // all search/create popup handling
2131 _search_create_popup: function(view, ids, context) {
2133 var pop = new openerp.web.form.SelectCreatePopup(this);
2135 self.field.relation,
2137 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2138 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2140 disable_multiple_selection: true
2142 self.build_domain(),
2143 new openerp.web.CompoundContext(self.build_context(), context || {})
2145 pop.on_select_elements.add(function(element_ids) {
2146 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2147 dataset.name_get([element_ids[0]], function(data) {
2148 self._change_int_ext_value(data[0]);
2152 _change_int_ext_value: function(value) {
2153 this._change_int_value(value);
2154 this.$input.val(this.value ? this.value[1] : "");
2156 _change_int_value: function(value) {
2158 var back_orig_value = this.original_value;
2159 if (this.value === null || this.value) {
2160 this.original_value = this.value;
2162 if (back_orig_value === undefined) { // first use after a set_value()
2165 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2166 !== (this.value ? this.value[0] : null))) {
2167 this.on_ui_change();
2170 set_value: function(value) {
2171 value = value || null;
2172 this.invalid = false;
2174 this.tmp_value = value;
2176 self.on_value_changed();
2177 var real_set_value = function(rval) {
2178 self.tmp_value = undefined;
2180 self.original_value = undefined;
2181 self._change_int_ext_value(rval);
2183 if (value && !(value instanceof Array)) {
2184 // name_get in a m2o does not use the context of the field
2185 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2186 dataset.name_get([value], function(data) {
2187 real_set_value(data[0]);
2188 }).fail(function() {self.tmp_value = undefined;});
2190 $.async_when().then(function() {real_set_value(value);});
2193 get_value: function() {
2194 if (this.tmp_value !== undefined) {
2195 if (this.tmp_value instanceof Array) {
2196 return this.tmp_value[0];
2198 return this.tmp_value ? this.tmp_value : false;
2200 if (this.value === undefined)
2201 return this.original_value ? this.original_value[0] : false;
2202 return this.value ? this.value[0] : false;
2204 validate: function() {
2205 this.invalid = false;
2206 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2208 this.invalid = this.required;
2211 open_related: function(related) {
2215 var additional_context = {
2216 active_id: self.value[0],
2217 active_ids: [self.value[0]],
2218 active_model: self.field.relation
2220 self.rpc("/web/action/load", {
2221 action_id: related[2].id,
2222 context: additional_context
2223 }, function(result) {
2224 result.result.context = _.extend(result.result.context || {}, additional_context);
2225 self.do_action(result.result);
2228 focus: function ($element) {
2229 this._super($element || this.$input);
2231 update_dom: function() {
2232 this._super.apply(this, arguments);
2233 this.$input.prop('readonly', this.readonly);
2238 # Values: (0, 0, { fields }) create
2239 # (1, ID, { fields }) update
2240 # (2, ID) remove (delete)
2241 # (3, ID) unlink one (target id or target of relation)
2243 # (5) unlink all (only valid for one2many)
2248 'create': function (values) {
2249 return [commands.CREATE, false, values];
2251 // (1, id, {values})
2253 'update': function (id, values) {
2254 return [commands.UPDATE, id, values];
2258 'delete': function (id) {
2259 return [commands.DELETE, id, false];
2261 // (3, id[, _]) removes relation, but not linked record itself
2263 'forget': function (id) {
2264 return [commands.FORGET, id, false];
2268 'link_to': function (id) {
2269 return [commands.LINK_TO, id, false];
2273 'delete_all': function () {
2274 return [5, false, false];
2276 // (6, _, ids) replaces all linked records with provided ids
2278 'replace_with': function (ids) {
2279 return [6, false, ids];
2282 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2283 form_template: 'FieldOne2Many',
2284 multi_selection: false,
2285 init: function(view, node) {
2286 this._super(view, node);
2287 this.is_loaded = $.Deferred();
2288 this.initial_is_loaded = this.is_loaded;
2289 this.is_setted = $.Deferred();
2290 this.form_last_update = $.Deferred();
2291 this.init_form_last_update = this.form_last_update;
2292 this.disable_utility_classes = true;
2295 this._super.apply(this, arguments);
2299 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2300 this.dataset.o2m = this;
2301 this.dataset.parent_view = this.view;
2302 this.dataset.child_name = this.name;
2303 //this.dataset.child_name =
2304 this.dataset.on_change.add_last(function() {
2305 self.trigger_on_change();
2308 this.is_setted.then(function() {
2312 trigger_on_change: function() {
2313 var tmp = this.doing_on_change;
2314 this.doing_on_change = true;
2315 this.on_ui_change();
2316 this.doing_on_change = tmp;
2318 is_readonly: function() {
2319 return this.readonly || this.force_readonly;
2321 load_views: function() {
2324 var modes = this.node.attrs.mode;
2325 modes = !!modes ? modes.split(",") : ["tree"];
2327 _.each(modes, function(mode) {
2330 view_type: mode == "tree" ? "list" : mode,
2331 options: { sidebar : false }
2333 if (self.field.views && self.field.views[mode]) {
2334 view.embedded_view = self.field.views[mode];
2336 if(view.view_type === "list") {
2337 view.options.selectable = self.multi_selection;
2338 if (self.is_readonly()) {
2339 view.options.addable = null;
2340 view.options.deletable = null;
2341 view.options.isClarkGable = false;
2343 } else if (view.view_type === "form") {
2344 if (self.is_readonly()) {
2345 view.view_type = 'page';
2347 view.options.not_interactible_on_create = true;
2353 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2354 this.viewmanager.template = 'One2Many.viewmanager';
2355 this.viewmanager.registry = openerp.web.views.extend({
2356 list: 'openerp.web.form.One2ManyListView',
2357 form: 'openerp.web.form.One2ManyFormView',
2358 page: 'openerp.web.PageView'
2360 var once = $.Deferred().then(function() {
2361 self.init_form_last_update.resolve();
2363 var def = $.Deferred().then(function() {
2364 self.initial_is_loaded.resolve();
2366 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2367 if (view_type == "list") {
2368 controller.o2m = self;
2369 if (self.is_readonly())
2370 controller.set_editable(false);
2371 } else if (view_type == "form" || view_type == 'page') {
2372 if (view_type == 'page' || self.is_readonly()) {
2373 $(".oe_form_buttons", controller.$element).children().remove();
2375 controller.on_record_loaded.add_last(function() {
2378 controller.on_pager_action.add_first(function() {
2379 self.save_any_view();
2381 } else if (view_type == "graph") {
2382 self.reload_current_view()
2386 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2387 $.when(self.save_any_view()).then(function() {
2388 if(n_mode === "list")
2389 $.async_when().then(function() {self.reload_current_view();});
2392 this.is_setted.then(function() {
2393 $.async_when().then(function () {
2394 self.viewmanager.appendTo(self.$element);
2399 reload_current_view: function() {
2401 return self.is_loaded = self.is_loaded.pipe(function() {
2402 var active_view = self.viewmanager.active_view;
2403 var view = self.viewmanager.views[active_view].controller;
2404 if(active_view === "list") {
2405 return view.reload_content();
2406 } else if (active_view === "form" || active_view === 'page') {
2407 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2408 self.dataset.index = 0;
2410 var act = function() {
2411 return view.do_show();
2413 self.form_last_update = self.form_last_update.pipe(act, act);
2414 return self.form_last_update;
2415 } else if (active_view === "graph") {
2416 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2420 set_value: function(value) {
2421 value = value || [];
2423 this.dataset.reset_ids([]);
2424 if(value.length >= 1 && value[0] instanceof Array) {
2426 _.each(value, function(command) {
2427 var obj = {values: command[2]};
2428 switch (command[0]) {
2429 case commands.CREATE:
2430 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2432 self.dataset.to_create.push(obj);
2433 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2436 case commands.UPDATE:
2437 obj['id'] = command[1];
2438 self.dataset.to_write.push(obj);
2439 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2442 case commands.DELETE:
2443 self.dataset.to_delete.push({id: command[1]});
2445 case commands.LINK_TO:
2446 ids.push(command[1]);
2448 case commands.DELETE_ALL:
2449 self.dataset.delete_all = true;
2454 this.dataset.set_ids(ids);
2455 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2457 this.dataset.delete_all = true;
2458 _.each(value, function(command) {
2459 var obj = {values: command};
2460 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2462 self.dataset.to_create.push(obj);
2463 self.dataset.cache.push(_.clone(obj));
2467 this.dataset.set_ids(ids);
2470 this.dataset.reset_ids(value);
2472 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2473 this.dataset.index = 0;
2475 self.is_setted.resolve();
2476 return self.reload_current_view();
2478 get_value: function() {
2482 this.save_any_view();
2483 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2484 val = val.concat(_.map(this.dataset.ids, function(id) {
2485 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2487 return commands.create(alter_order.values);
2489 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2491 return commands.update(alter_order.id, alter_order.values);
2493 return commands.link_to(id);
2495 return val.concat(_.map(
2496 this.dataset.to_delete, function(x) {
2497 return commands['delete'](x.id);}));
2499 save_any_view: function() {
2500 if (this.doing_on_change)
2502 return this.session.synchronized_mode(_.bind(function() {
2503 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2504 this.viewmanager.views[this.viewmanager.active_view] &&
2505 this.viewmanager.views[this.viewmanager.active_view].controller) {
2506 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2507 if (this.viewmanager.active_view === "form") {
2508 if (!view.is_initialized.isResolved()) {
2511 var res = $.when(view.do_save());
2512 if (!res.isResolved() && !res.isRejected()) {
2513 console.warn("Asynchronous get_value() is not supported in form view.");
2516 } else if (this.viewmanager.active_view === "list") {
2517 var res = $.when(view.ensure_saved());
2518 if (!res.isResolved() && !res.isRejected()) {
2519 console.warn("Asynchronous get_value() is not supported in list view.");
2527 is_valid: function() {
2529 return this._super();
2531 validate: function() {
2532 this.invalid = false;
2533 if (!this.viewmanager.views[this.viewmanager.active_view])
2535 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2536 if (this.viewmanager.active_view === "form") {
2537 for (var f in view.fields) {
2539 if (!f.is_valid()) {
2540 this.invalid = true;
2546 is_dirty: function() {
2547 this.save_any_view();
2548 return this._super();
2550 update_dom: function() {
2551 this._super.apply(this, arguments);
2553 if (this.previous_readonly !== this.readonly) {
2554 this.previous_readonly = this.readonly;
2555 if (this.viewmanager) {
2556 this.is_loaded = this.is_loaded.pipe(function() {
2557 self.viewmanager.stop();
2558 return $.when(self.load_views()).then(function() {
2559 self.reload_current_view();
2567 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2568 get_context: function() {
2569 this.context = this.o2m.build_context([this.o2m.name]);
2570 return this.context;
2574 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2575 _template: 'One2Many.listview',
2576 do_add_record: function () {
2577 if (this.options.editable) {
2578 this._super.apply(this, arguments);
2581 var pop = new openerp.web.form.SelectCreatePopup(this);
2582 pop.on_default_get.add(self.dataset.on_default_get);
2584 self.o2m.field.relation,
2586 title: _t("Create: ") + self.name,
2587 initial_view: "form",
2588 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2589 create_function: function(data, callback, error_callback) {
2590 return self.o2m.dataset.create(data).then(function(r) {
2591 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2592 self.o2m.dataset.on_change();
2593 }).then(callback, error_callback);
2595 read_function: function() {
2596 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2598 parent_view: self.o2m.view,
2599 child_name: self.o2m.name,
2600 form_view_options: {'not_interactible_on_create':true}
2602 self.o2m.build_domain(),
2603 self.o2m.build_context()
2605 pop.on_select_elements.add_last(function() {
2606 self.o2m.reload_current_view();
2610 do_activate_record: function(index, id) {
2612 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2613 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2614 title: _t("Open: ") + self.name,
2616 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2617 parent_view: self.o2m.view,
2618 child_name: self.o2m.name,
2619 read_function: function() {
2620 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2622 form_view_options: {'not_interactible_on_create':true},
2623 readonly: self.o2m.is_readonly()
2625 pop.on_write.add(function(id, data) {
2626 self.o2m.dataset.write(id, data, {}, function(r) {
2627 self.o2m.reload_current_view();
2631 do_button_action: function (name, id, callback) {
2633 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2634 return this._super(name, id, _.bind(def.resolve, def));
2638 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2639 form_template: 'One2Many.formview',
2640 on_loaded: function(data) {
2643 this.$form_header.find('button.oe_form_button_create').click(function() {
2644 self.do_save().then(self.on_button_new);
2647 do_notify_change: function() {
2648 if (this.dataset.parent_view) {
2649 this.dataset.parent_view.do_notify_change();
2651 this._super.apply(this, arguments);
2656 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2657 form_template: 'FieldMany2Many',
2658 multi_selection: false,
2659 init: function(view, node) {
2660 this._super(view, node);
2661 this.list_id = _.uniqueId("many2many");
2662 this.is_loaded = $.Deferred();
2663 this.initial_is_loaded = this.is_loaded;
2664 this.is_setted = $.Deferred();
2667 this._super.apply(this, arguments);
2671 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2672 this.dataset.m2m = this;
2673 this.dataset.on_unlink.add_last(function(ids) {
2674 self.on_ui_change();
2677 this.is_setted.then(function() {
2681 set_value: function(value) {
2682 value = value || [];
2683 if (value.length >= 1 && value[0] instanceof Array) {
2684 value = value[0][2];
2687 this.dataset.set_ids(value);
2689 self.reload_content();
2690 this.is_setted.resolve();
2692 get_value: function() {
2693 return [commands.replace_with(this.dataset.ids)];
2695 validate: function() {
2696 this.invalid = false;
2698 is_readonly: function() {
2699 return this.readonly || this.force_readonly;
2701 load_view: function() {
2703 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2704 'addable': self.is_readonly() ? null : _t("Add"),
2705 'deletable': self.is_readonly() ? false : true,
2706 'selectable': self.multi_selection,
2707 'isClarkGable': self.is_readonly() ? false : true
2709 var embedded = (this.field.views || {}).tree;
2711 this.list_view.set_embedded_view(embedded);
2713 this.list_view.m2m_field = this;
2714 var loaded = $.Deferred();
2715 this.list_view.on_loaded.add_last(function() {
2716 self.initial_is_loaded.resolve();
2719 $.async_when().then(function () {
2720 self.list_view.appendTo($("#" + self.list_id));
2724 reload_content: function() {
2726 this.is_loaded = this.is_loaded.pipe(function() {
2727 return self.list_view.reload_content();
2730 update_dom: function() {
2731 this._super.apply(this, arguments);
2733 if (this.previous_readonly !== this.readonly) {
2734 this.previous_readonly = this.readonly;
2735 if (this.list_view) {
2736 this.is_loaded = this.is_loaded.pipe(function() {
2737 self.list_view.stop();
2738 return $.when(self.load_view()).then(function() {
2739 self.reload_content();
2747 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2748 get_context: function() {
2749 this.context = this.m2m.build_context();
2750 return this.context;
2756 * @extends openerp.web.ListView
2758 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2759 do_add_record: function () {
2760 var pop = new openerp.web.form.SelectCreatePopup(this);
2764 title: _t("Add: ") + this.name
2766 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2767 this.m2m_field.build_context()
2770 pop.on_select_elements.add(function(element_ids) {
2771 _.each(element_ids, function(element_id) {
2772 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2773 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2774 self.m2m_field.on_ui_change();
2775 self.reload_content();
2780 do_activate_record: function(index, id) {
2782 var pop = new openerp.web.form.FormOpenPopup(this);
2783 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2784 title: _t("Open: ") + this.name,
2785 readonly: this.widget_parent.is_readonly()
2787 pop.on_write_completed.add_last(function() {
2788 self.reload_content();
2795 * @extends openerp.web.OldWidget
2797 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2798 template: "SelectCreatePopup",
2802 * - initial_view: form or search (default search)
2803 * - disable_multiple_selection
2804 * - alternative_form_view
2805 * - create_function (defaults to a naive saving behavior)
2808 * - form_view_options
2809 * - list_view_options
2812 select_element: function(model, options, domain, context) {
2815 this.domain = domain || [];
2816 this.context = context || {};
2817 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2818 return self.create_row.apply(self, arguments);
2819 }, read_function: null});
2820 this.initial_ids = this.options.initial_ids;
2821 this.created_elements = [];
2822 this.render_element();
2823 openerp.web.form.dialog(this.$element, {
2827 title: options.title || ""
2834 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2836 this.dataset.create_function = function() {
2837 return self.options.create_function.apply(null, arguments).then(function(r) {
2838 self.created_elements.push(r.result);
2841 this.dataset.write_function = function() {
2842 return self.write_row.apply(self, arguments);
2844 this.dataset.read_function = this.options.read_function;
2845 this.dataset.parent_view = this.options.parent_view;
2846 this.dataset.child_name = this.options.child_name;
2847 this.dataset.on_default_get.add(this.on_default_get);
2848 if (this.options.initial_view == "search") {
2849 self.rpc('/web/session/eval_domain_and_context', {
2851 contexts: [this.context]
2852 }, function (results) {
2853 var search_defaults = {};
2854 _.each(results.context, function (value, key) {
2855 var match = /^search_default_(.*)$/.exec(key);
2857 search_defaults[match[1]] = value;
2860 self.setup_search_view(search_defaults);
2866 setup_search_view: function(search_defaults) {
2868 if (this.searchview) {
2869 this.searchview.stop();
2871 this.searchview = new openerp.web.SearchView(this,
2872 this.dataset, false, search_defaults);
2873 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2874 if (self.initial_ids) {
2875 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2876 contexts, groupbys);
2877 self.initial_ids = undefined;
2879 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2882 this.searchview.on_loaded.add_last(function () {
2883 self.view_list = new openerp.web.form.SelectCreateListView(self,
2884 self.dataset, false,
2885 _.extend({'deletable': false,
2886 'selectable': !self.options.disable_multiple_selection
2887 }, self.options.list_view_options || {}));
2888 self.view_list.popup = self;
2889 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2890 self.view_list.do_show();
2891 }).pipe(function() {
2892 self.searchview.do_search();
2894 self.view_list.on_loaded.add_last(function() {
2895 var $buttons = self.view_list.$element.find(".oe-actions");
2896 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2897 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2898 $cbutton.click(function() {
2901 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2902 if(self.options.disable_multiple_selection) {
2905 $sbutton.click(function() {
2906 self.on_select_elements(self.selected_ids);
2911 this.searchview.appendTo($("#" + this.element_id + "_search"));
2913 do_search: function(domains, contexts, groupbys) {
2915 this.rpc('/web/session/eval_domain_and_context', {
2916 domains: domains || [],
2917 contexts: contexts || [],
2918 group_by_seq: groupbys || []
2919 }, function (results) {
2920 self.view_list.do_search(results.domain, results.context, results.group_by);
2923 create_row: function() {
2925 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2926 wdataset.parent_view = this.options.parent_view;
2927 wdataset.child_name = this.options.child_name;
2928 return wdataset.create.apply(wdataset, arguments);
2930 write_row: function() {
2932 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2933 wdataset.parent_view = this.options.parent_view;
2934 wdataset.child_name = this.options.child_name;
2935 return wdataset.write.apply(wdataset, arguments);
2937 on_select_elements: function(element_ids) {
2939 on_click_element: function(ids) {
2940 this.selected_ids = ids || [];
2941 if(this.selected_ids.length > 0) {
2942 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2944 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2947 new_object: function() {
2949 if (this.searchview) {
2950 this.searchview.hide();
2952 if (this.view_list) {
2953 this.view_list.$element.hide();
2955 this.dataset.index = null;
2956 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2957 if (this.options.alternative_form_view) {
2958 this.view_form.set_embedded_view(this.options.alternative_form_view);
2960 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2961 this.view_form.on_loaded.add_last(function() {
2962 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2963 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2964 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2965 $nbutton.click(function() {
2966 $.when(self.view_form.do_save()).then(function() {
2967 self.view_form.reload_mutex.exec(function() {
2968 self.view_form.on_button_new();
2972 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2973 $nbutton.click(function() {
2974 $.when(self.view_form.do_save()).then(function() {
2975 self.view_form.reload_mutex.exec(function() {
2980 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2981 $cbutton.click(function() {
2985 this.view_form.do_show();
2987 check_exit: function() {
2988 if (this.created_elements.length > 0) {
2989 this.on_select_elements(this.created_elements);
2993 on_default_get: function(res) {}
2996 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2997 do_add_record: function () {
2998 this.popup.new_object();
3000 select_record: function(index) {
3001 this.popup.on_select_elements([this.dataset.ids[index]]);
3004 do_select: function(ids, records) {
3005 this._super(ids, records);
3006 this.popup.on_click_element(ids);
3012 * @extends openerp.web.OldWidget
3014 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
3015 template: "FormOpenPopup",
3018 * - alternative_form_view
3019 * - auto_write (default true)
3023 * - form_view_options
3026 show_element: function(model, row_id, context, options) {
3028 this.row_id = row_id;
3029 this.context = context || {};
3030 this.options = _.defaults(options || {}, {"auto_write": true});
3031 this.render_element();
3032 openerp.web.dialog(this.$element, {
3033 title: options.title || '',
3042 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3043 this.dataset.fop = this;
3044 this.dataset.ids = [this.row_id];
3045 this.dataset.index = 0;
3046 this.dataset.parent_view = this.options.parent_view;
3047 this.dataset.child_name = this.options.child_name;
3048 this.setup_form_view();
3050 on_write: function(id, data) {
3051 if (!this.options.auto_write)
3054 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3055 wdataset.parent_view = this.options.parent_view;
3056 wdataset.child_name = this.options.child_name;
3057 wdataset.write(id, data, {}, function(r) {
3058 self.on_write_completed();
3061 on_write_completed: function() {},
3062 setup_form_view: function() {
3064 var FormClass = this.options.readonly
3065 ? openerp.web.views.get_object('page')
3066 : openerp.web.views.get_object('form');
3067 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3068 if (this.options.alternative_form_view) {
3069 this.view_form.set_embedded_view(this.options.alternative_form_view);
3071 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3072 this.view_form.on_loaded.add_last(function() {
3073 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3074 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3075 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3076 $nbutton.click(function() {
3077 self.view_form.do_save().then(function() {
3081 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3082 $cbutton.click(function() {
3085 if (self.options.readonly) {
3087 $cbutton.text(_t("Close"));
3089 self.view_form.do_show();
3091 this.dataset.on_write.add(this.on_write);
3095 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3096 read_ids: function() {
3097 if (this.fop.options.read_function) {
3098 return this.fop.options.read_function.apply(null, arguments);
3100 return this._super.apply(this, arguments);
3105 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3106 form_template: 'FieldReference',
3107 init: function(view, node) {
3108 this._super(view, node);
3109 this.fields_view = {
3112 selection: view.fields_view.fields[this.name].selection
3119 this.get_fields_values = view.get_fields_values;
3120 this.get_selected_ids = view.get_selected_ids;
3121 this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3122 this.dataset = this.view.dataset;
3123 this.widgets_counter = 0;
3124 this.view_id = 'reference_' + _.uniqueId();
3127 this.fields_order = [];
3128 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3132 this.reference_ready = true;
3133 this.selection.on_value_changed.add_last(this.on_selection_changed);
3134 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3138 this.m2o.on_ui_change.add_last(this.on_ui_change);
3140 on_nop: function() {
3142 on_selection_changed: function() {
3143 if (this.reference_ready) {
3144 var sel = this.selection.get_value();
3145 this.m2o.field.relation = sel;
3146 this.m2o.set_value(null);
3147 this.m2o.$element.toggle(sel !== false);
3152 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3153 this.selection.render_element();
3154 this.selection.start();
3155 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3156 this.m2o.render_element();
3159 is_valid: function() {
3160 return this.required === false || typeof(this.get_value()) === 'string';
3162 is_dirty: function() {
3163 return this.selection.is_dirty() || this.m2o.is_dirty();
3165 set_value: function(value) {
3167 this.reference_ready = false;
3168 var vals = [], sel_val, m2o_val;
3169 if (typeof(value) === 'string') {
3170 vals = value.split(',');
3172 sel_val = vals[0] || false;
3173 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3174 this.selection.set_value(sel_val);
3175 this.m2o.field.relation = sel_val;
3176 this.m2o.set_value(m2o_val);
3177 this.m2o.$element.toggle(sel_val !== false);
3178 this.reference_ready = true;
3180 get_value: function() {
3181 var model = this.selection.get_value(),
3182 id = this.m2o.get_value();
3183 if (typeof(model) === 'string' && typeof(id) === 'number') {
3184 return model + ',' + id;
3191 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3192 init: function(view, node) {
3193 this._super(view, node);
3194 this.iframe = this.element_id + '_iframe';
3195 this.binary_value = false;
3198 this._super.apply(this, arguments);
3199 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3200 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3201 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3203 human_filesize : function(size) {
3204 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3206 while (size >= 1024) {
3210 return size.toFixed(2) + ' ' + units[i];
3212 on_file_change: function(e) {
3213 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3214 // http://www.html5rocks.com/tutorials/file/dndfiles/
3215 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3216 window[this.iframe] = this.on_file_uploaded;
3217 if ($(e.target).val() != '') {
3218 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3219 this.$element.find('form.oe-binary-form').submit();
3220 this.$element.find('.oe-binary-progress').show();
3221 this.$element.find('.oe-binary').hide();
3224 on_file_uploaded: function(size, name, content_type, file_base64) {
3225 delete(window[this.iframe]);
3226 if (size === false) {
3227 this.do_warn("File Upload", "There was a problem while uploading your file");
3228 // TODO: use openerp web crashmanager
3229 console.warn("Error while uploading file : ", name);
3231 this.on_file_uploaded_and_valid.apply(this, arguments);
3232 this.on_ui_change();
3234 this.$element.find('.oe-binary-progress').hide();
3235 this.$element.find('.oe-binary').show();
3237 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3239 on_save_as: function() {
3241 this.session.get_file({
3242 url: '/web/binary/saveas_ajax',
3243 data: {data: JSON.stringify({
3244 model: this.view.dataset.model,
3245 id: (this.view.datarecord.id || ''),
3247 filename_field: (this.node.attrs.filename || ''),
3248 context: this.view.dataset.get_context()
3250 complete: $.unblockUI,
3251 error: openerp.webclient.crashmanager.on_rpc_error
3254 on_clear: function() {
3255 if (this.value !== false) {
3257 this.binary_value = false;
3258 this.on_ui_change();
3264 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3265 form_template: 'FieldBinaryFile',
3266 update_dom: function() {
3267 this._super.apply(this, arguments);
3268 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3269 this.$element.find('input[type=text]').prop('readonly', this.readonly);
3271 set_value: function(value) {
3272 this._super.apply(this, arguments);
3274 if (this.node.attrs.filename) {
3275 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3277 show_value = (value != null && value !== false) ? value : '';
3279 this.$element.find('input').eq(0).val(show_value);
3281 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3282 this.value = file_base64;
3283 this.binary_value = true;
3284 var show_value = name + " (" + this.human_filesize(size) + ")";
3285 this.$element.find('input').eq(0).val(show_value);
3286 this.set_filename(name);
3288 set_filename: function(value) {
3289 var filename = this.node.attrs.filename;
3290 if (this.view.fields[filename]) {
3291 this.view.fields[filename].set_value(value);
3292 this.view.fields[filename].on_ui_change();
3295 on_clear: function() {
3296 this._super.apply(this, arguments);
3297 this.$element.find('input').eq(0).val('');
3298 this.set_filename('');
3302 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3303 form_template: 'FieldBinaryImage',
3305 this._super.apply(this, arguments);
3306 this.$image = this.$element.find('img.oe-binary-image');
3308 update_dom: function() {
3309 this._super.apply(this, arguments);
3310 this.$element.find('.oe-binary').toggle(!this.readonly);
3312 set_value: function(value) {
3313 this._super.apply(this, arguments);
3314 this.set_image_maxwidth();
3315 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3316 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3317 this.$image.attr('src', url);
3319 set_image_maxwidth: function() {
3320 this.$image.css('max-width', this.$element.width());
3322 on_file_change: function() {
3323 this.set_image_maxwidth();
3324 this._super.apply(this, arguments);
3326 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3327 this.value = file_base64;
3328 this.binary_value = true;
3329 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3331 on_clear: function() {
3332 this._super.apply(this, arguments);
3333 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3337 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3338 form_template: "EmptyComponent",
3341 this.selected_value = null;
3345 set_value: function(value) {
3347 this.selected_value = value;
3351 render_list: function() {
3353 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3354 function(x) { return _.str.trim(x); });
3355 shown = _.select(shown, function(x) { return x.length > 0; });
3357 if (shown.length == 0) {
3358 this.to_show = this.field.selection;
3360 this.to_show = _.select(this.field.selection, function(x) {
3361 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3365 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3366 this.$element.html(content);
3368 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3369 var color = colors[this.selected_value];
3371 var elem = this.$element.find("li.oe-arrow-list-selected span");
3372 elem.css("border-color", color);
3373 if (this.check_white(color))
3374 elem.css("color", "white");
3375 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3376 elem.css("border-left-color", "rgba(0,0,0,0)");
3377 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3378 elem.css("border-color", "rgba(0,0,0,0)");
3379 elem.css("border-left-color", color);
3382 check_white: function(color) {
3383 var div = $("<div></div>");
3384 div.css("display", "none");
3385 div.css("color", color);
3386 div.appendTo($("body"));
3387 var ncolor = div.css("color");
3389 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3393 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3394 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3402 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3403 render_element: function () {
3404 var $root = $('<div class="oe_form_html_view">');
3405 this.render_children(this, $root);
3406 var rendered = $root.html();
3407 this.$element.html(rendered);
3409 render_children: function (object, $into) {
3411 fields = this.view.fields_view.fields;
3412 _(object.children).each(function (child) {
3413 if (typeof child === 'string') {
3415 } else if (child.tag === 'field') {
3416 var widget = instanciate_widget(self.view.registry.get_object('frame'),
3417 self.view, {tag: 'ueule', attrs: {}, children: [child] });
3418 widget.appendTo($into);
3420 var $child = $(document.createElement(child.tag))
3423 self.render_children(child, $child);
3431 * Registry of form widgets, called by :js:`openerp.web.FormView`
3433 openerp.web.form.widgets = new openerp.web.Registry({
3434 'frame' : 'openerp.web.form.WidgetFrame',
3435 'group' : 'openerp.web.form.WidgetGroup',
3436 'notebook' : 'openerp.web.form.WidgetNotebook',
3437 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3438 'separator' : 'openerp.web.form.WidgetSeparator',
3439 'label' : 'openerp.web.form.WidgetLabel',
3440 'button' : 'openerp.web.form.WidgetButton',
3441 'char' : 'openerp.web.form.FieldChar',
3442 'id' : 'openerp.web.form.FieldID',
3443 'email' : 'openerp.web.form.FieldEmail',
3444 'url' : 'openerp.web.form.FieldUrl',
3445 'text' : 'openerp.web.form.FieldText',
3446 'date' : 'openerp.web.form.FieldDate',
3447 'datetime' : 'openerp.web.form.FieldDatetime',
3448 'selection' : 'openerp.web.form.FieldSelection',
3449 'many2one' : 'openerp.web.form.FieldMany2One',
3450 'many2many' : 'openerp.web.form.FieldMany2Many',
3451 'one2many' : 'openerp.web.form.FieldOne2Many',
3452 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3453 'reference' : 'openerp.web.form.FieldReference',
3454 'boolean' : 'openerp.web.form.FieldBoolean',
3455 'float' : 'openerp.web.form.FieldFloat',
3456 'integer': 'openerp.web.form.FieldFloat',
3457 'float_time': 'openerp.web.form.FieldFloat',
3458 'progressbar': 'openerp.web.form.FieldProgressBar',
3459 'image': 'openerp.web.form.FieldBinaryImage',
3460 'binary': 'openerp.web.form.FieldBinaryFile',
3461 'statusbar': 'openerp.web.form.FieldStatus',
3462 'html': 'openerp.web.form.WidgetHtml'
3465 var instanciate_widget = function(claz, view, node, o1, o2) {
3466 var widget = new (claz)(view, node, o1, o2);
3467 widget.element_class = (['formview', view.view_id, widget.element_name,
3468 view.widgets_counter++].join("_")).replace(/[^\r\n\f0-9A-Za-z_-]/g, "_");
3469 view.widgets[widget.element_class] = widget;
3476 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: