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 this.fields_order = [];
95 this.fields_view = data;
96 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
98 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
100 this.$element.html(this.rendered);
101 _.each(this.widgets, function(w) {
104 this.$form_header = this.$element.find('.oe_form_header:first');
105 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
106 var action = $(this).data('pager-action');
107 self.on_pager_action(action);
110 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
111 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
113 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
114 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
115 this.sidebar.start();
116 this.sidebar.do_unfold();
117 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
118 this.sidebar.add_toolbar(this.fields_view.toolbar);
119 this.set_common_sidebar_sections(this.sidebar);
121 this.sidebar.add_section(_t('Customize'), 'customize');
122 this.sidebar.add_items('customize', [{
123 label: _t('Set Default'),
125 callback: function (item) {
126 item.form.open_defaults_dialog();
130 this.has_been_loaded.resolve();
133 do_load_state: function(state, warm) {
134 if (state.id && this.datarecord.id != state.id) {
135 if (!this.dataset.get_id_index(state.id)) {
136 this.dataset.ids.push(state.id);
138 this.dataset.select_id(state.id);
145 do_show: function () {
147 this.$element.show().css('visibility', 'hidden');
148 return this.has_been_loaded.pipe(function() {
150 if (self.dataset.index === null) {
151 // null index means we should start a new record
152 result = self.on_button_new();
154 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
155 context : { 'bin_size' : true }
156 }).pipe(self.on_record_loaded);
158 result.pipe(function() {
159 self.$element.css('visibility', 'visible');
162 self.sidebar.$element.show();
167 do_hide: function () {
170 this.sidebar.$element.hide();
173 on_record_loaded: function(record) {
174 var self = this, set_values = [];
176 this.do_warn("Form", "The record could not be found in the database.", true);
177 return $.Deferred().reject();
179 this.datarecord = record;
181 _(this.fields).each(function (field, f) {
183 var result = field.set_value(self.datarecord[f] || false);
184 set_values.push(result);
185 $.when(result).then(function() {
189 return $.when.apply(null, set_values).pipe(function() {
191 // New record: Second pass in order to trigger the onchanges
192 // respecting the fields order defined in the view
193 _.each(self.fields_order, function(field_name) {
194 if (record[field_name] !== undefined) {
195 var field = self.fields[field_name];
197 self.do_onchange(field);
201 self.on_form_changed();
202 self.is_initialized.resolve();
203 self.do_update_pager(record.id == null);
205 self.sidebar.attachments.do_update();
207 if (self.default_focus_field && !self.embedded_view) {
208 self.default_focus_field.focus();
211 self.do_push_state({id:record.id});
215 on_form_changed: function() {
216 for (var w in this.widgets) {
218 w.process_modifiers();
225 on_pager_action: function(action) {
226 if (this.can_be_discarded()) {
229 this.dataset.index = 0;
232 this.dataset.previous();
238 this.dataset.index = this.dataset.ids.length - 1;
244 do_update_pager: function(hide_index) {
245 var $pager = this.$form_header.find('div.oe_form_pager');
246 var index = hide_index ? '-' : this.dataset.index + 1;
247 $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
248 $pager.find('span.oe_pager_index').html(index);
249 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
251 parse_on_change: function (on_change, widget) {
253 var onchange = _.str.trim(on_change);
254 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
259 var method = call[1];
260 if (!_.str.trim(call[2])) {
261 return {method: method, args: [], context_index: null}
264 var argument_replacement = {
265 'False': function () {return false;},
266 'True': function () {return true;},
267 'None': function () {return null;},
268 'context': function (i) {
270 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
274 var parent_fields = null, context_index = null;
275 var args = _.map(call[2].split(','), function (a, i) {
276 var field = _.str.trim(a);
278 // literal constant or context
279 if (field in argument_replacement) {
280 return argument_replacement[field](i);
283 if (/^-?\d+(\.\d+)?$/.test(field)) {
284 return Number(field);
287 if (self.fields[field]) {
288 var value = self.fields[field].get_on_change_value();
289 return value == null ? false : value;
292 var splitted = field.split('.');
293 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
294 if (parent_fields === null) {
295 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
297 var p_val = parent_fields[_.str.trim(splitted[1])];
298 if (p_val !== undefined) {
299 return p_val == null ? false : p_val;
303 var first_char = field[0], last_char = field[field.length-1];
304 if ((first_char === '"' && last_char === '"')
305 || (first_char === "'" && last_char === "'")) {
306 return field.slice(1, -1);
309 throw new Error("Could not get field with name '" + field +
310 "' for onchange '" + onchange + "'");
316 context_index: context_index
319 do_onchange: function(widget, processed) {
321 return this.on_change_mutex.exec(function() {
323 var response = {}, can_process_onchange = $.Deferred();
324 processed = processed || [];
325 processed.push(widget.name);
326 var on_change = widget.node.attrs.on_change;
328 var change_spec = self.parse_on_change(on_change, widget);
331 url: '/web/dataset/onchange',
334 can_process_onchange = self.rpc(ajax, {
335 model: self.dataset.model,
336 method: change_spec.method,
337 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
338 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
339 }).then(function(r) {
340 _.extend(response, r);
343 console.warn("Wrong on_change format", on_change);
346 // fail if onchange failed
347 if (can_process_onchange.isRejected()) {
348 return can_process_onchange;
351 if (widget.field['change_default']) {
352 var fieldname = widget.name, value;
353 if (response.value && (fieldname in response.value)) {
354 // Use value from onchange if onchange executed
355 value = response.value[fieldname];
357 // otherwise get form value for field
358 value = self.fields[fieldname].get_on_change_value();
360 var condition = fieldname + '=' + value;
363 can_process_onchange = self.rpc({
364 url: '/web/dataset/call',
368 method: 'get_defaults',
369 args: [self.model, condition]
370 }).then(function (results) {
371 if (!results.length) { return; }
372 if (!response.value) {
375 for(var i=0; i<results.length; ++i) {
376 // [whatever, key, value]
377 var triplet = results[i];
378 response.value[triplet[1]] = triplet[2];
383 if (can_process_onchange.isRejected()) {
384 return can_process_onchange;
387 return self.on_processed_onchange(response, processed);
390 return $.Deferred().reject();
394 on_processed_onchange: function(response, processed) {
396 var result = response;
398 for (var f in result.value) {
399 if (!result.value.hasOwnProperty(f)) { continue; }
400 var field = this.fields[f];
401 // If field is not defined in the view, just ignore it
403 var value = result.value[f];
404 if (field.get_value() != value) {
405 field.set_value(value);
407 if (!_.contains(processed, field.name)) {
408 this.do_onchange(field, processed);
413 this.on_form_changed();
415 if (!_.isEmpty(result.warning)) {
416 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
419 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
424 function edit_domain(node) {
425 var new_domain = result.domain[node.attrs.name];
427 node.attrs.domain = new_domain;
429 _(node.children).each(edit_domain);
431 edit_domain(this.fields_view.arch);
433 return $.Deferred().resolve();
436 return $.Deferred().reject();
439 on_button_save: function() {
441 return this.do_save().then(function(result) {
442 self.do_prev_view({'created': result.created, 'default': 'page'});
445 on_button_cancel: function() {
446 return this.do_prev_view({'default': 'page'});
448 on_button_new: function() {
450 var def = $.Deferred();
451 $.when(this.has_been_loaded).then(function() {
452 if (self.can_be_discarded()) {
453 var keys = _.keys(self.fields_view.fields);
455 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
459 self.on_record_loaded({}).then(function() {
465 return def.promise();
467 can_be_discarded: function() {
468 return true; // FIXME: Disabled until the page view and button refactoring is done
469 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
472 * Triggers saving the form's record. Chooses between creating a new
473 * record or saving an existing one depending on whether the record
474 * already has an id property.
476 * @param {Function} success callback on save success
477 * @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)
479 do_save: function(success, prepend_on_create) {
481 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
483 var form_invalid = false,
485 first_invalid_field = null;
486 for (var f in self.fields) {
491 if (!first_invalid_field) {
492 first_invalid_field = f;
494 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
495 // Special case 'id' field, do not save this field
496 // on 'create' : save all non readonly fields
497 // on 'edit' : save non readonly modified fields
498 values[f.name] = f.get_value();
502 first_invalid_field.focus();
504 return $.Deferred().reject();
507 if (!self.datarecord.id) {
508 //console.log("FormView(", self, ") : About to create", values);
509 save_deferral = self.dataset.create(values).pipe(function(r) {
510 return self.on_created(r, undefined, prepend_on_create);
512 } else if (_.isEmpty(values)) {
513 //console.log("FormView(", self, ") : Nothing to save");
514 save_deferral = $.Deferred().resolve({}).promise();
516 //console.log("FormView(", self, ") : About to save", values);
517 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
518 return self.on_saved(r);
521 return save_deferral.then(success);
525 return $.Deferred().reject();
529 on_invalid: function() {
531 _.each(this.fields, function(f) {
533 msg += "<li>" + f.string + "</li>";
537 this.do_warn("The following fields are invalid :", msg);
539 on_saved: function(r, success) {
541 // should not happen in the server, but may happen for internal purpose
542 return $.Deferred().reject();
544 return $.when(this.reload()).pipe(function () {
545 return $.when(r).then(success); }, null);
549 * Updates the form' dataset to contain the new record:
551 * * Adds the newly created record to the current dataset (at the end by
553 * * Selects that record (sets the dataset's index to point to the new
555 * * Updates the pager and sidebar displays
558 * @param {Function} success callback to execute after having updated the dataset
559 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
561 on_created: function(r, success, prepend_on_create) {
563 // should not happen in the server, but may happen for internal purpose
564 return $.Deferred().reject();
566 this.datarecord.id = r.result;
567 if (!prepend_on_create) {
568 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
569 this.dataset.index = this.dataset.ids.length - 1;
571 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
572 this.dataset.index = 0;
574 this.do_update_pager();
576 this.sidebar.attachments.do_update();
578 //openerp.log("The record has been created with id #" + this.datarecord.id);
580 return $.when(_.extend(r, {created: true})).then(success);
583 on_action: function (action) {
584 console.debug('Executing action', action);
588 return this.reload_mutex.exec(function() {
589 if (self.dataset.index == null || self.dataset.index < 0) {
590 return $.when(self.on_button_new());
592 return self.dataset.read_index(_.keys(self.fields_view.fields), {
593 context : { 'bin_size' : true }
594 }).pipe(self.on_record_loaded);
598 get_fields_values: function(blacklist) {
599 blacklist = blacklist || [];
601 var ids = this.get_selected_ids();
602 values["id"] = ids.length > 0 ? ids[0] : false;
603 _.each(this.fields, function(value, key) {
604 if (_.include(blacklist, key))
606 var val = value.get_value();
611 get_selected_ids: function() {
612 var id = this.dataset.ids[this.dataset.index];
613 return id ? [id] : [];
615 recursive_save: function() {
617 return $.when(this.do_save()).pipe(function(res) {
618 if (self.dataset.parent_view)
619 return self.dataset.parent_view.recursive_save();
622 is_dirty: function() {
623 return _.any(this.fields, function (value) {
624 return value.is_dirty();
627 is_interactible_record: function() {
628 var id = this.datarecord.id;
630 if (this.options.not_interactible_on_create)
632 } else if (typeof(id) === "string") {
633 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
638 sidebar_context: function () {
639 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
641 open_defaults_dialog: function () {
643 var fields = _.chain(this.fields)
644 .map(function (field, name) {
645 var value = field.get_value();
646 // ignore fields which are empty, invisible, readonly, o2m
651 || field.field.type === 'one2many'
652 || field.field.type === 'many2many') {
656 switch(field.field.type) {
658 displayed = _(field.values).find(function (option) {
659 return option[0] === value;
663 displayed = field.value[1] || value;
671 string: field.string,
673 displayed: displayed,
674 // convert undefined to false
675 change_default: !!field.field.change_default
679 .sortBy(function (field) { return field.string; })
681 var conditions = _.chain(fields)
682 .filter(function (field) { return field.change_default; })
685 var d = new openerp.web.Dialog(this, {
686 title: _t("Set Default"),
689 conditions: conditions
692 {text: _t("Close"), click: function () { d.close(); }},
693 {text: _t("Save default"), click: function () {
694 var $defaults = d.$element.find('#formview_default_fields');
695 var field_to_set = $defaults.val();
697 $defaults.parent().addClass('invalid');
700 var condition = d.$element.find('#formview_default_conditions').val(),
701 all_users = d.$element.find('#formview_default_all').is(':checked');
702 new openerp.web.DataSet(self, 'ir.values').call(
706 self.fields[field_to_set].get_value(),
710 ]).then(function () { d.close(); });
714 d.template = 'FormView.set_default';
718 openerp.web.FormDialog = openerp.web.Dialog.extend({
719 init: function(parent, options, view_id, dataset) {
720 this._super(parent, options);
721 this.dataset = dataset;
722 this.view_id = view_id;
727 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
731 this.form.appendTo(this.$element);
732 this.form.on_created.add_last(this.on_form_dialog_saved);
733 this.form.on_saved.add_last(this.on_form_dialog_saved);
736 select_id: function(id) {
737 if (this.form.dataset.select_id(id)) {
738 return this.form.do_show();
740 this.do_warn("Could not find id in dataset");
741 return $.Deferred().reject();
744 on_form_dialog_saved: function(r) {
750 openerp.web.form = {};
752 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
753 init: function(parent, form_view) {
754 var $section = parent.add_section(_t('Attachments'), 'attachments');
755 this.$div = $('<div class="oe-sidebar-attachments"></div>');
756 $section.append(this.$div);
758 this._super(parent, $section.attr('id'));
759 this.view = form_view;
761 do_update: function() {
762 if (!this.view.datarecord.id) {
763 this.on_attachments_loaded([]);
765 (new openerp.web.DataSetSearch(
766 this, 'ir.attachment', this.view.dataset.get_context(),
768 ['res_model', '=', this.view.dataset.model],
769 ['res_id', '=', this.view.datarecord.id],
770 ['type', 'in', ['binary', 'url']]
771 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
774 on_attachments_loaded: function(attachments) {
775 this.attachments = attachments;
776 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
777 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
778 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
780 on_attachment_changed: function(e) {
781 window[this.element_id + '_iframe'] = this.do_update;
782 var $e = $(e.target);
783 if ($e.val() != '') {
784 this.$element.find('form.oe-binary-form').submit();
785 $e.parent().find('input[type=file]').prop('disabled', true);
786 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
789 on_attachment_delete: function(e) {
790 var self = this, $e = $(e.currentTarget);
791 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
792 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
793 this.rpc('/web/dataset/unlink', {
794 model: 'ir.attachment',
795 ids: [parseInt($e.attr('data-id'))]
797 $e.parent().remove();
798 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
804 openerp.web.form.compute_domain = function(expr, fields) {
806 for (var i = expr.length - 1; i >= 0; i--) {
808 if (ex.length == 1) {
809 var top = stack.pop();
812 stack.push(stack.pop() || top);
815 stack.push(stack.pop() && top);
821 throw new Error(_.str.sprintf(
822 _t("Unknown operator %s in domain %s"),
823 ex, JSON.stringify(expr)));
827 var field = fields[ex[0]];
829 throw new Error(_.str.sprintf(
830 _t("Unknown field %s in domain %s"),
831 ex[0], JSON.stringify(expr)));
833 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
837 switch (op.toLowerCase()) {
840 stack.push(field_value == val);
844 stack.push(field_value != val);
847 stack.push(field_value < val);
850 stack.push(field_value > val);
853 stack.push(field_value <= val);
856 stack.push(field_value >= val);
859 if (!_.isArray(val)) val = [val];
860 stack.push(_(val).contains(field_value));
863 if (!_.isArray(val)) val = [val];
864 stack.push(!_(val).contains(field_value));
868 _t("Unsupported operator %s in domain %s"),
869 op, JSON.stringify(expr));
872 return _.all(stack, _.identity);
875 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
878 * @constructs openerp.web.form.Widget
879 * @extends openerp.web.OldWidget
884 init: function(view, node) {
887 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
888 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
889 this.type = this.type || node.tag;
890 this.element_name = this.element_name || this.type;
891 this.element_class = [
892 'formview', this.view.view_id, this.element_name,
893 this.view.widgets_counter++].join("_");
897 this.view.widgets[this.element_class] = this;
898 this.children = node.children;
899 this.colspan = parseInt(node.attrs.colspan || 1, 10);
900 this.decrease_max_width = 0;
902 this.string = this.string || node.attrs.string;
903 this.help = this.help || node.attrs.help;
904 this.invisible = this.modifiers['invisible'] === true;
905 this.classname = 'oe_form_' + this.type;
907 this.align = parseFloat(this.node.attrs.align);
908 if (isNaN(this.align) || this.align === 1) {
909 this.align = 'right';
910 } else if (this.align === 0) {
913 this.align = 'center';
917 this.width = this.node.attrs.width;
920 this.$element = this.view.$element.find(
921 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
924 this._super.apply(this, arguments);
927 process_modifiers: function() {
928 var compute_domain = openerp.web.form.compute_domain;
929 for (var a in this.modifiers) {
930 this[a] = compute_domain(this.modifiers[a], this.view.fields);
933 update_dom: function() {
934 this.$element.toggle(!this.invisible);
937 var template = this.template;
938 return QWeb.render(template, { "widget": this });
940 do_attach_tooltip: function(widget, trigger, options) {
941 widget = widget || this;
942 trigger = trigger || this.$element;
948 var template = widget.template + '.tooltip';
949 if (!QWeb.has_template(template)) {
950 template = 'WidgetLabel.tooltip';
952 return QWeb.render(template, {
953 debug: openerp.connection.debug,
956 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
961 trigger.tipsy(options);
963 _build_view_fields_values: function(blacklist) {
964 var a_dataset = this.view.dataset;
965 var fields_values = this.view.get_fields_values(blacklist);
966 var active_id = a_dataset.ids[a_dataset.index];
967 _.extend(fields_values, {
968 active_id: active_id || false,
969 active_ids: active_id ? [active_id] : [],
970 active_model: a_dataset.model,
973 if (a_dataset.parent_view) {
974 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
976 return fields_values;
978 _build_eval_context: function(blacklist) {
979 var a_dataset = this.view.dataset;
980 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
983 * Builds a new context usable for operations related to fields by merging
984 * the fields'context with the action's context.
986 build_context: function(blacklist) {
987 // only use the model's context if there is not context on the node
988 var v_context = this.node.attrs.context;
990 v_context = (this.field || {}).context || {};
993 if (v_context.__ref || true) { //TODO: remove true
994 var fields_values = this._build_eval_context(blacklist);
995 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
999 build_domain: function() {
1000 var f_domain = this.field.domain || [];
1001 var n_domain = this.node.attrs.domain || null;
1002 // if there is a domain on the node, overrides the model's domain
1003 var final_domain = n_domain !== null ? n_domain : f_domain;
1004 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1005 var fields_values = this._build_eval_context();
1006 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1008 return final_domain;
1012 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1013 template: 'WidgetFrame',
1014 init: function(view, node) {
1015 this._super(view, node);
1016 this.columns = parseInt(node.attrs.col || 4, 10);
1021 for (var i = 0; i < node.children.length; i++) {
1022 var n = node.children[i];
1023 if (n.tag == "newline") {
1026 this.handle_node(n);
1029 this.set_row_cells_with(this.table[this.table.length - 1]);
1031 add_row: function(){
1032 if (this.table.length) {
1033 this.set_row_cells_with(this.table[this.table.length - 1]);
1036 this.table.push(row);
1041 set_row_cells_with: function(row) {
1044 row_length = row.length;
1045 for (var i = 0; i < row.length; i++) {
1046 if (row[i].always_invisible) {
1049 bypass += row[i].width === undefined ? 0 : 1;
1050 max_width -= row[i].decrease_max_width;
1053 var size_unit = Math.round(max_width / (this.columns - bypass)),
1055 for (var i = 0; i < row.length; i++) {
1057 if (w.always_invisible) {
1060 colspan_sum += w.colspan;
1061 if (w.width === undefined) {
1062 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1064 w.width = width + '%';
1068 handle_node: function(node) {
1070 if (node.tag == 'field') {
1071 type = this.view.fields_view.fields[node.attrs.name] || {};
1072 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1073 // This way we can retain backward compatibility between addons and old clients
1074 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1075 node.attrs.nolabel = '1';
1078 var widget = new (this.view.registry.get_any(
1079 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1080 if (node.tag == 'field') {
1081 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1082 this.view.default_focus_field = widget;
1084 if (node.attrs.nolabel != '1') {
1085 var label = new (this.view.registry.get_object('label')) (this.view, node);
1086 label["for"] = widget;
1087 this.add_widget(label, widget.colspan + 1);
1090 this.add_widget(widget);
1092 add_widget: function(widget, colspan) {
1093 var current_row = this.table[this.table.length - 1];
1094 if (!widget.always_invisible) {
1095 colspan = colspan || widget.colspan;
1096 if (current_row.length && (this.x + colspan) > this.columns) {
1097 current_row = this.add_row();
1099 this.x += widget.colspan;
1101 current_row.push(widget);
1106 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1107 template: 'WidgetGroup'
1110 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1111 template: 'WidgetNotebook',
1112 init: function(view, node) {
1113 this._super(view, node);
1115 for (var i = 0; i < node.children.length; i++) {
1116 var n = node.children[i];
1117 if (n.tag == "page") {
1118 var page = new (this.view.registry.get_object('notebookpage'))(
1119 this.view, n, this, this.pages.length);
1120 this.pages.push(page);
1126 this._super.apply(this, arguments);
1127 this.$element.find('> ul > li').each(function (index, tab_li) {
1128 var page = self.pages[index],
1129 id = _.uniqueId(self.element_name + '-');
1130 page.element_id = id;
1131 $(tab_li).find('a').attr('href', '#' + id);
1133 this.$element.find('> div').each(function (index, page) {
1134 page.id = self.pages[index].element_id;
1136 this.$element.tabs();
1137 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1138 if (openerp.connection.debug) {
1139 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1144 do_select_first_visible_tab: function() {
1145 for (var i = 0; i < this.pages.length; i++) {
1146 var page = this.pages[i];
1147 if (page.invisible === false) {
1148 this.$element.tabs('select', page.index);
1155 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1156 template: 'WidgetNotebookPage',
1157 init: function(view, node, notebook, index) {
1158 this.notebook = notebook;
1160 this.element_name = 'page_' + index;
1161 this._super(view, node);
1164 this._super.apply(this, arguments);
1165 this.$element_tab = this.notebook.$element.find(
1166 '> ul > li:eq(' + this.index + ')');
1168 update_dom: function() {
1169 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1170 this.notebook.do_select_first_visible_tab();
1172 this.$element_tab.toggle(!this.invisible);
1173 this.$element.toggle(!this.invisible);
1177 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1178 template: 'WidgetSeparator',
1179 init: function(view, node) {
1180 this._super(view, node);
1181 this.orientation = node.attrs.orientation || 'horizontal';
1182 if (this.orientation === 'vertical') {
1185 this.classname += '_' + this.orientation;
1189 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1190 template: 'WidgetButton',
1191 init: function(view, node) {
1192 this._super(view, node);
1193 this.force_disabled = false;
1195 // We don't have button key bindings in the webclient
1196 this.string = this.string.replace(/_/g, '');
1198 if (node.attrs.default_focus == '1') {
1199 // TODO fme: provide enter key binding to widgets
1200 this.view.default_focus_button = this;
1204 this._super.apply(this, arguments);
1205 this.$element.find("button").click(this.on_click);
1206 if (this.help || openerp.connection.debug) {
1207 this.do_attach_tooltip();
1210 on_click: function() {
1212 this.force_disabled = true;
1213 this.check_disable();
1214 this.execute_action().always(function() {
1215 self.force_disabled = false;
1216 self.check_disable();
1219 execute_action: function() {
1221 var exec_action = function() {
1222 if (self.node.attrs.confirm) {
1223 var def = $.Deferred();
1224 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1225 title: _t('Confirm'),
1228 {text: _t("Cancel"), click: function() {
1230 $(this).dialog("close");
1233 {text: _t("Ok"), click: function() {
1234 self.on_confirmed().then(function() {
1237 $(this).dialog("close");
1242 return def.promise();
1244 return self.on_confirmed();
1247 if (!this.node.attrs.special) {
1248 return this.view.recursive_save().pipe(exec_action);
1250 return exec_action();
1253 on_confirmed: function() {
1256 var context = this.node.attrs.context;
1257 if (context && context.__ref) {
1258 context = new openerp.web.CompoundContext(context);
1259 context.set_eval_context(this._build_eval_context());
1262 return this.view.do_execute_action(
1263 _.extend({}, this.node.attrs, {context: context}),
1264 this.view.dataset, this.view.datarecord.id, function () {
1268 update_dom: function() {
1269 this._super.apply(this, arguments);
1270 this.check_disable();
1272 check_disable: function() {
1273 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1274 this.$element.find('button').prop('disabled', disabled);
1275 this.$element.find("button").css('color', disabled ? 'grey' : '');
1279 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1280 template: 'WidgetLabel',
1281 init: function(view, node) {
1282 this.element_name = 'label_' + node.attrs.name;
1284 this._super(view, node);
1286 if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1287 this.string = this.node.children[0];
1288 this.align = 'left';
1291 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1292 this.template = "WidgetParagraph";
1293 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1294 // Widgets default to right-aligned, but paragraph defaults to
1296 if (isNaN(parseFloat(this.node.attrs.align))) {
1297 this.align = 'left';
1300 this.multilines = this.string && _.str.lines(this.string).length > 1;
1304 this.decrease_max_width = 1;
1308 render: function () {
1309 if (this['for'] && this.type !== 'label') {
1310 return QWeb.render(this.template, {widget: this['for']});
1312 // Actual label widgets should not have a false and have type label
1313 return QWeb.render(this.template, {widget: this});
1318 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1319 this.do_attach_tooltip(self['for']);
1321 this.$element.find("label").dblclick(function() {
1322 var widget = self['for'] || self;
1323 openerp.log(widget.element_class , widget);
1329 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1331 * @constructs openerp.web.form.Field
1332 * @extends openerp.web.form.Widget
1337 init: function(view, node) {
1338 this.name = node.attrs.name;
1339 this.value = undefined;
1340 view.fields[this.name] = this;
1341 view.fields_order.push(this.name);
1342 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1343 this.element_name = "field_" + this.name + "_" + this.type;
1345 this._super(view, node);
1347 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1350 this.field = view.fields_view.fields[node.attrs.name] || {};
1351 this.string = node.attrs.string || this.field.string;
1352 this.help = node.attrs.help || this.field.help;
1353 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1354 this.readonly = this.modifiers['readonly'] === true;
1355 this.required = this.modifiers['required'] === true;
1356 this.invalid = this.dirty = false;
1358 this.classname = 'oe_form_field_' + this.type;
1361 this._super.apply(this, arguments);
1362 if (this.field.translate) {
1363 this.view.translatable_fields.push(this);
1364 this.$element.find('.oe_field_translate').click(this.on_translate);
1366 if (this.nolabel && openerp.connection.debug) {
1367 this.do_attach_tooltip(this, this.$element);
1370 set_value: function(value) {
1372 this.invalid = false;
1374 this.on_value_changed();
1376 set_value_from_ui: function() {
1377 this.on_value_changed();
1379 on_value_changed: function() {
1381 on_translate: function() {
1382 this.view.open_translate_dialog(this);
1384 get_value: function() {
1387 is_valid: function() {
1388 return !this.invalid;
1390 is_dirty: function() {
1391 return this.dirty && !this.readonly;
1393 get_on_change_value: function() {
1394 return this.get_value();
1396 update_dom: function(show_invalid) {
1397 this._super.apply(this, arguments);
1398 if (this.field.translate) {
1399 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1401 if (!this.disable_utility_classes) {
1402 this.$element.toggleClass('disabled', this.readonly);
1403 this.$element.toggleClass('required', this.required);
1405 this.$element.toggleClass('invalid', !this.is_valid());
1409 on_ui_change: function() {
1412 if (this.is_valid()) {
1413 this.set_value_from_ui();
1414 this.view.do_onchange(this);
1415 this.view.on_form_changed();
1417 this.update_dom(true);
1420 validate: function() {
1421 this.invalid = false;
1423 focus: function($element) {
1425 setTimeout(function() {
1433 get_definition_options: function() {
1434 if (!this.definition_options) {
1435 var str = this.node.attrs.options || '{}';
1436 this.definition_options = JSON.parse(str);
1438 return this.definition_options;
1442 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1443 template: 'FieldChar',
1444 init: function (view, node) {
1445 this._super(view, node);
1446 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1449 this._super.apply(this, arguments);
1450 this.$element.find('input').change(this.on_ui_change);
1452 set_value: function(value) {
1453 this._super.apply(this, arguments);
1454 var show_value = openerp.web.format_value(value, this, '');
1455 this.$element.find('input').val(show_value);
1458 update_dom: function() {
1459 this._super.apply(this, arguments);
1460 this.$element.find('input').prop('readonly', this.readonly);
1462 set_value_from_ui: function() {
1463 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1466 validate: function() {
1467 this.invalid = false;
1469 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1470 this.invalid = this.required && value === '';
1472 this.invalid = true;
1475 focus: function($element) {
1476 this._super($element || this.$element.find('input:first'));
1480 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1481 update_dom: function() {
1482 this._super.apply(this, arguments);
1483 this.$element.find('input').prop('readonly', true);
1487 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1488 template: 'FieldEmail',
1490 this._super.apply(this, arguments);
1491 this.$element.find('button').click(this.on_button_clicked);
1493 on_button_clicked: function() {
1494 if (!this.value || !this.is_valid()) {
1495 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1497 location.href = 'mailto:' + this.value;
1502 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1503 template: 'FieldUrl',
1505 this._super.apply(this, arguments);
1506 this.$element.find('button').click(this.on_button_clicked);
1508 on_button_clicked: function() {
1510 this.do_warn("Resource error", "This resource is empty");
1512 window.open(this.value);
1517 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1518 init: function (view, node) {
1519 this._super(view, node);
1520 if (node.attrs.digits) {
1521 this.parse_digits(node.attrs.digits);
1523 this.digits = view.fields_view.fields[node.attrs.name].digits;
1526 parse_digits: function (digits_attr) {
1527 // could use a Python parser instead.
1528 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1529 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1531 set_value: function(value) {
1532 if (value === false || value === undefined) {
1533 // As in GTK client, floats default to 0
1536 this._super.apply(this, [value]);
1540 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1541 template: "web.datetimepicker",
1542 jqueryui_object: 'datetimepicker',
1543 type_of_date: "datetime",
1544 init: function(parent) {
1545 this._super(parent);
1546 this.name = parent.name;
1550 this.$input = this.$element.find('input.oe_datepicker_master');
1551 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1552 this.$input.change(this.on_change);
1554 onSelect: this.on_picker_select,
1558 showButtonPanel: true
1560 this.$element.find('img.oe_datepicker_trigger').click(function() {
1561 if (!self.readonly && !self.picker('widget').is(':visible')) {
1562 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1563 self.$input_picker.show();
1564 self.picker('show');
1565 self.$input_picker.hide();
1568 this.set_readonly(false);
1571 picker: function() {
1572 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1574 on_picker_select: function(text, instance) {
1575 var date = this.picker('getDate');
1576 this.$input.val(date ? this.format_client(date) : '').change();
1578 set_value: function(value) {
1580 this.$input.val(value ? this.format_client(value) : '');
1582 get_value: function() {
1585 set_value_from_ui: function() {
1586 var value = this.$input.val() || false;
1587 this.value = this.parse_client(value);
1589 set_readonly: function(readonly) {
1590 this.readonly = readonly;
1591 this.$input.prop('readonly', this.readonly);
1592 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1594 is_valid: function(required) {
1595 var value = this.$input.val();
1600 this.parse_client(value);
1607 parse_client: function(v) {
1608 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1610 format_client: function(v) {
1611 return openerp.web.format_value(v, {"widget": this.type_of_date});
1613 on_change: function() {
1614 if (this.is_valid()) {
1615 this.set_value_from_ui();
1620 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1621 jqueryui_object: 'datepicker',
1622 type_of_date: "date"
1625 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1626 template: "EmptyComponent",
1627 build_widget: function() {
1628 return new openerp.web.DateTimeWidget(this);
1632 this._super.apply(this, arguments);
1633 this.datewidget = this.build_widget();
1634 this.datewidget.on_change.add_last(this.on_ui_change);
1635 this.datewidget.appendTo(this.$element);
1637 set_value: function(value) {
1639 this.datewidget.set_value(value);
1641 get_value: function() {
1642 return this.datewidget.get_value();
1644 update_dom: function() {
1645 this._super.apply(this, arguments);
1646 this.datewidget.set_readonly(this.readonly);
1648 validate: function() {
1649 this.invalid = !this.datewidget.is_valid(this.required);
1651 focus: function($element) {
1652 this._super($element || this.datewidget.$input);
1656 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1657 build_widget: function() {
1658 return new openerp.web.DateWidget(this);
1662 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1663 template: 'FieldText',
1665 this._super.apply(this, arguments);
1666 this.$element.find('textarea').change(this.on_ui_change);
1667 this.resized = false;
1669 set_value: function(value) {
1670 this._super.apply(this, arguments);
1671 var show_value = openerp.web.format_value(value, this, '');
1672 this.$element.find('textarea').val(show_value);
1673 if (!this.resized && this.view.options.resize_textareas) {
1674 this.do_resize(this.view.options.resize_textareas);
1675 this.resized = true;
1678 update_dom: function() {
1679 this._super.apply(this, arguments);
1680 this.$element.find('textarea').prop('readonly', this.readonly);
1682 set_value_from_ui: function() {
1683 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1686 validate: function() {
1687 this.invalid = false;
1689 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1690 this.invalid = this.required && value === '';
1692 this.invalid = true;
1695 focus: function($element) {
1696 this._super($element || this.$element.find('textarea:first'));
1698 do_resize: function(max_height) {
1699 max_height = parseInt(max_height, 10);
1700 var $input = this.$element.find('textarea'),
1701 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1703 $div.text($input.val());
1704 _.each('font-family,font-size,white-space'.split(','), function(style) {
1705 $div.css(style, $input.css(style));
1707 $div.appendTo($('body'));
1708 new_height = $div.height();
1709 if (new_height < 90) {
1712 if (!isNaN(max_height) && new_height > max_height) {
1713 new_height = max_height;
1716 $input.height(new_height);
1719 this.resized = false;
1723 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1724 template: 'FieldBoolean',
1727 this._super.apply(this, arguments);
1728 this.$element.find('input').click(self.on_ui_change);
1730 set_value: function(value) {
1731 this._super.apply(this, arguments);
1732 this.$element.find('input')[0].checked = value;
1734 set_value_from_ui: function() {
1735 this.value = this.$element.find('input').is(':checked');
1738 update_dom: function() {
1739 this._super.apply(this, arguments);
1740 this.$element.find('input').prop('disabled', this.readonly);
1742 focus: function($element) {
1743 this._super($element || this.$element.find('input:first'));
1747 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1748 template: 'FieldProgressBar',
1750 this._super.apply(this, arguments);
1751 this.$element.find('div').progressbar({
1753 disabled: this.readonly
1756 set_value: function(value) {
1757 this._super.apply(this, arguments);
1758 var show_value = Number(value);
1759 if (isNaN(show_value)) {
1762 var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1763 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1767 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1768 // to replace view editor
1771 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1772 template: 'FieldSelection',
1773 init: function(view, node) {
1775 this._super(view, node);
1776 this.values = _.clone(this.field.selection);
1777 _.each(this.values, function(v, i) {
1778 if (v[0] === false && v[1] === '') {
1779 self.values.splice(i, 1);
1782 this.values.unshift([false, '']);
1785 // Flag indicating whether we're in an event chain containing a change
1786 // event on the select, in order to know what to do on keyup[RETURN]:
1787 // * If the user presses [RETURN] as part of changing the value of a
1788 // selection, we should just let the value change and not let the
1789 // event broadcast further (e.g. to validating the current state of
1790 // the form in editable list view, which would lead to saving the
1791 // current row or switching to the next one)
1792 // * If the user presses [RETURN] with a select closed (side-effect:
1793 // also if the user opened the select and pressed [RETURN] without
1794 // changing the selected value), takes the action as validating the
1796 var ischanging = false;
1797 this._super.apply(this, arguments);
1798 this.$element.find('select')
1799 .change(this.on_ui_change)
1800 .change(function () { ischanging = true; })
1801 .click(function () { ischanging = false; })
1802 .keyup(function (e) {
1803 if (e.which !== 13 || !ischanging) { return; }
1804 e.stopPropagation();
1808 set_value: function(value) {
1809 value = value === null ? false : value;
1810 value = value instanceof Array ? value[0] : value;
1813 for (var i = 0, ii = this.values.length; i < ii; i++) {
1814 if (this.values[i][0] === value) index = i;
1816 this.$element.find('select')[0].selectedIndex = index;
1818 set_value_from_ui: function() {
1819 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1822 update_dom: function() {
1823 this._super.apply(this, arguments);
1824 this.$element.find('select').prop('disabled', this.readonly);
1826 validate: function() {
1827 var value = this.values[this.$element.find('select')[0].selectedIndex];
1828 this.invalid = !(value && !(this.required && value[0] === false));
1830 focus: function($element) {
1831 this._super($element || this.$element.find('select:first'));
1835 // jquery autocomplete tweak to allow html
1837 var proto = $.ui.autocomplete.prototype,
1838 initSource = proto._initSource;
1840 function filter( array, term ) {
1841 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1842 return $.grep( array, function(value) {
1843 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1848 _initSource: function() {
1849 if ( this.options.html && $.isArray(this.options.source) ) {
1850 this.source = function( request, response ) {
1851 response( filter( this.options.source, request.term ) );
1854 initSource.call( this );
1858 _renderItem: function( ul, item) {
1859 return $( "<li></li>" )
1860 .data( "item.autocomplete", item )
1861 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1867 openerp.web.form.dialog = function(content, options) {
1868 options = _.extend({
1873 var dialog = new openerp.web.Dialog(null, options, content).open();
1874 return dialog.$element;
1877 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1878 template: 'FieldMany2One',
1879 init: function(view, node) {
1880 this._super(view, node);
1883 this.cm_id = _.uniqueId('m2o_cm_');
1884 this.last_search = [];
1885 this.tmp_value = undefined;
1890 this.$input = this.$element.find("input");
1891 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1892 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1895 var init_context_menu_def = $.Deferred().then(function(e) {
1896 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1897 rdataset.call("get", ['action', 'client_action_relate',
1898 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1899 .then(function(result) {
1900 self.related_entries = result;
1902 var $cmenu = $("#" + self.cm_id);
1903 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1905 bindings[self.cm_id + "_search"] = function() {
1906 self._search_create_popup("search");
1908 bindings[self.cm_id + "_create"] = function() {
1909 self._search_create_popup("form");
1911 bindings[self.cm_id + "_open"] = function() {
1915 var pop = new openerp.web.form.FormOpenPopup(self.view);
1917 self.field.relation,
1919 self.build_context(),
1921 title: _t("Open: ") + (self.string || self.name)
1924 pop.on_write_completed.add_last(function() {
1925 self.set_value(self.value[0]);
1928 _.each(_.range(self.related_entries.length), function(i) {
1929 bindings[self.cm_id + "_related_" + i] = function() {
1930 self.open_related(self.related_entries[i]);
1933 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1934 bindings: bindings, itemStyle: {"color": ""},
1935 onContextMenu: function() {
1937 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1939 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1941 if (!self.readonly) {
1942 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1944 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1947 }, menuStyle: {width: "200px"}
1949 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1952 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1953 this.$menu_btn.click(ctx_callback);
1955 // some behavior for input
1956 this.$input.keyup(function() {
1957 if (self.$input.val() === "") {
1958 self._change_int_value(null);
1959 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1960 self._change_int_value(undefined);
1963 this.$drop_down.click(function() {
1966 if (self.$input.autocomplete("widget").is(":visible")) {
1967 self.$input.autocomplete("close");
1970 self.$input.autocomplete("search", "");
1972 self.$input.autocomplete("search");
1974 self.$input.focus();
1977 var anyoneLoosesFocus = function() {
1978 if (!self.$input.is(":focus") &&
1979 !self.$input.autocomplete("widget").is(":visible") &&
1981 if (self.value === undefined && self.last_search.length > 0) {
1982 self._change_int_ext_value(self.last_search[0]);
1984 self._change_int_ext_value(null);
1988 this.$input.focusout(anyoneLoosesFocus);
1990 var isSelecting = false;
1992 this.$input.autocomplete({
1993 source: function(req, resp) { self.get_search_result(req, resp); },
1994 select: function(event, ui) {
1998 self._change_int_value([item.id, item.name]);
1999 } else if (item.action) {
2000 self._change_int_value(undefined);
2005 focus: function(e, ui) {
2009 close: anyoneLoosesFocus,
2013 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2014 this.$input.keyup(function(e) {
2015 if (e.which === 13) {
2017 e.stopPropagation();
2019 isSelecting = false;
2022 // autocomplete component content handling
2023 get_search_result: function(request, response) {
2024 var search_val = request.term;
2027 if (this.abort_last) {
2029 delete this.abort_last;
2031 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2033 dataset.name_search(search_val, self.build_domain(), 'ilike',
2034 this.limit + 1, function(data) {
2035 self.last_search = data;
2036 // possible selections for the m2o
2037 var values = _.map(data, function(x) {
2039 label: _.str.escapeHTML(x[1]),
2046 // search more... if more results that max
2047 if (values.length > self.limit) {
2048 values = values.slice(0, self.limit);
2049 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2050 dataset.name_search(search_val, self.build_domain(), 'ilike'
2051 , false, function(data) {
2052 self._change_int_value(null);
2053 self._search_create_popup("search", data);
2058 var raw_result = _(data.result).map(function(x) {return x[1];});
2059 if (search_val.length > 0 &&
2060 !_.include(raw_result, search_val) &&
2061 (!self.value || search_val !== self.value[1])) {
2062 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2063 $('<span />').text(search_val).html()), action: function() {
2064 self._quick_create(search_val);
2068 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2069 self._change_int_value(null);
2070 self._search_create_popup("form", undefined, {"default_name": search_val});
2075 this.abort_last = dataset.abort_last;
2077 _quick_create: function(name) {
2079 var slow_create = function () {
2080 self._change_int_value(null);
2081 self._search_create_popup("form", undefined, {"default_name": name});
2083 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2084 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2085 dataset.name_create(name, function(data) {
2086 self._change_int_ext_value(data);
2087 }).fail(function(error, event) {
2088 event.preventDefault();
2094 // all search/create popup handling
2095 _search_create_popup: function(view, ids, context) {
2097 var pop = new openerp.web.form.SelectCreatePopup(this);
2099 self.field.relation,
2101 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2102 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2104 disable_multiple_selection: true
2106 self.build_domain(),
2107 new openerp.web.CompoundContext(self.build_context(), context || {})
2109 pop.on_select_elements.add(function(element_ids) {
2110 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2111 dataset.name_get([element_ids[0]], function(data) {
2112 self._change_int_ext_value(data[0]);
2116 _change_int_ext_value: function(value) {
2117 this._change_int_value(value);
2118 this.$input.val(this.value ? this.value[1] : "");
2120 _change_int_value: function(value) {
2122 var back_orig_value = this.original_value;
2123 if (this.value === null || this.value) {
2124 this.original_value = this.value;
2126 if (back_orig_value === undefined) { // first use after a set_value()
2129 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2130 !== (this.value ? this.value[0] : null))) {
2131 this.on_ui_change();
2134 set_value: function(value) {
2135 value = value || null;
2136 this.invalid = false;
2138 this.tmp_value = value;
2140 self.on_value_changed();
2141 var real_set_value = function(rval) {
2142 self.tmp_value = undefined;
2144 self.original_value = undefined;
2145 self._change_int_ext_value(rval);
2147 if (value && !(value instanceof Array)) {
2148 // name_get in a m2o does not use the context of the field
2149 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2150 dataset.name_get([value], function(data) {
2151 real_set_value(data[0]);
2152 }).fail(function() {self.tmp_value = undefined;});
2154 $.async_when().then(function() {real_set_value(value);});
2157 get_value: function() {
2158 if (this.tmp_value !== undefined) {
2159 if (this.tmp_value instanceof Array) {
2160 return this.tmp_value[0];
2162 return this.tmp_value ? this.tmp_value : false;
2164 if (this.value === undefined)
2165 return this.original_value ? this.original_value[0] : false;
2166 return this.value ? this.value[0] : false;
2168 validate: function() {
2169 this.invalid = false;
2170 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2172 this.invalid = this.required;
2175 open_related: function(related) {
2179 var additional_context = {
2180 active_id: self.value[0],
2181 active_ids: [self.value[0]],
2182 active_model: self.field.relation
2184 self.rpc("/web/action/load", {
2185 action_id: related[2].id,
2186 context: additional_context
2187 }, function(result) {
2188 result.result.context = _.extend(result.result.context || {}, additional_context);
2189 self.do_action(result.result);
2192 focus: function ($element) {
2193 this._super($element || this.$input);
2195 update_dom: function() {
2196 this._super.apply(this, arguments);
2197 this.$input.prop('readonly', this.readonly);
2202 # Values: (0, 0, { fields }) create
2203 # (1, ID, { fields }) update
2204 # (2, ID) remove (delete)
2205 # (3, ID) unlink one (target id or target of relation)
2207 # (5) unlink all (only valid for one2many)
2212 'create': function (values) {
2213 return [commands.CREATE, false, values];
2215 // (1, id, {values})
2217 'update': function (id, values) {
2218 return [commands.UPDATE, id, values];
2222 'delete': function (id) {
2223 return [commands.DELETE, id, false];
2225 // (3, id[, _]) removes relation, but not linked record itself
2227 'forget': function (id) {
2228 return [commands.FORGET, id, false];
2232 'link_to': function (id) {
2233 return [commands.LINK_TO, id, false];
2237 'delete_all': function () {
2238 return [5, false, false];
2240 // (6, _, ids) replaces all linked records with provided ids
2242 'replace_with': function (ids) {
2243 return [6, false, ids];
2246 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2247 template: 'FieldOne2Many',
2248 multi_selection: false,
2249 init: function(view, node) {
2250 this._super(view, node);
2251 this.is_loaded = $.Deferred();
2252 this.initial_is_loaded = this.is_loaded;
2253 this.is_setted = $.Deferred();
2254 this.form_last_update = $.Deferred();
2255 this.init_form_last_update = this.form_last_update;
2256 this.disable_utility_classes = true;
2259 this._super.apply(this, arguments);
2263 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2264 this.dataset.o2m = this;
2265 this.dataset.parent_view = this.view;
2266 this.dataset.child_name = this.name;
2267 //this.dataset.child_name =
2268 this.dataset.on_change.add_last(function() {
2269 self.trigger_on_change();
2272 this.is_setted.then(function() {
2276 trigger_on_change: function() {
2277 var tmp = this.doing_on_change;
2278 this.doing_on_change = true;
2279 this.on_ui_change();
2280 this.doing_on_change = tmp;
2282 is_readonly: function() {
2283 return this.readonly || this.force_readonly;
2285 load_views: function() {
2288 var modes = this.node.attrs.mode;
2289 modes = !!modes ? modes.split(",") : ["tree"];
2291 _.each(modes, function(mode) {
2294 view_type: mode == "tree" ? "list" : mode,
2295 options: { sidebar : false }
2297 if (self.field.views && self.field.views[mode]) {
2298 view.embedded_view = self.field.views[mode];
2300 if(view.view_type === "list") {
2301 view.options.selectable = self.multi_selection;
2302 if (self.is_readonly()) {
2303 view.options.addable = null;
2304 view.options.deletable = null;
2305 view.options.isClarkGable = false;
2307 } else if (view.view_type === "form") {
2308 if (self.is_readonly()) {
2309 view.view_type = 'page';
2311 view.options.not_interactible_on_create = true;
2317 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2318 this.viewmanager.template = 'One2Many.viewmanager';
2319 this.viewmanager.registry = openerp.web.views.extend({
2320 list: 'openerp.web.form.One2ManyListView',
2321 form: 'openerp.web.form.One2ManyFormView',
2322 page: 'openerp.web.PageView'
2324 var once = $.Deferred().then(function() {
2325 self.init_form_last_update.resolve();
2327 var def = $.Deferred().then(function() {
2328 self.initial_is_loaded.resolve();
2330 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2331 if (view_type == "list") {
2332 controller.o2m = self;
2333 if (self.is_readonly())
2334 controller.set_editable(false);
2335 } else if (view_type == "form" || view_type == 'page') {
2336 if (view_type == 'page' || self.is_readonly()) {
2337 $(".oe_form_buttons", controller.$element).children().remove();
2339 controller.on_record_loaded.add_last(function() {
2342 controller.on_pager_action.add_first(function() {
2343 self.save_any_view();
2345 } else if (view_type == "graph") {
2346 self.reload_current_view()
2350 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2351 $.when(self.save_any_view()).then(function() {
2352 if(n_mode === "list")
2353 $.async_when().then(function() {self.reload_current_view();});
2356 this.is_setted.then(function() {
2357 $.async_when().then(function () {
2358 self.viewmanager.appendTo(self.$element);
2363 reload_current_view: function() {
2365 return self.is_loaded = self.is_loaded.pipe(function() {
2366 var active_view = self.viewmanager.active_view;
2367 var view = self.viewmanager.views[active_view].controller;
2368 if(active_view === "list") {
2369 return view.reload_content();
2370 } else if (active_view === "form" || active_view === 'page') {
2371 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2372 self.dataset.index = 0;
2374 var act = function() {
2375 return view.do_show();
2377 self.form_last_update = self.form_last_update.pipe(act, act);
2378 return self.form_last_update;
2379 } else if (active_view === "graph") {
2380 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2384 set_value: function(value) {
2385 value = value || [];
2387 this.dataset.reset_ids([]);
2388 if(value.length >= 1 && value[0] instanceof Array) {
2390 _.each(value, function(command) {
2391 var obj = {values: command[2]};
2392 switch (command[0]) {
2393 case commands.CREATE:
2394 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2396 self.dataset.to_create.push(obj);
2397 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2400 case commands.UPDATE:
2401 obj['id'] = command[1];
2402 self.dataset.to_write.push(obj);
2403 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2406 case commands.DELETE:
2407 self.dataset.to_delete.push({id: command[1]});
2409 case commands.LINK_TO:
2410 ids.push(command[1]);
2412 case commands.DELETE_ALL:
2413 self.dataset.delete_all = true;
2418 this.dataset.set_ids(ids);
2419 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2421 this.dataset.delete_all = true;
2422 _.each(value, function(command) {
2423 var obj = {values: command};
2424 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2426 self.dataset.to_create.push(obj);
2427 self.dataset.cache.push(_.clone(obj));
2431 this.dataset.set_ids(ids);
2434 this.dataset.reset_ids(value);
2436 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2437 this.dataset.index = 0;
2439 self.is_setted.resolve();
2440 return self.reload_current_view();
2442 get_value: function() {
2446 this.save_any_view();
2447 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2448 val = val.concat(_.map(this.dataset.ids, function(id) {
2449 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2451 return commands.create(alter_order.values);
2453 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2455 return commands.update(alter_order.id, alter_order.values);
2457 return commands.link_to(id);
2459 return val.concat(_.map(
2460 this.dataset.to_delete, function(x) {
2461 return commands['delete'](x.id);}));
2463 save_any_view: function() {
2464 if (this.doing_on_change)
2466 return this.session.synchronized_mode(_.bind(function() {
2467 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2468 this.viewmanager.views[this.viewmanager.active_view] &&
2469 this.viewmanager.views[this.viewmanager.active_view].controller) {
2470 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2471 if (this.viewmanager.active_view === "form") {
2472 if (!view.is_initialized.isResolved()) {
2475 var res = $.when(view.do_save());
2476 if (!res.isResolved() && !res.isRejected()) {
2477 console.warn("Asynchronous get_value() is not supported in form view.");
2480 } else if (this.viewmanager.active_view === "list") {
2481 var res = $.when(view.ensure_saved());
2482 if (!res.isResolved() && !res.isRejected()) {
2483 console.warn("Asynchronous get_value() is not supported in list view.");
2491 is_valid: function() {
2493 return this._super();
2495 validate: function() {
2496 this.invalid = false;
2497 if (!this.viewmanager.views[this.viewmanager.active_view])
2499 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2500 if (this.viewmanager.active_view === "form") {
2501 for (var f in view.fields) {
2503 if (!f.is_valid()) {
2504 this.invalid = true;
2510 is_dirty: function() {
2511 this.save_any_view();
2512 return this._super();
2514 update_dom: function() {
2515 this._super.apply(this, arguments);
2517 if (this.previous_readonly !== this.readonly) {
2518 this.previous_readonly = this.readonly;
2519 if (this.viewmanager) {
2520 this.is_loaded = this.is_loaded.pipe(function() {
2521 self.viewmanager.stop();
2522 return $.when(self.load_views()).then(function() {
2523 self.reload_current_view();
2531 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2532 get_context: function() {
2533 this.context = this.o2m.build_context([this.o2m.name]);
2534 return this.context;
2538 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2539 _template: 'One2Many.listview',
2540 do_add_record: function () {
2541 if (this.options.editable) {
2542 this._super.apply(this, arguments);
2545 var pop = new openerp.web.form.SelectCreatePopup(this);
2546 pop.on_default_get.add(self.dataset.on_default_get);
2548 self.o2m.field.relation,
2550 title: _t("Create: ") + self.name,
2551 initial_view: "form",
2552 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2553 create_function: function(data, callback, error_callback) {
2554 return self.o2m.dataset.create(data).then(function(r) {
2555 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2556 self.o2m.dataset.on_change();
2557 }).then(callback, error_callback);
2559 read_function: function() {
2560 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2562 parent_view: self.o2m.view,
2563 child_name: self.o2m.name,
2564 form_view_options: {'not_interactible_on_create':true}
2566 self.o2m.build_domain(),
2567 self.o2m.build_context()
2569 pop.on_select_elements.add_last(function() {
2570 self.o2m.reload_current_view();
2574 do_activate_record: function(index, id) {
2576 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2577 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2578 title: _t("Open: ") + self.name,
2580 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2581 parent_view: self.o2m.view,
2582 child_name: self.o2m.name,
2583 read_function: function() {
2584 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2586 form_view_options: {'not_interactible_on_create':true},
2587 readonly: self.o2m.is_readonly()
2589 pop.on_write.add(function(id, data) {
2590 self.o2m.dataset.write(id, data, {}, function(r) {
2591 self.o2m.reload_current_view();
2595 do_button_action: function (name, id, callback) {
2597 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2598 return this._super(name, id, _.bind(def.resolve, def));
2602 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2603 form_template: 'One2Many.formview',
2604 on_loaded: function(data) {
2607 this.$form_header.find('button.oe_form_button_create').click(function() {
2608 self.do_save().then(self.on_button_new);
2613 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2614 template: 'FieldMany2Many',
2615 multi_selection: false,
2616 init: function(view, node) {
2617 this._super(view, node);
2618 this.list_id = _.uniqueId("many2many");
2619 this.is_loaded = $.Deferred();
2620 this.initial_is_loaded = this.is_loaded;
2621 this.is_setted = $.Deferred();
2624 this._super.apply(this, arguments);
2628 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2629 this.dataset.m2m = this;
2630 this.dataset.on_unlink.add_last(function(ids) {
2631 self.on_ui_change();
2634 this.is_setted.then(function() {
2638 set_value: function(value) {
2639 value = value || [];
2640 if (value.length >= 1 && value[0] instanceof Array) {
2641 value = value[0][2];
2644 this.dataset.set_ids(value);
2646 self.reload_content();
2647 this.is_setted.resolve();
2649 get_value: function() {
2650 return [commands.replace_with(this.dataset.ids)];
2652 validate: function() {
2653 this.invalid = false;
2655 is_readonly: function() {
2656 return this.readonly || this.force_readonly;
2658 load_view: function() {
2660 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2661 'addable': self.is_readonly() ? null : _t("Add"),
2662 'deletable': self.is_readonly() ? false : true,
2663 'selectable': self.multi_selection,
2664 'isClarkGable': self.is_readonly() ? false : true
2666 var embedded = (this.field.views || {}).tree;
2668 this.list_view.set_embedded_view(embedded);
2670 this.list_view.m2m_field = this;
2671 var loaded = $.Deferred();
2672 this.list_view.on_loaded.add_last(function() {
2673 self.initial_is_loaded.resolve();
2676 $.async_when().then(function () {
2677 self.list_view.appendTo($("#" + self.list_id));
2681 reload_content: function() {
2683 this.is_loaded = this.is_loaded.pipe(function() {
2684 return self.list_view.reload_content();
2687 update_dom: function() {
2688 this._super.apply(this, arguments);
2690 if (this.previous_readonly !== this.readonly) {
2691 this.previous_readonly = this.readonly;
2692 if (this.list_view) {
2693 this.is_loaded = this.is_loaded.pipe(function() {
2694 self.list_view.stop();
2695 return $.when(self.load_view()).then(function() {
2696 self.reload_content();
2704 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2705 get_context: function() {
2706 this.context = this.m2m.build_context();
2707 return this.context;
2713 * @extends openerp.web.ListView
2715 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2716 do_add_record: function () {
2717 var pop = new openerp.web.form.SelectCreatePopup(this);
2721 title: _t("Add: ") + this.name
2723 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2724 this.m2m_field.build_context()
2727 pop.on_select_elements.add(function(element_ids) {
2728 _.each(element_ids, function(element_id) {
2729 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2730 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2731 self.m2m_field.on_ui_change();
2732 self.reload_content();
2737 do_activate_record: function(index, id) {
2739 var pop = new openerp.web.form.FormOpenPopup(this);
2740 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2741 title: _t("Open: ") + this.name,
2742 readonly: this.widget_parent.is_readonly()
2744 pop.on_write_completed.add_last(function() {
2745 self.reload_content();
2752 * @extends openerp.web.OldWidget
2754 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2755 template: "SelectCreatePopup",
2759 * - initial_view: form or search (default search)
2760 * - disable_multiple_selection
2761 * - alternative_form_view
2762 * - create_function (defaults to a naive saving behavior)
2765 * - form_view_options
2766 * - list_view_options
2769 select_element: function(model, options, domain, context) {
2772 this.domain = domain || [];
2773 this.context = context || {};
2774 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2775 return self.create_row.apply(self, arguments);
2776 }, read_function: null});
2777 this.initial_ids = this.options.initial_ids;
2778 this.created_elements = [];
2779 this.render_element();
2780 openerp.web.form.dialog(this.$element, {
2784 title: options.title || ""
2791 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2793 this.dataset.create_function = function() {
2794 return self.options.create_function.apply(null, arguments).then(function(r) {
2795 self.created_elements.push(r.result);
2798 this.dataset.write_function = function() {
2799 return self.write_row.apply(self, arguments);
2801 this.dataset.read_function = this.options.read_function;
2802 this.dataset.parent_view = this.options.parent_view;
2803 this.dataset.child_name = this.options.child_name;
2804 this.dataset.on_default_get.add(this.on_default_get);
2805 if (this.options.initial_view == "search") {
2806 self.rpc('/web/session/eval_domain_and_context', {
2808 contexts: [this.context]
2809 }, function (results) {
2810 var search_defaults = {};
2811 _.each(results.context, function (value, key) {
2812 var match = /^search_default_(.*)$/.exec(key);
2814 search_defaults[match[1]] = value;
2817 self.setup_search_view(search_defaults);
2823 setup_search_view: function(search_defaults) {
2825 if (this.searchview) {
2826 this.searchview.stop();
2828 this.searchview = new openerp.web.SearchView(this,
2829 this.dataset, false, search_defaults);
2830 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2831 if (self.initial_ids) {
2832 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2833 contexts, groupbys);
2834 self.initial_ids = undefined;
2836 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2839 this.searchview.on_loaded.add_last(function () {
2840 self.view_list = new openerp.web.form.SelectCreateListView(self,
2841 self.dataset, false,
2842 _.extend({'deletable': false,
2843 'selectable': !self.options.disable_multiple_selection
2844 }, self.options.list_view_options || {}));
2845 self.view_list.popup = self;
2846 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2847 self.view_list.do_show();
2848 }).pipe(function() {
2849 self.searchview.do_search();
2851 self.view_list.on_loaded.add_last(function() {
2852 var $buttons = self.view_list.$element.find(".oe-actions");
2853 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2854 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2855 $cbutton.click(function() {
2858 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2859 if(self.options.disable_multiple_selection) {
2862 $sbutton.click(function() {
2863 self.on_select_elements(self.selected_ids);
2868 this.searchview.appendTo($("#" + this.element_id + "_search"));
2870 do_search: function(domains, contexts, groupbys) {
2872 this.rpc('/web/session/eval_domain_and_context', {
2873 domains: domains || [],
2874 contexts: contexts || [],
2875 group_by_seq: groupbys || []
2876 }, function (results) {
2877 self.view_list.do_search(results.domain, results.context, results.group_by);
2880 create_row: function() {
2882 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2883 wdataset.parent_view = this.options.parent_view;
2884 wdataset.child_name = this.options.child_name;
2885 return wdataset.create.apply(wdataset, arguments);
2887 write_row: function() {
2889 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2890 wdataset.parent_view = this.options.parent_view;
2891 wdataset.child_name = this.options.child_name;
2892 return wdataset.write.apply(wdataset, arguments);
2894 on_select_elements: function(element_ids) {
2896 on_click_element: function(ids) {
2897 this.selected_ids = ids || [];
2898 if(this.selected_ids.length > 0) {
2899 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2901 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2904 new_object: function() {
2906 if (this.searchview) {
2907 this.searchview.hide();
2909 if (this.view_list) {
2910 this.view_list.$element.hide();
2912 this.dataset.index = null;
2913 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2914 if (this.options.alternative_form_view) {
2915 this.view_form.set_embedded_view(this.options.alternative_form_view);
2917 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2918 this.view_form.on_loaded.add_last(function() {
2919 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2920 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2921 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2922 $nbutton.click(function() {
2923 $.when(self.view_form.do_save()).then(function() {
2924 self.view_form.reload_mutex.exec(function() {
2925 self.view_form.on_button_new();
2929 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2930 $nbutton.click(function() {
2931 $.when(self.view_form.do_save()).then(function() {
2932 self.view_form.reload_mutex.exec(function() {
2937 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2938 $cbutton.click(function() {
2942 this.view_form.do_show();
2944 check_exit: function() {
2945 if (this.created_elements.length > 0) {
2946 this.on_select_elements(this.created_elements);
2950 on_default_get: function(res) {}
2953 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2954 do_add_record: function () {
2955 this.popup.new_object();
2957 select_record: function(index) {
2958 this.popup.on_select_elements([this.dataset.ids[index]]);
2961 do_select: function(ids, records) {
2962 this._super(ids, records);
2963 this.popup.on_click_element(ids);
2969 * @extends openerp.web.OldWidget
2971 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2972 template: "FormOpenPopup",
2975 * - alternative_form_view
2976 * - auto_write (default true)
2980 * - form_view_options
2983 show_element: function(model, row_id, context, options) {
2985 this.row_id = row_id;
2986 this.context = context || {};
2987 this.options = _.defaults(options || {}, {"auto_write": true});
2988 this.render_element();
2989 this.$element.dialog({
2990 title: options.title || '',
2999 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3000 this.dataset.fop = this;
3001 this.dataset.ids = [this.row_id];
3002 this.dataset.index = 0;
3003 this.dataset.parent_view = this.options.parent_view;
3004 this.dataset.child_name = this.options.child_name;
3005 this.setup_form_view();
3007 on_write: function(id, data) {
3008 if (!this.options.auto_write)
3011 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3012 wdataset.parent_view = this.options.parent_view;
3013 wdataset.child_name = this.options.child_name;
3014 wdataset.write(id, data, {}, function(r) {
3015 self.on_write_completed();
3018 on_write_completed: function() {},
3019 setup_form_view: function() {
3021 var FormClass = this.options.readonly
3022 ? openerp.web.views.get_object('page')
3023 : openerp.web.views.get_object('form');
3024 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3025 if (this.options.alternative_form_view) {
3026 this.view_form.set_embedded_view(this.options.alternative_form_view);
3028 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3029 this.view_form.on_loaded.add_last(function() {
3030 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3031 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3032 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3033 $nbutton.click(function() {
3034 self.view_form.do_save().then(function() {
3038 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3039 $cbutton.click(function() {
3042 if (self.options.readonly) {
3044 $cbutton.text(_t("Close"));
3046 self.view_form.do_show();
3048 this.dataset.on_write.add(this.on_write);
3052 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3053 read_ids: function() {
3054 if (this.fop.options.read_function) {
3055 return this.fop.options.read_function.apply(null, arguments);
3057 return this._super.apply(this, arguments);
3062 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3063 template: 'FieldReference',
3064 init: function(view, node) {
3065 this._super(view, node);
3066 this.fields_view = {
3069 selection: view.fields_view.fields[this.name].selection
3076 this.get_fields_values = view.get_fields_values;
3077 this.get_selected_ids = view.get_selected_ids;
3078 this.do_onchange = this.on_form_changed = this.on_nop;
3079 this.dataset = this.view.dataset;
3080 this.widgets_counter = 0;
3081 this.view_id = 'reference_' + _.uniqueId();
3084 this.fields_order = [];
3085 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3089 this.reference_ready = true;
3090 this.selection.on_value_changed.add_last(this.on_selection_changed);
3091 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3095 this.m2o.on_ui_change.add_last(this.on_ui_change);
3097 on_nop: function() {
3099 on_selection_changed: function() {
3100 if (this.reference_ready) {
3101 var sel = this.selection.get_value();
3102 this.m2o.field.relation = sel;
3103 this.m2o.set_value(null);
3104 this.m2o.$element.toggle(sel !== false);
3109 this.selection.start();
3112 is_valid: function() {
3113 return this.required === false || typeof(this.get_value()) === 'string';
3115 is_dirty: function() {
3116 return this.selection.is_dirty() || this.m2o.is_dirty();
3118 set_value: function(value) {
3120 this.reference_ready = false;
3121 var vals = [], sel_val, m2o_val;
3122 if (typeof(value) === 'string') {
3123 vals = value.split(',');
3125 sel_val = vals[0] || false;
3126 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3127 this.selection.set_value(sel_val);
3128 this.m2o.field.relation = sel_val;
3129 this.m2o.set_value(m2o_val);
3130 this.m2o.$element.toggle(sel_val !== false);
3131 this.reference_ready = true;
3133 get_value: function() {
3134 var model = this.selection.get_value(),
3135 id = this.m2o.get_value();
3136 if (typeof(model) === 'string' && typeof(id) === 'number') {
3137 return model + ',' + id;
3144 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3145 init: function(view, node) {
3146 this._super(view, node);
3147 this.iframe = this.element_id + '_iframe';
3148 this.binary_value = false;
3151 this._super.apply(this, arguments);
3152 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3153 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3154 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3156 human_filesize : function(size) {
3157 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3159 while (size >= 1024) {
3163 return size.toFixed(2) + ' ' + units[i];
3165 on_file_change: function(e) {
3166 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3167 // http://www.html5rocks.com/tutorials/file/dndfiles/
3168 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3169 window[this.iframe] = this.on_file_uploaded;
3170 if ($(e.target).val() != '') {
3171 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3172 this.$element.find('form.oe-binary-form').submit();
3173 this.$element.find('.oe-binary-progress').show();
3174 this.$element.find('.oe-binary').hide();
3177 on_file_uploaded: function(size, name, content_type, file_base64) {
3178 delete(window[this.iframe]);
3179 if (size === false) {
3180 this.do_warn("File Upload", "There was a problem while uploading your file");
3181 // TODO: use openerp web crashmanager
3182 console.warn("Error while uploading file : ", name);
3184 this.on_file_uploaded_and_valid.apply(this, arguments);
3185 this.on_ui_change();
3187 this.$element.find('.oe-binary-progress').hide();
3188 this.$element.find('.oe-binary').show();
3190 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3192 on_save_as: function() {
3194 this.session.get_file({
3195 url: '/web/binary/saveas_ajax',
3196 data: {data: JSON.stringify({
3197 model: this.view.dataset.model,
3198 id: (this.view.datarecord.id || ''),
3200 filename_field: (this.node.attrs.filename || ''),
3201 context: this.view.dataset.get_context()
3203 complete: $.unblockUI,
3204 error: openerp.webclient.crashmanager.on_rpc_error
3207 on_clear: function() {
3208 if (this.value !== false) {
3210 this.binary_value = false;
3211 this.on_ui_change();
3217 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3218 template: 'FieldBinaryFile',
3219 update_dom: function() {
3220 this._super.apply(this, arguments);
3221 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3222 this.$element.find('input[type=text]').prop('readonly', this.readonly);
3224 set_value: function(value) {
3225 this._super.apply(this, arguments);
3227 if (this.node.attrs.filename) {
3228 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3230 show_value = (value != null && value !== false) ? value : '';
3232 this.$element.find('input').eq(0).val(show_value);
3234 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3235 this.value = file_base64;
3236 this.binary_value = true;
3237 var show_value = name + " (" + this.human_filesize(size) + ")";
3238 this.$element.find('input').eq(0).val(show_value);
3239 this.set_filename(name);
3241 set_filename: function(value) {
3242 var filename = this.node.attrs.filename;
3243 if (this.view.fields[filename]) {
3244 this.view.fields[filename].set_value(value);
3245 this.view.fields[filename].on_ui_change();
3248 on_clear: function() {
3249 this._super.apply(this, arguments);
3250 this.$element.find('input').eq(0).val('');
3251 this.set_filename('');
3255 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3256 template: 'FieldBinaryImage',
3258 this._super.apply(this, arguments);
3259 this.$image = this.$element.find('img.oe-binary-image');
3261 update_dom: function() {
3262 this._super.apply(this, arguments);
3263 this.$element.find('.oe-binary').toggle(!this.readonly);
3265 set_value: function(value) {
3266 this._super.apply(this, arguments);
3267 this.set_image_maxwidth();
3268 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3269 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3270 this.$image.attr('src', url);
3272 set_image_maxwidth: function() {
3273 this.$image.css('max-width', this.$element.width());
3275 on_file_change: function() {
3276 this.set_image_maxwidth();
3277 this._super.apply(this, arguments);
3279 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3280 this.value = file_base64;
3281 this.binary_value = true;
3282 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3284 on_clear: function() {
3285 this._super.apply(this, arguments);
3286 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3290 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3291 template: "EmptyComponent",
3294 this.selected_value = null;
3298 set_value: function(value) {
3300 this.selected_value = value;
3304 render_list: function() {
3306 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3307 function(x) { return _.str.trim(x); });
3308 shown = _.select(shown, function(x) { return x.length > 0; });
3310 if (shown.length == 0) {
3311 this.to_show = this.field.selection;
3313 this.to_show = _.select(this.field.selection, function(x) {
3314 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3318 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3319 this.$element.html(content);
3321 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3322 var color = colors[this.selected_value];
3324 var elem = this.$element.find("li.oe-arrow-list-selected span");
3325 elem.css("border-color", color);
3326 if (this.check_white(color))
3327 elem.css("color", "white");
3328 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3329 elem.css("border-left-color", "rgba(0,0,0,0)");
3330 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3331 elem.css("border-color", "rgba(0,0,0,0)");
3332 elem.css("border-left-color", color);
3335 check_white: function(color) {
3336 var div = $("<div></div>");
3337 div.css("display", "none");
3338 div.css("color", color);
3339 div.appendTo($("body"));
3340 var ncolor = div.css("color");
3342 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3346 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3347 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3355 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3356 render: function () {
3357 var $root = $('<div class="oe_form_html_view">');
3358 this.render_children(this, $root);
3359 return $root.html();
3361 render_children: function (object, $into) {
3363 fields = this.view.fields_view.fields;
3364 _(object.children).each(function (child) {
3365 if (typeof child === 'string') {
3367 } else if (child.tag === 'field') {
3369 new (self.view.registry.get_object('frame'))(
3370 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3373 var $child = $(document.createElement(child.tag))
3376 self.render_children(child, $child);
3384 * Registry of form widgets, called by :js:`openerp.web.FormView`
3386 openerp.web.form.widgets = new openerp.web.Registry({
3387 'frame' : 'openerp.web.form.WidgetFrame',
3388 'group' : 'openerp.web.form.WidgetGroup',
3389 'notebook' : 'openerp.web.form.WidgetNotebook',
3390 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3391 'separator' : 'openerp.web.form.WidgetSeparator',
3392 'label' : 'openerp.web.form.WidgetLabel',
3393 'button' : 'openerp.web.form.WidgetButton',
3394 'char' : 'openerp.web.form.FieldChar',
3395 'id' : 'openerp.web.form.FieldID',
3396 'email' : 'openerp.web.form.FieldEmail',
3397 'url' : 'openerp.web.form.FieldUrl',
3398 'text' : 'openerp.web.form.FieldText',
3399 'date' : 'openerp.web.form.FieldDate',
3400 'datetime' : 'openerp.web.form.FieldDatetime',
3401 'selection' : 'openerp.web.form.FieldSelection',
3402 'many2one' : 'openerp.web.form.FieldMany2One',
3403 'many2many' : 'openerp.web.form.FieldMany2Many',
3404 'one2many' : 'openerp.web.form.FieldOne2Many',
3405 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3406 'reference' : 'openerp.web.form.FieldReference',
3407 'boolean' : 'openerp.web.form.FieldBoolean',
3408 'float' : 'openerp.web.form.FieldFloat',
3409 'integer': 'openerp.web.form.FieldFloat',
3410 'float_time': 'openerp.web.form.FieldFloat',
3411 'progressbar': 'openerp.web.form.FieldProgressBar',
3412 'image': 'openerp.web.form.FieldBinaryImage',
3413 'binary': 'openerp.web.form.FieldBinaryFile',
3414 'statusbar': 'openerp.web.form.FieldStatus',
3415 'html': 'openerp.web.form.WidgetHtml'
3421 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: