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 this.$element.removeClass('oe_form_dirty');
149 return this.has_been_loaded.pipe(function() {
151 if (self.dataset.index === null) {
152 // null index means we should start a new record
153 result = self.on_button_new();
155 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
156 context : { 'bin_size' : true }
157 }).pipe(self.on_record_loaded);
159 result.pipe(function() {
160 self.$element.css('visibility', 'visible');
163 self.sidebar.$element.show();
168 do_hide: function () {
171 this.sidebar.$element.hide();
174 on_record_loaded: function(record) {
175 var self = this, set_values = [];
177 this.do_warn("Form", "The record could not be found in the database.", true);
178 return $.Deferred().reject();
180 this.datarecord = record;
182 _(this.fields).each(function (field, f) {
184 var result = field.set_value(self.datarecord[f] || false);
185 set_values.push(result);
186 $.when(result).then(function() {
190 return $.when.apply(null, set_values).pipe(function() {
192 // New record: Second pass in order to trigger the onchanges
193 // respecting the fields order defined in the view
194 _.each(self.fields_order, function(field_name) {
195 if (record[field_name] !== undefined) {
196 var field = self.fields[field_name];
198 self.do_onchange(field);
202 self.on_form_changed();
203 self.is_initialized.resolve();
204 self.do_update_pager(record.id == null);
206 self.sidebar.attachments.do_update();
208 if (self.default_focus_field) {
209 self.default_focus_field.focus();
212 self.do_push_state({id:record.id});
214 self.$element.removeClass('oe_form_dirty');
217 on_form_changed: function() {
218 for (var w in this.widgets) {
220 w.process_modifiers();
227 do_notify_change: function() {
228 this.$element.addClass('oe_form_dirty');
230 on_pager_action: function(action) {
231 if (this.can_be_discarded()) {
234 this.dataset.index = 0;
237 this.dataset.previous();
243 this.dataset.index = this.dataset.ids.length - 1;
249 do_update_pager: function(hide_index) {
250 var $pager = this.$form_header.find('div.oe_form_pager');
251 var index = hide_index ? '-' : this.dataset.index + 1;
252 $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
253 $pager.find('span.oe_pager_index').html(index);
254 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
256 parse_on_change: function (on_change, widget) {
258 var onchange = _.str.trim(on_change);
259 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
264 var method = call[1];
265 if (!_.str.trim(call[2])) {
266 return {method: method, args: [], context_index: null}
269 var argument_replacement = {
270 'False': function () {return false;},
271 'True': function () {return true;},
272 'None': function () {return null;},
273 'context': function (i) {
275 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
279 var parent_fields = null, context_index = null;
280 var args = _.map(call[2].split(','), function (a, i) {
281 var field = _.str.trim(a);
283 // literal constant or context
284 if (field in argument_replacement) {
285 return argument_replacement[field](i);
288 if (/^-?\d+(\.\d+)?$/.test(field)) {
289 return Number(field);
292 if (self.fields[field]) {
293 var value = self.fields[field].get_on_change_value();
294 return value == null ? false : value;
297 var splitted = field.split('.');
298 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
299 if (parent_fields === null) {
300 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
302 var p_val = parent_fields[_.str.trim(splitted[1])];
303 if (p_val !== undefined) {
304 return p_val == null ? false : p_val;
308 var first_char = field[0], last_char = field[field.length-1];
309 if ((first_char === '"' && last_char === '"')
310 || (first_char === "'" && last_char === "'")) {
311 return field.slice(1, -1);
314 throw new Error("Could not get field with name '" + field +
315 "' for onchange '" + onchange + "'");
321 context_index: context_index
324 do_onchange: function(widget, processed) {
326 return this.on_change_mutex.exec(function() {
328 var response = {}, can_process_onchange = $.Deferred();
329 processed = processed || [];
330 processed.push(widget.name);
331 var on_change = widget.node.attrs.on_change;
333 var change_spec = self.parse_on_change(on_change, widget);
336 url: '/web/dataset/onchange',
339 can_process_onchange = self.rpc(ajax, {
340 model: self.dataset.model,
341 method: change_spec.method,
342 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
343 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
344 }).then(function(r) {
345 _.extend(response, r);
348 console.warn("Wrong on_change format", on_change);
351 // fail if onchange failed
352 if (can_process_onchange.isRejected()) {
353 return can_process_onchange;
356 if (widget.field['change_default']) {
357 var fieldname = widget.name, value;
358 if (response.value && (fieldname in response.value)) {
359 // Use value from onchange if onchange executed
360 value = response.value[fieldname];
362 // otherwise get form value for field
363 value = self.fields[fieldname].get_on_change_value();
365 var condition = fieldname + '=' + value;
368 can_process_onchange = self.rpc({
369 url: '/web/dataset/call',
373 method: 'get_defaults',
374 args: [self.model, condition]
375 }).then(function (results) {
376 if (!results.length) { return; }
377 if (!response.value) {
380 for(var i=0; i<results.length; ++i) {
381 // [whatever, key, value]
382 var triplet = results[i];
383 response.value[triplet[1]] = triplet[2];
388 if (can_process_onchange.isRejected()) {
389 return can_process_onchange;
392 return self.on_processed_onchange(response, processed);
395 return $.Deferred().reject();
399 on_processed_onchange: function(response, processed) {
401 var result = response;
403 for (var f in result.value) {
404 if (!result.value.hasOwnProperty(f)) { continue; }
405 var field = this.fields[f];
406 // If field is not defined in the view, just ignore it
408 var value = result.value[f];
409 if (field.get_value() != value) {
410 field.set_value(value);
412 if (!_.contains(processed, field.name)) {
413 this.do_onchange(field, processed);
418 this.on_form_changed();
420 if (!_.isEmpty(result.warning)) {
421 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
424 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
429 function edit_domain(node) {
430 var new_domain = result.domain[node.attrs.name];
432 node.attrs.domain = new_domain;
434 _(node.children).each(edit_domain);
436 edit_domain(this.fields_view.arch);
438 return $.Deferred().resolve();
441 return $.Deferred().reject();
444 on_button_save: function() {
446 return this.do_save().then(function(result) {
447 self.do_prev_view({'created': result.created, 'default': 'page'});
450 on_button_cancel: function() {
451 if (this.can_be_discarded()) {
452 return this.do_prev_view({'default': 'page'});
455 on_button_new: function() {
457 var def = $.Deferred();
458 $.when(this.has_been_loaded).then(function() {
459 if (self.can_be_discarded()) {
460 var keys = _.keys(self.fields_view.fields);
462 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
466 self.on_record_loaded({}).then(function() {
472 return def.promise();
474 can_be_discarded: function() {
475 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
478 * Triggers saving the form's record. Chooses between creating a new
479 * record or saving an existing one depending on whether the record
480 * already has an id property.
482 * @param {Function} success callback on save success
483 * @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)
485 do_save: function(success, prepend_on_create) {
487 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
489 var form_invalid = false,
491 first_invalid_field = null;
492 for (var f in self.fields) {
497 if (!first_invalid_field) {
498 first_invalid_field = f;
500 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
501 // Special case 'id' field, do not save this field
502 // on 'create' : save all non readonly fields
503 // on 'edit' : save non readonly modified fields
504 values[f.name] = f.get_value();
508 first_invalid_field.focus();
510 return $.Deferred().reject();
513 if (!self.datarecord.id) {
514 //console.log("FormView(", self, ") : About to create", values);
515 save_deferral = self.dataset.create(values).pipe(function(r) {
516 return self.on_created(r, undefined, prepend_on_create);
518 } else if (_.isEmpty(values) && ! self.force_dirty) {
519 //console.log("FormView(", self, ") : Nothing to save");
520 save_deferral = $.Deferred().resolve({}).promise();
522 self.force_dirty = false;
523 //console.log("FormView(", self, ") : About to save", values);
524 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
525 return self.on_saved(r);
528 return save_deferral.then(success);
532 return $.Deferred().reject();
536 on_invalid: function() {
538 _.each(this.fields, function(f) {
540 msg += "<li>" + f.string + "</li>";
544 this.do_warn("The following fields are invalid :", msg);
546 on_saved: function(r, success) {
548 // should not happen in the server, but may happen for internal purpose
549 return $.Deferred().reject();
551 return $.when(this.reload()).pipe(function () {
557 * Updates the form' dataset to contain the new record:
559 * * Adds the newly created record to the current dataset (at the end by
561 * * Selects that record (sets the dataset's index to point to the new
563 * * Updates the pager and sidebar displays
566 * @param {Function} success callback to execute after having updated the dataset
567 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
569 on_created: function(r, success, prepend_on_create) {
571 // should not happen in the server, but may happen for internal purpose
572 return $.Deferred().reject();
574 this.datarecord.id = r.result;
575 if (!prepend_on_create) {
576 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
577 this.dataset.index = this.dataset.ids.length - 1;
579 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
580 this.dataset.index = 0;
582 this.do_update_pager();
584 this.sidebar.attachments.do_update();
586 //openerp.log("The record has been created with id #" + this.datarecord.id);
587 return $.when(this.reload()).pipe(function () {
588 return _.extend(r, {created: true}); })
592 on_action: function (action) {
593 console.debug('Executing action', action);
597 return this.reload_mutex.exec(function() {
598 if (self.dataset.index == null || self.dataset.index < 0) {
599 return $.when(self.on_button_new());
601 return self.dataset.read_index(_.keys(self.fields_view.fields), {
602 context : { 'bin_size' : true }
603 }).pipe(self.on_record_loaded);
607 get_fields_values: function(blacklist) {
608 blacklist = blacklist || [];
610 var ids = this.get_selected_ids();
611 values["id"] = ids.length > 0 ? ids[0] : false;
612 _.each(this.fields, function(value, key) {
613 if (_.include(blacklist, key))
615 var val = value.get_value();
620 get_selected_ids: function() {
621 var id = this.dataset.ids[this.dataset.index];
622 return id ? [id] : [];
624 recursive_save: function() {
626 return $.when(this.do_save()).pipe(function(res) {
627 if (self.dataset.parent_view)
628 return self.dataset.parent_view.recursive_save();
631 is_dirty: function() {
632 return _.any(this.fields, function (value) {
633 return value.is_dirty();
636 is_interactible_record: function() {
637 var id = this.datarecord.id;
639 if (this.options.not_interactible_on_create)
641 } else if (typeof(id) === "string") {
642 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
647 sidebar_context: function () {
648 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
650 open_defaults_dialog: function () {
652 var fields = _.chain(this.fields)
653 .map(function (field, name) {
654 var value = field.get_value();
655 // ignore fields which are empty, invisible, readonly, o2m
660 || field.field.type === 'one2many'
661 || field.field.type === 'many2many') {
665 switch(field.field.type) {
667 displayed = _(field.values).find(function (option) {
668 return option[0] === value;
672 displayed = field.value[1] || value;
680 string: field.string,
682 displayed: displayed,
683 // convert undefined to false
684 change_default: !!field.field.change_default
688 .sortBy(function (field) { return field.string; })
690 var conditions = _.chain(fields)
691 .filter(function (field) { return field.change_default; })
694 var d = new openerp.web.Dialog(this, {
695 title: _t("Set Default"),
698 conditions: conditions
701 {text: _t("Close"), click: function () { d.close(); }},
702 {text: _t("Save default"), click: function () {
703 var $defaults = d.$element.find('#formview_default_fields');
704 var field_to_set = $defaults.val();
706 $defaults.parent().addClass('invalid');
709 var condition = d.$element.find('#formview_default_conditions').val(),
710 all_users = d.$element.find('#formview_default_all').is(':checked');
711 new openerp.web.DataSet(self, 'ir.values').call(
715 self.fields[field_to_set].get_value(),
719 ]).then(function () { d.close(); });
723 d.template = 'FormView.set_default';
727 openerp.web.FormDialog = openerp.web.Dialog.extend({
728 init: function(parent, options, view_id, dataset) {
729 this._super(parent, options);
730 this.dataset = dataset;
731 this.view_id = view_id;
736 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
740 this.form.appendTo(this.$element);
741 this.form.on_created.add_last(this.on_form_dialog_saved);
742 this.form.on_saved.add_last(this.on_form_dialog_saved);
745 select_id: function(id) {
746 if (this.form.dataset.select_id(id)) {
747 return this.form.do_show();
749 this.do_warn("Could not find id in dataset");
750 return $.Deferred().reject();
753 on_form_dialog_saved: function(r) {
759 openerp.web.form = {};
761 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
762 init: function(parent, form_view) {
763 var $section = parent.add_section(_t('Attachments'), 'attachments');
764 this.$div = $('<div class="oe-sidebar-attachments"></div>');
765 $section.append(this.$div);
767 this._super(parent, $section.attr('id'));
768 this.view = form_view;
770 do_update: function() {
771 if (!this.view.datarecord.id) {
772 this.on_attachments_loaded([]);
774 (new openerp.web.DataSetSearch(
775 this, 'ir.attachment', this.view.dataset.get_context(),
777 ['res_model', '=', this.view.dataset.model],
778 ['res_id', '=', this.view.datarecord.id],
779 ['type', 'in', ['binary', 'url']]
780 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
783 on_attachments_loaded: function(attachments) {
784 this.attachments = attachments;
785 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
786 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
787 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
789 on_attachment_changed: function(e) {
790 window[this.element_id + '_iframe'] = this.do_update;
791 var $e = $(e.target);
792 if ($e.val() != '') {
793 this.$element.find('form.oe-binary-form').submit();
794 $e.parent().find('input[type=file]').prop('disabled', true);
795 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
798 on_attachment_delete: function(e) {
799 var self = this, $e = $(e.currentTarget);
800 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
801 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
802 this.rpc('/web/dataset/unlink', {
803 model: 'ir.attachment',
804 ids: [parseInt($e.attr('data-id'))]
806 $e.parent().remove();
808 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
814 openerp.web.form.compute_domain = function(expr, fields) {
816 for (var i = expr.length - 1; i >= 0; i--) {
818 if (ex.length == 1) {
819 var top = stack.pop();
822 stack.push(stack.pop() || top);
825 stack.push(stack.pop() && top);
831 throw new Error(_.str.sprintf(
832 _t("Unknown operator %s in domain %s"),
833 ex, JSON.stringify(expr)));
837 var field = fields[ex[0]];
839 throw new Error(_.str.sprintf(
840 _t("Unknown field %s in domain %s"),
841 ex[0], JSON.stringify(expr)));
843 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
847 switch (op.toLowerCase()) {
850 stack.push(field_value == val);
854 stack.push(field_value != val);
857 stack.push(field_value < val);
860 stack.push(field_value > val);
863 stack.push(field_value <= val);
866 stack.push(field_value >= val);
869 if (!_.isArray(val)) val = [val];
870 stack.push(_(val).contains(field_value));
873 if (!_.isArray(val)) val = [val];
874 stack.push(!_(val).contains(field_value));
878 _t("Unsupported operator %s in domain %s"),
879 op, JSON.stringify(expr));
882 return _.all(stack, _.identity);
885 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
888 * @constructs openerp.web.form.Widget
889 * @extends openerp.web.OldWidget
894 init: function(view, node) {
897 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
898 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
899 this.type = this.type || node.tag;
900 this.element_name = this.element_name || this.type;
901 this.element_class = [
902 'formview', this.view.view_id, this.element_name,
903 this.view.widgets_counter++].join("_");
907 this.view.widgets[this.element_class] = this;
908 this.children = node.children;
909 this.colspan = parseInt(node.attrs.colspan || 1, 10);
910 this.decrease_max_width = 0;
912 this.string = this.string || node.attrs.string;
913 this.help = this.help || node.attrs.help;
914 this.invisible = this.modifiers['invisible'] === true;
915 this.classname = 'oe_form_' + this.type;
917 this.align = parseFloat(this.node.attrs.align);
918 if (isNaN(this.align) || this.align === 1) {
919 this.align = 'right';
920 } else if (this.align === 0) {
923 this.align = 'center';
927 this.width = this.node.attrs.width;
930 this.$element = this.view.$element.find(
931 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
934 this._super.apply(this, arguments);
937 process_modifiers: function() {
938 var compute_domain = openerp.web.form.compute_domain;
939 for (var a in this.modifiers) {
940 this[a] = compute_domain(this.modifiers[a], this.view.fields);
943 update_dom: function() {
944 this.$element.toggle(!this.invisible);
947 var template = this.template;
948 return QWeb.render(template, { "widget": this });
950 do_attach_tooltip: function(widget, trigger, options) {
951 widget = widget || this;
952 trigger = trigger || this.$element;
958 var template = widget.template + '.tooltip';
959 if (!QWeb.has_template(template)) {
960 template = 'WidgetLabel.tooltip';
962 return QWeb.render(template, {
963 debug: openerp.connection.debug,
966 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
971 trigger.tipsy(options);
973 _build_view_fields_values: function(blacklist) {
974 var a_dataset = this.view.dataset;
975 var fields_values = this.view.get_fields_values(blacklist);
976 var active_id = a_dataset.ids[a_dataset.index];
977 _.extend(fields_values, {
978 active_id: active_id || false,
979 active_ids: active_id ? [active_id] : [],
980 active_model: a_dataset.model,
983 if (a_dataset.parent_view) {
984 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
986 return fields_values;
988 _build_eval_context: function(blacklist) {
989 var a_dataset = this.view.dataset;
990 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
993 * Builds a new context usable for operations related to fields by merging
994 * the fields'context with the action's context.
996 build_context: function(blacklist) {
997 // only use the model's context if there is not context on the node
998 var v_context = this.node.attrs.context;
1000 v_context = (this.field || {}).context || {};
1003 if (v_context.__ref || true) { //TODO: remove true
1004 var fields_values = this._build_eval_context(blacklist);
1005 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1009 build_domain: function() {
1010 var f_domain = this.field.domain || [];
1011 var n_domain = this.node.attrs.domain || null;
1012 // if there is a domain on the node, overrides the model's domain
1013 var final_domain = n_domain !== null ? n_domain : f_domain;
1014 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1015 var fields_values = this._build_eval_context();
1016 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1018 return final_domain;
1022 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1023 template: 'WidgetFrame',
1024 init: function(view, node) {
1025 this._super(view, node);
1026 this.columns = parseInt(node.attrs.col || 4, 10);
1031 for (var i = 0; i < node.children.length; i++) {
1032 var n = node.children[i];
1033 if (n.tag == "newline") {
1036 this.handle_node(n);
1039 this.set_row_cells_with(this.table[this.table.length - 1]);
1041 add_row: function(){
1042 if (this.table.length) {
1043 this.set_row_cells_with(this.table[this.table.length - 1]);
1046 this.table.push(row);
1051 set_row_cells_with: function(row) {
1054 row_length = row.length;
1055 for (var i = 0; i < row.length; i++) {
1056 if (row[i].always_invisible) {
1059 bypass += row[i].width === undefined ? 0 : 1;
1060 max_width -= row[i].decrease_max_width;
1063 var size_unit = Math.round(max_width / (this.columns - bypass)),
1065 for (var i = 0; i < row.length; i++) {
1067 if (w.always_invisible) {
1070 colspan_sum += w.colspan;
1071 if (w.width === undefined) {
1072 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1074 w.width = width + '%';
1078 handle_node: function(node) {
1080 if (node.tag == 'field') {
1081 type = this.view.fields_view.fields[node.attrs.name] || {};
1082 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1083 // This way we can retain backward compatibility between addons and old clients
1084 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1085 node.attrs.nolabel = '1';
1088 var widget = new (this.view.registry.get_any(
1089 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1090 if (node.tag == 'field') {
1091 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1092 this.view.default_focus_field = widget;
1094 if (node.attrs.nolabel != '1') {
1095 var label = new (this.view.registry.get_object('label')) (this.view, node);
1096 label["for"] = widget;
1097 this.add_widget(label, widget.colspan + 1);
1100 this.add_widget(widget);
1102 add_widget: function(widget, colspan) {
1103 var current_row = this.table[this.table.length - 1];
1104 if (!widget.always_invisible) {
1105 colspan = colspan || widget.colspan;
1106 if (current_row.length && (this.x + colspan) > this.columns) {
1107 current_row = this.add_row();
1109 this.x += widget.colspan;
1111 current_row.push(widget);
1116 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1117 template: 'WidgetGroup'
1120 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1121 template: 'WidgetNotebook',
1122 init: function(view, node) {
1123 this._super(view, node);
1125 for (var i = 0; i < node.children.length; i++) {
1126 var n = node.children[i];
1127 if (n.tag == "page") {
1128 var page = new (this.view.registry.get_object('notebookpage'))(
1129 this.view, n, this, this.pages.length);
1130 this.pages.push(page);
1136 this._super.apply(this, arguments);
1137 this.$element.find('> ul > li').each(function (index, tab_li) {
1138 var page = self.pages[index],
1139 id = _.uniqueId(self.element_name + '-');
1140 page.element_id = id;
1141 $(tab_li).find('a').attr('href', '#' + id);
1143 this.$element.find('> div').each(function (index, page) {
1144 page.id = self.pages[index].element_id;
1146 this.$element.tabs();
1147 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1148 if (openerp.connection.debug) {
1149 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1154 do_select_first_visible_tab: function() {
1155 for (var i = 0; i < this.pages.length; i++) {
1156 var page = this.pages[i];
1157 if (page.invisible === false) {
1158 this.$element.tabs('select', page.index);
1165 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1166 template: 'WidgetNotebookPage',
1167 init: function(view, node, notebook, index) {
1168 this.notebook = notebook;
1170 this.element_name = 'page_' + index;
1171 this._super(view, node);
1174 this._super.apply(this, arguments);
1175 this.$element_tab = this.notebook.$element.find(
1176 '> ul > li:eq(' + this.index + ')');
1178 update_dom: function() {
1179 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1180 this.notebook.do_select_first_visible_tab();
1182 this.$element_tab.toggle(!this.invisible);
1183 this.$element.toggle(!this.invisible);
1187 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1188 template: 'WidgetSeparator',
1189 init: function(view, node) {
1190 this._super(view, node);
1191 this.orientation = node.attrs.orientation || 'horizontal';
1192 if (this.orientation === 'vertical') {
1195 this.classname += '_' + this.orientation;
1199 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1200 template: 'WidgetButton',
1201 init: function(view, node) {
1202 this._super(view, node);
1203 this.force_disabled = false;
1205 // We don't have button key bindings in the webclient
1206 this.string = this.string.replace(/_/g, '');
1208 if (node.attrs.default_focus == '1') {
1209 // TODO fme: provide enter key binding to widgets
1210 this.view.default_focus_button = this;
1214 this._super.apply(this, arguments);
1215 this.$element.find("button").click(this.on_click);
1216 if (this.help || openerp.connection.debug) {
1217 this.do_attach_tooltip();
1220 on_click: function() {
1222 this.force_disabled = true;
1223 this.check_disable();
1224 this.execute_action().always(function() {
1225 self.force_disabled = false;
1226 self.check_disable();
1229 execute_action: function() {
1231 var exec_action = function() {
1232 if (self.node.attrs.confirm) {
1233 var def = $.Deferred();
1234 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1235 title: _t('Confirm'),
1238 {text: _t("Cancel"), click: function() {
1240 $(this).dialog("close");
1243 {text: _t("Ok"), click: function() {
1244 self.on_confirmed().then(function() {
1247 $(this).dialog("close");
1252 return def.promise();
1254 return self.on_confirmed();
1257 if (!this.node.attrs.special) {
1258 this.view.force_dirty = true;
1259 return this.view.recursive_save().pipe(exec_action);
1261 return exec_action();
1264 on_confirmed: function() {
1267 var context = this.node.attrs.context;
1268 if (context && context.__ref) {
1269 context = new openerp.web.CompoundContext(context);
1270 context.set_eval_context(this._build_eval_context());
1273 return this.view.do_execute_action(
1274 _.extend({}, this.node.attrs, {context: context}),
1275 this.view.dataset, this.view.datarecord.id, function () {
1279 update_dom: function() {
1280 this._super.apply(this, arguments);
1281 this.check_disable();
1283 check_disable: function() {
1284 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1285 this.$element.find('button').prop('disabled', disabled);
1286 this.$element.find("button").css('color', disabled ? 'grey' : '');
1290 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1291 template: 'WidgetLabel',
1292 init: function(view, node) {
1293 this.element_name = 'label_' + node.attrs.name;
1295 this._super(view, node);
1297 if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1298 this.string = this.node.children[0];
1299 this.align = 'left';
1302 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1303 this.template = "WidgetParagraph";
1304 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1305 // Widgets default to right-aligned, but paragraph defaults to
1307 if (isNaN(parseFloat(this.node.attrs.align))) {
1308 this.align = 'left';
1311 this.multilines = this.string && _.str.lines(this.string).length > 1;
1315 this.decrease_max_width = 1;
1319 render: function () {
1320 if (this['for'] && this.type !== 'label') {
1321 return QWeb.render(this.template, {widget: this['for']});
1323 // Actual label widgets should not have a false and have type label
1324 return QWeb.render(this.template, {widget: this});
1329 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1330 this.do_attach_tooltip(self['for']);
1332 this.$element.find("label").dblclick(function() {
1333 var widget = self['for'] || self;
1334 openerp.log(widget.element_class , widget);
1340 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1342 * @constructs openerp.web.form.Field
1343 * @extends openerp.web.form.Widget
1348 init: function(view, node) {
1349 this.name = node.attrs.name;
1350 this.value = undefined;
1351 view.fields[this.name] = this;
1352 view.fields_order.push(this.name);
1353 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1354 this.element_name = "field_" + this.name + "_" + this.type;
1356 this._super(view, node);
1358 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1361 this.field = view.fields_view.fields[node.attrs.name] || {};
1362 this.string = node.attrs.string || this.field.string;
1363 this.help = node.attrs.help || this.field.help;
1364 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1365 this.readonly = this.modifiers['readonly'] === true;
1366 this.required = this.modifiers['required'] === true;
1367 this.invalid = this.dirty = false;
1369 this.classname = 'oe_form_field_' + this.type;
1372 this._super.apply(this, arguments);
1373 if (this.field.translate) {
1374 this.view.translatable_fields.push(this);
1375 this.$element.addClass('oe_form_field_translatable');
1376 this.$element.find('.oe_field_translate').click(this.on_translate);
1378 if (this.nolabel && openerp.connection.debug) {
1379 this.do_attach_tooltip(this, this.$element);
1382 set_value: function(value) {
1384 this.invalid = false;
1386 this.on_value_changed();
1388 set_value_from_ui: function() {
1389 this.on_value_changed();
1391 on_value_changed: function() {
1393 on_translate: function() {
1394 this.view.open_translate_dialog(this);
1396 get_value: function() {
1399 is_valid: function() {
1400 return !this.invalid;
1402 is_dirty: function() {
1403 return this.dirty && !this.readonly;
1405 get_on_change_value: function() {
1406 return this.get_value();
1408 update_dom: function(show_invalid) {
1409 this._super.apply(this, arguments);
1410 if (this.field.translate) {
1411 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1413 if (!this.disable_utility_classes) {
1414 this.$element.toggleClass('disabled', this.readonly);
1415 this.$element.toggleClass('required', this.required);
1417 this.$element.toggleClass('invalid', !this.is_valid());
1421 on_ui_change: function() {
1424 if (this.is_valid()) {
1425 this.set_value_from_ui();
1426 this.view.do_onchange(this);
1427 this.view.on_form_changed(true);
1428 this.view.do_notify_change();
1430 this.update_dom(true);
1433 validate: function() {
1434 this.invalid = false;
1436 focus: function($element) {
1438 setTimeout(function() {
1446 get_definition_options: function() {
1447 if (!this.definition_options) {
1448 var str = this.node.attrs.options || '{}';
1449 this.definition_options = JSON.parse(str);
1451 return this.definition_options;
1455 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1456 template: 'FieldChar',
1457 init: function (view, node) {
1458 this._super(view, node);
1459 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1462 this._super.apply(this, arguments);
1463 this.$element.find('input').change(this.on_ui_change);
1465 set_value: function(value) {
1466 this._super.apply(this, arguments);
1467 var show_value = openerp.web.format_value(value, this, '');
1468 this.$element.find('input').val(show_value);
1471 update_dom: function() {
1472 this._super.apply(this, arguments);
1473 this.$element.find('input').prop('readonly', this.readonly);
1475 set_value_from_ui: function() {
1476 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1479 validate: function() {
1480 this.invalid = false;
1482 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1483 this.invalid = this.required && value === '';
1485 this.invalid = true;
1488 focus: function($element) {
1489 this._super($element || this.$element.find('input:first'));
1493 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1494 update_dom: function() {
1495 this._super.apply(this, arguments);
1496 this.$element.find('input').prop('readonly', true);
1500 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1501 template: 'FieldEmail',
1503 this._super.apply(this, arguments);
1504 this.$element.find('button').click(this.on_button_clicked);
1506 on_button_clicked: function() {
1507 if (!this.value || !this.is_valid()) {
1508 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1510 location.href = 'mailto:' + this.value;
1515 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1516 template: 'FieldUrl',
1518 this._super.apply(this, arguments);
1519 this.$element.find('button').click(this.on_button_clicked);
1521 on_button_clicked: function() {
1523 this.do_warn("Resource error", "This resource is empty");
1525 window.open(this.value);
1530 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1531 init: function (view, node) {
1532 this._super(view, node);
1533 if (node.attrs.digits) {
1534 this.digits = py.eval(node.attrs.digits).toJSON();
1536 this.digits = view.fields_view.fields[node.attrs.name].digits;
1539 set_value: function(value) {
1540 if (value === false || value === undefined) {
1541 // As in GTK client, floats default to 0
1544 this._super.apply(this, [value]);
1548 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1549 template: "web.datetimepicker",
1550 jqueryui_object: 'datetimepicker',
1551 type_of_date: "datetime",
1552 init: function(parent) {
1553 this._super(parent);
1554 this.name = parent.name;
1558 this.$input = this.$element.find('input.oe_datepicker_master');
1559 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1560 this.$input.change(this.on_change);
1562 onSelect: this.on_picker_select,
1566 showButtonPanel: true
1568 this.$element.find('img.oe_datepicker_trigger').click(function() {
1569 if (!self.readonly && !self.picker('widget').is(':visible')) {
1570 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1571 self.$input_picker.show();
1572 self.picker('show');
1573 self.$input_picker.hide();
1576 this.set_readonly(false);
1579 picker: function() {
1580 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1582 on_picker_select: function(text, instance) {
1583 var date = this.picker('getDate');
1584 this.$input.val(date ? this.format_client(date) : '').change();
1586 set_value: function(value) {
1588 this.$input.val(value ? this.format_client(value) : '');
1590 get_value: function() {
1593 set_value_from_ui: function() {
1594 var value = this.$input.val() || false;
1595 this.value = this.parse_client(value);
1597 set_readonly: function(readonly) {
1598 this.readonly = readonly;
1599 this.$input.prop('readonly', this.readonly);
1600 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1602 is_valid: function(required) {
1603 var value = this.$input.val();
1608 this.parse_client(value);
1615 parse_client: function(v) {
1616 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1618 format_client: function(v) {
1619 return openerp.web.format_value(v, {"widget": this.type_of_date});
1621 on_change: function() {
1622 if (this.is_valid()) {
1623 this.set_value_from_ui();
1628 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1629 jqueryui_object: 'datepicker',
1630 type_of_date: "date"
1633 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1634 template: "EmptyComponent",
1635 build_widget: function() {
1636 return new openerp.web.DateTimeWidget(this);
1640 this._super.apply(this, arguments);
1641 this.datewidget = this.build_widget();
1642 this.datewidget.on_change.add_last(this.on_ui_change);
1643 this.datewidget.appendTo(this.$element);
1645 set_value: function(value) {
1647 this.datewidget.set_value(value);
1649 get_value: function() {
1650 return this.datewidget.get_value();
1652 update_dom: function() {
1653 this._super.apply(this, arguments);
1654 this.datewidget.set_readonly(this.readonly);
1656 validate: function() {
1657 this.invalid = !this.datewidget.is_valid(this.required);
1659 focus: function($element) {
1660 this._super($element || this.datewidget.$input);
1664 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1665 build_widget: function() {
1666 return new openerp.web.DateWidget(this);
1670 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1671 template: 'FieldText',
1673 this._super.apply(this, arguments);
1674 this.$element.find('textarea').change(this.on_ui_change);
1675 this.resized = false;
1677 set_value: function(value) {
1678 this._super.apply(this, arguments);
1679 var show_value = openerp.web.format_value(value, this, '');
1680 this.$element.find('textarea').val(show_value);
1681 if (!this.resized && this.view.options.resize_textareas) {
1682 this.do_resize(this.view.options.resize_textareas);
1683 this.resized = true;
1686 update_dom: function() {
1687 this._super.apply(this, arguments);
1688 this.$element.find('textarea').prop('readonly', this.readonly);
1690 set_value_from_ui: function() {
1691 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1694 validate: function() {
1695 this.invalid = false;
1697 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1698 this.invalid = this.required && value === '';
1700 this.invalid = true;
1703 focus: function($element) {
1704 this._super($element || this.$element.find('textarea:first'));
1706 do_resize: function(max_height) {
1707 max_height = parseInt(max_height, 10);
1708 var $input = this.$element.find('textarea'),
1709 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1711 $div.text($input.val());
1712 _.each('font-family,font-size,white-space'.split(','), function(style) {
1713 $div.css(style, $input.css(style));
1715 $div.appendTo($('body'));
1716 new_height = $div.height();
1717 if (new_height < 90) {
1720 if (!isNaN(max_height) && new_height > max_height) {
1721 new_height = max_height;
1724 $input.height(new_height);
1727 this.resized = false;
1731 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1732 template: 'FieldBoolean',
1735 this._super.apply(this, arguments);
1736 this.$element.find('input').click(self.on_ui_change);
1738 set_value: function(value) {
1739 this._super.apply(this, arguments);
1740 this.$element.find('input')[0].checked = value;
1742 set_value_from_ui: function() {
1743 this.value = this.$element.find('input').is(':checked');
1746 update_dom: function() {
1747 this._super.apply(this, arguments);
1748 this.$element.find('input').prop('disabled', this.readonly);
1750 focus: function($element) {
1751 this._super($element || this.$element.find('input:first'));
1755 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1756 template: 'FieldProgressBar',
1758 this._super.apply(this, arguments);
1759 this.$element.find('div').progressbar({
1761 disabled: this.readonly
1764 set_value: function(value) {
1765 this._super.apply(this, arguments);
1766 var show_value = Number(value);
1767 if (isNaN(show_value)) {
1770 var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1771 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1775 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1776 // to replace view editor
1779 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1780 template: 'FieldSelection',
1781 init: function(view, node) {
1783 this._super(view, node);
1784 this.values = _.clone(this.field.selection);
1785 _.each(this.values, function(v, i) {
1786 if (v[0] === false && v[1] === '') {
1787 self.values.splice(i, 1);
1790 this.values.unshift([false, '']);
1793 // Flag indicating whether we're in an event chain containing a change
1794 // event on the select, in order to know what to do on keyup[RETURN]:
1795 // * If the user presses [RETURN] as part of changing the value of a
1796 // selection, we should just let the value change and not let the
1797 // event broadcast further (e.g. to validating the current state of
1798 // the form in editable list view, which would lead to saving the
1799 // current row or switching to the next one)
1800 // * If the user presses [RETURN] with a select closed (side-effect:
1801 // also if the user opened the select and pressed [RETURN] without
1802 // changing the selected value), takes the action as validating the
1804 var ischanging = false;
1805 this._super.apply(this, arguments);
1806 this.$element.find('select')
1807 .change(this.on_ui_change)
1808 .change(function () { ischanging = true; })
1809 .click(function () { ischanging = false; })
1810 .keyup(function (e) {
1811 if (e.which !== 13 || !ischanging) { return; }
1812 e.stopPropagation();
1816 set_value: function(value) {
1817 value = value === null ? false : value;
1818 value = value instanceof Array ? value[0] : value;
1821 for (var i = 0, ii = this.values.length; i < ii; i++) {
1822 if (this.values[i][0] === value) index = i;
1824 this.$element.find('select')[0].selectedIndex = index;
1826 set_value_from_ui: function() {
1827 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1830 update_dom: function() {
1831 this._super.apply(this, arguments);
1832 this.$element.find('select').prop('disabled', this.readonly);
1834 validate: function() {
1835 var value = this.values[this.$element.find('select')[0].selectedIndex];
1836 this.invalid = !(value && !(this.required && value[0] === false));
1838 focus: function($element) {
1839 this._super($element || this.$element.find('select:first'));
1843 // jquery autocomplete tweak to allow html
1845 var proto = $.ui.autocomplete.prototype,
1846 initSource = proto._initSource;
1848 function filter( array, term ) {
1849 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1850 return $.grep( array, function(value) {
1851 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1856 _initSource: function() {
1857 if ( this.options.html && $.isArray(this.options.source) ) {
1858 this.source = function( request, response ) {
1859 response( filter( this.options.source, request.term ) );
1862 initSource.call( this );
1866 _renderItem: function( ul, item) {
1867 return $( "<li></li>" )
1868 .data( "item.autocomplete", item )
1869 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1875 openerp.web.form.dialog = function(content, options) {
1876 options = _.extend({
1881 var dialog = new openerp.web.Dialog(null, options, content).open();
1882 return dialog.$element;
1885 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1886 template: 'FieldMany2One',
1887 init: function(view, node) {
1888 this._super(view, node);
1891 this.cm_id = _.uniqueId('m2o_cm_');
1892 this.last_search = [];
1893 this.tmp_value = undefined;
1898 this.$input = this.$element.find("input");
1899 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1900 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1903 var init_context_menu_def = $.Deferred().then(function(e) {
1904 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1905 rdataset.call("get", ['action', 'client_action_relate',
1906 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1907 .then(function(result) {
1908 self.related_entries = result;
1910 var $cmenu = $("#" + self.cm_id);
1911 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1913 bindings[self.cm_id + "_search"] = function() {
1916 self._search_create_popup("search");
1918 bindings[self.cm_id + "_create"] = function() {
1921 self._search_create_popup("form");
1923 bindings[self.cm_id + "_open"] = function() {
1927 var pop = new openerp.web.form.FormOpenPopup(self.view);
1929 self.field.relation,
1931 self.build_context(),
1933 title: _t("Open: ") + (self.string || self.name)
1936 pop.on_write_completed.add_last(function() {
1937 self.set_value(self.value[0]);
1940 _.each(_.range(self.related_entries.length), function(i) {
1941 bindings[self.cm_id + "_related_" + i] = function() {
1942 self.open_related(self.related_entries[i]);
1945 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1946 bindings: bindings, itemStyle: {"color": ""},
1947 onContextMenu: function() {
1949 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1951 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1953 if (!self.readonly) {
1954 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1956 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1959 }, menuStyle: {width: "200px"}
1961 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1964 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1965 this.$menu_btn.click(ctx_callback);
1967 // some behavior for input
1968 this.$input.keyup(function() {
1969 if (self.$input.val() === "") {
1970 self._change_int_value(null);
1971 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1972 self._change_int_value(undefined);
1975 this.$drop_down.click(function() {
1978 if (self.$input.autocomplete("widget").is(":visible")) {
1979 self.$input.autocomplete("close");
1982 self.$input.autocomplete("search", "");
1984 self.$input.autocomplete("search");
1986 self.$input.focus();
1989 var anyoneLoosesFocus = function() {
1990 if (!self.$input.is(":focus") &&
1991 !self.$input.autocomplete("widget").is(":visible") &&
1993 if (self.value === undefined && self.last_search.length > 0) {
1994 self._change_int_ext_value(self.last_search[0]);
1996 self._change_int_ext_value(null);
2000 this.$input.focusout(anyoneLoosesFocus);
2002 var isSelecting = false;
2004 this.$input.autocomplete({
2005 source: function(req, resp) { self.get_search_result(req, resp); },
2006 select: function(event, ui) {
2010 self._change_int_value([item.id, item.name]);
2011 } else if (item.action) {
2012 self._change_int_value(undefined);
2017 focus: function(e, ui) {
2021 close: anyoneLoosesFocus,
2025 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2026 this.$input.keyup(function(e) {
2027 if (e.which === 13) {
2029 e.stopPropagation();
2031 isSelecting = false;
2034 // autocomplete component content handling
2035 get_search_result: function(request, response) {
2036 var search_val = request.term;
2039 if (this.abort_last) {
2041 delete this.abort_last;
2043 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2045 dataset.name_search(search_val, self.build_domain(), 'ilike',
2046 this.limit + 1, function(data) {
2047 self.last_search = data;
2048 // possible selections for the m2o
2049 var values = _.map(data, function(x) {
2051 label: _.str.escapeHTML(x[1]),
2058 // search more... if more results that max
2059 if (values.length > self.limit) {
2060 var open_search_popup = function(data) {
2061 self._change_int_value(null);
2062 self._search_create_popup("search", data);
2064 values = values.slice(0, self.limit);
2065 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2067 // search optimisation - in case user didn't enter any text we
2068 // do not need to prefilter records; for big datasets (ex: more
2069 // that 10.000 records) calling name_search() could be very very
2071 open_search_popup();
2074 dataset.name_search(search_val, self.build_domain(),
2075 'ilike', false, open_search_popup);
2079 var raw_result = _(data.result).map(function(x) {return x[1];});
2080 if (search_val.length > 0 &&
2081 !_.include(raw_result, search_val) &&
2082 (!self.value || search_val !== self.value[1])) {
2083 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2084 $('<span />').text(search_val).html()), action: function() {
2085 self._quick_create(search_val);
2089 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2090 self._change_int_value(null);
2091 self._search_create_popup("form", undefined, {"default_name": search_val});
2096 this.abort_last = dataset.abort_last;
2098 _quick_create: function(name) {
2100 var slow_create = function () {
2101 self._change_int_value(null);
2102 self._search_create_popup("form", undefined, {"default_name": name});
2104 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2105 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2106 dataset.name_create(name, function(data) {
2107 self._change_int_ext_value(data);
2108 }).fail(function(error, event) {
2109 event.preventDefault();
2115 // all search/create popup handling
2116 _search_create_popup: function(view, ids, context) {
2118 var pop = new openerp.web.form.SelectCreatePopup(this);
2120 self.field.relation,
2122 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2123 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2125 disable_multiple_selection: true
2127 self.build_domain(),
2128 new openerp.web.CompoundContext(self.build_context(), context || {})
2130 pop.on_select_elements.add(function(element_ids) {
2131 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2132 dataset.name_get([element_ids[0]], function(data) {
2133 self._change_int_ext_value(data[0]);
2137 _change_int_ext_value: function(value) {
2138 this._change_int_value(value);
2139 this.$input.val(this.value ? this.value[1] : "");
2141 _change_int_value: function(value) {
2143 var back_orig_value = this.original_value;
2144 if (this.value === null || this.value) {
2145 this.original_value = this.value;
2147 if (back_orig_value === undefined) { // first use after a set_value()
2150 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2151 !== (this.value ? this.value[0] : null))) {
2152 this.on_ui_change();
2155 set_value: function(value) {
2156 value = value || null;
2157 this.invalid = false;
2159 this.tmp_value = value;
2161 self.on_value_changed();
2162 var real_set_value = function(rval) {
2163 self.tmp_value = undefined;
2165 self.original_value = undefined;
2166 self._change_int_ext_value(rval);
2168 if (value && !(value instanceof Array)) {
2169 // name_get in a m2o does not use the context of the field
2170 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2171 dataset.name_get([value], function(data) {
2172 real_set_value(data[0]);
2173 }).fail(function() {self.tmp_value = undefined;});
2175 $.async_when().then(function() {real_set_value(value);});
2178 get_value: function() {
2179 if (this.tmp_value !== undefined) {
2180 if (this.tmp_value instanceof Array) {
2181 return this.tmp_value[0];
2183 return this.tmp_value ? this.tmp_value : false;
2185 if (this.value === undefined)
2186 return this.original_value ? this.original_value[0] : false;
2187 return this.value ? this.value[0] : false;
2189 validate: function() {
2190 this.invalid = false;
2191 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2193 this.invalid = this.required;
2196 open_related: function(related) {
2200 var additional_context = {
2201 active_id: self.value[0],
2202 active_ids: [self.value[0]],
2203 active_model: self.field.relation
2205 self.rpc("/web/action/load", {
2206 action_id: related[2].id,
2207 context: additional_context
2208 }, function(result) {
2209 result.result.context = _.extend(result.result.context || {}, additional_context);
2210 self.do_action(result.result);
2213 focus: function ($element) {
2214 this._super($element || this.$input);
2216 update_dom: function() {
2217 this._super.apply(this, arguments);
2218 this.$input.prop('readonly', this.readonly);
2223 # Values: (0, 0, { fields }) create
2224 # (1, ID, { fields }) update
2225 # (2, ID) remove (delete)
2226 # (3, ID) unlink one (target id or target of relation)
2228 # (5) unlink all (only valid for one2many)
2233 'create': function (values) {
2234 return [commands.CREATE, false, values];
2236 // (1, id, {values})
2238 'update': function (id, values) {
2239 return [commands.UPDATE, id, values];
2243 'delete': function (id) {
2244 return [commands.DELETE, id, false];
2246 // (3, id[, _]) removes relation, but not linked record itself
2248 'forget': function (id) {
2249 return [commands.FORGET, id, false];
2253 'link_to': function (id) {
2254 return [commands.LINK_TO, id, false];
2258 'delete_all': function () {
2259 return [5, false, false];
2261 // (6, _, ids) replaces all linked records with provided ids
2263 'replace_with': function (ids) {
2264 return [6, false, ids];
2267 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2268 template: 'FieldOne2Many',
2269 multi_selection: false,
2270 init: function(view, node) {
2271 this._super(view, node);
2272 this.is_loaded = $.Deferred();
2273 this.initial_is_loaded = this.is_loaded;
2274 this.is_setted = $.Deferred();
2275 this.form_last_update = $.Deferred();
2276 this.init_form_last_update = this.form_last_update;
2277 this.disable_utility_classes = true;
2280 this._super.apply(this, arguments);
2284 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2285 this.dataset.o2m = this;
2286 this.dataset.parent_view = this.view;
2287 this.dataset.child_name = this.name;
2288 //this.dataset.child_name =
2289 this.dataset.on_change.add_last(function() {
2290 self.trigger_on_change();
2293 this.is_setted.then(function() {
2297 trigger_on_change: function() {
2298 var tmp = this.doing_on_change;
2299 this.doing_on_change = true;
2300 this.on_ui_change();
2301 this.doing_on_change = tmp;
2303 is_readonly: function() {
2304 return this.readonly || this.force_readonly;
2306 load_views: function() {
2309 var modes = this.node.attrs.mode;
2310 modes = !!modes ? modes.split(",") : ["tree"];
2312 _.each(modes, function(mode) {
2315 view_type: mode == "tree" ? "list" : mode,
2316 options: { sidebar : false }
2318 if (self.field.views && self.field.views[mode]) {
2319 view.embedded_view = self.field.views[mode];
2321 if(view.view_type === "list") {
2322 view.options.selectable = self.multi_selection;
2323 if (self.is_readonly()) {
2324 view.options.addable = null;
2325 view.options.deletable = null;
2326 view.options.isClarkGable = false;
2328 } else if (view.view_type === "form") {
2329 if (self.is_readonly()) {
2330 view.view_type = 'page';
2332 view.options.not_interactible_on_create = true;
2338 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2339 this.viewmanager.template = 'One2Many.viewmanager';
2340 this.viewmanager.registry = openerp.web.views.extend({
2341 list: 'openerp.web.form.One2ManyListView',
2342 form: 'openerp.web.form.One2ManyFormView',
2343 page: 'openerp.web.PageView'
2345 var once = $.Deferred().then(function() {
2346 self.init_form_last_update.resolve();
2348 var def = $.Deferred().then(function() {
2349 self.initial_is_loaded.resolve();
2351 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2352 if (view_type == "list") {
2353 controller.o2m = self;
2354 if (self.is_readonly())
2355 controller.set_editable(false);
2356 } else if (view_type == "form" || view_type == 'page') {
2357 if (view_type == 'page' || self.is_readonly()) {
2358 $(".oe_form_buttons", controller.$element).children().remove();
2360 controller.on_record_loaded.add_last(function() {
2363 controller.on_pager_action.add_first(function() {
2364 self.save_any_view();
2366 } else if (view_type == "graph") {
2367 self.reload_current_view()
2371 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2372 $.when(self.save_any_view()).then(function() {
2373 if(n_mode === "list")
2374 $.async_when().then(function() {self.reload_current_view();});
2377 this.is_setted.then(function() {
2378 $.async_when().then(function () {
2379 self.viewmanager.appendTo(self.$element);
2384 reload_current_view: function() {
2386 return self.is_loaded = self.is_loaded.pipe(function() {
2387 var active_view = self.viewmanager.active_view;
2388 var view = self.viewmanager.views[active_view].controller;
2389 if(active_view === "list") {
2390 return view.reload_content();
2391 } else if (active_view === "form" || active_view === 'page') {
2392 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2393 self.dataset.index = 0;
2395 var act = function() {
2396 return view.do_show();
2398 self.form_last_update = self.form_last_update.pipe(act, act);
2399 return self.form_last_update;
2400 } else if (active_view === "graph") {
2401 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2405 set_value: function(value) {
2406 value = value || [];
2408 this.dataset.reset_ids([]);
2409 if(value.length >= 1 && value[0] instanceof Array) {
2411 _.each(value, function(command) {
2412 var obj = {values: command[2]};
2413 switch (command[0]) {
2414 case commands.CREATE:
2415 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2417 self.dataset.to_create.push(obj);
2418 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2421 case commands.UPDATE:
2422 obj['id'] = command[1];
2423 self.dataset.to_write.push(obj);
2424 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2427 case commands.DELETE:
2428 self.dataset.to_delete.push({id: command[1]});
2430 case commands.LINK_TO:
2431 ids.push(command[1]);
2433 case commands.DELETE_ALL:
2434 self.dataset.delete_all = true;
2439 this.dataset.set_ids(ids);
2440 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2442 this.dataset.delete_all = true;
2443 _.each(value, function(command) {
2444 var obj = {values: command};
2445 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2447 self.dataset.to_create.push(obj);
2448 self.dataset.cache.push(_.clone(obj));
2452 this.dataset.set_ids(ids);
2455 this.dataset.reset_ids(value);
2457 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2458 this.dataset.index = 0;
2460 self.is_setted.resolve();
2461 return self.reload_current_view();
2463 get_value: function() {
2467 this.save_any_view();
2468 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2469 val = val.concat(_.map(this.dataset.ids, function(id) {
2470 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2472 return commands.create(alter_order.values);
2474 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2476 return commands.update(alter_order.id, alter_order.values);
2478 return commands.link_to(id);
2480 return val.concat(_.map(
2481 this.dataset.to_delete, function(x) {
2482 return commands['delete'](x.id);}));
2484 save_any_view: function() {
2485 if (this.doing_on_change)
2487 return this.session.synchronized_mode(_.bind(function() {
2488 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2489 this.viewmanager.views[this.viewmanager.active_view] &&
2490 this.viewmanager.views[this.viewmanager.active_view].controller) {
2491 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2492 if (this.viewmanager.active_view === "form") {
2493 if (!view.is_initialized.isResolved()) {
2496 var res = $.when(view.do_save());
2497 if (!res.isResolved() && !res.isRejected()) {
2498 console.warn("Asynchronous get_value() is not supported in form view.");
2501 } else if (this.viewmanager.active_view === "list") {
2502 var res = $.when(view.ensure_saved());
2503 if (!res.isResolved() && !res.isRejected()) {
2504 console.warn("Asynchronous get_value() is not supported in list view.");
2512 is_valid: function() {
2513 if (!this.viewmanager.views[this.viewmanager.active_view])
2515 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2516 switch (this.viewmanager.active_view) {
2518 return _(view.fields).chain()
2524 return view.is_valid();
2528 is_dirty: function() {
2529 this.save_any_view();
2530 return this._super();
2532 update_dom: function() {
2533 this._super.apply(this, arguments);
2535 if (this.previous_readonly !== this.readonly) {
2536 this.previous_readonly = this.readonly;
2537 if (this.viewmanager) {
2538 this.is_loaded = this.is_loaded.pipe(function() {
2539 self.viewmanager.stop();
2540 return $.when(self.load_views()).then(function() {
2541 self.reload_current_view();
2549 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2550 get_context: function() {
2551 this.context = this.o2m.build_context([this.o2m.name]);
2552 return this.context;
2556 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2557 _template: 'One2Many.listview',
2558 init: function (parent, dataset, view_id, options) {
2559 this._super(parent, dataset, view_id, _.extend(options || {}, {
2560 ListType: openerp.web.form.One2ManyList
2563 is_valid: function () {
2565 // A list not being edited is always valid
2566 if (!(form = this.first_edition_form())) {
2569 // If the form has not been modified, the view can only be valid
2570 // NB: is_dirty will also be set on defaults/onchanges/whatever?
2571 // oe_form_dirty seems to only be set on actual user actions
2572 if (!form.$element.is('.oe_form_dirty')) {
2576 // Otherwise validate internal form
2577 return _(form.fields).chain()
2578 .invoke(function () {
2580 this.update_dom(true);
2581 return this.is_valid();
2586 first_edition_form: function () {
2587 var get_form = function (group_or_list) {
2588 if (group_or_list.edition) {
2589 return group_or_list.edition_form;
2591 return _(group_or_list.children).chain()
2597 return get_form(this.groups);
2599 do_add_record: function () {
2600 if (this.options.editable) {
2601 this._super.apply(this, arguments);
2604 var pop = new openerp.web.form.SelectCreatePopup(this);
2605 pop.on_default_get.add(self.dataset.on_default_get);
2607 self.o2m.field.relation,
2609 title: _t("Create: ") + self.name,
2610 initial_view: "form",
2611 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2612 create_function: function(data, callback, error_callback) {
2613 return self.o2m.dataset.create(data).then(function(r) {
2614 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2615 self.o2m.dataset.on_change();
2616 }).then(callback, error_callback);
2618 read_function: function() {
2619 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2621 parent_view: self.o2m.view,
2622 child_name: self.o2m.name,
2623 form_view_options: {'not_interactible_on_create':true}
2625 self.o2m.build_domain(),
2626 self.o2m.build_context()
2628 pop.on_select_elements.add_last(function() {
2629 self.o2m.reload_current_view();
2633 do_activate_record: function(index, id) {
2635 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2636 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2637 title: _t("Open: ") + self.name,
2639 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2640 parent_view: self.o2m.view,
2641 child_name: self.o2m.name,
2642 read_function: function() {
2643 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2645 form_view_options: {'not_interactible_on_create':true},
2646 readonly: self.o2m.is_readonly()
2648 pop.dataset.call_button = function() {
2649 var button_result = self.o2m.dataset.call_button.apply(self.o2m.dataset, arguments);
2650 self.o2m.reload_current_view();
2651 return button_result;
2653 pop.on_write.add(function(id, data) {
2654 self.o2m.dataset.write(id, data, {}, function(r) {
2655 self.o2m.reload_current_view();
2659 do_button_action: function (name, id, callback) {
2661 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2662 return this._super(name, id, _.bind(def.resolve, def));
2665 openerp.web.form.One2ManyList = openerp.web.ListView.List.extend({
2666 render_row_as_form: function () {
2668 return this._super.apply(this, arguments).then(function () {
2669 self.setup_save_on_row_blur();
2672 bind_blur_focus: function (new_row, onblur, onfocus) {
2673 if (new_row.addEventListener) {
2674 new_row.addEventListener('blur', onblur, true);
2675 new_row.addEventListener('focus', onfocus, true);
2677 new_row.onfocusout = onblur;
2678 new_row.onfocusin = onfocus;
2681 setup_save_on_row_blur: function () {
2683 var form = this.edition_form;
2684 this.bind_blur_focus(this.edition_form.$element[0], function () {
2685 self._save_row_timeout = setTimeout(function () {
2686 if (form.widget_is_stopped) {
2687 // Saved or cancelled already, maybe?
2690 self.view.ensure_saved();
2693 clearTimeout(self._save_row_timeout);
2694 delete self._save_row_timeout;
2699 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2700 form_template: 'One2Many.formview',
2701 on_loaded: function(data) {
2704 this.$form_header.find('button.oe_form_button_create').click(function() {
2705 self.do_save().then(self.on_button_new);
2708 do_notify_change: function() {
2709 if (this.dataset.parent_view) {
2710 this.dataset.parent_view.do_notify_change();
2712 this._super.apply(this, arguments);
2717 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2718 template: 'FieldMany2Many',
2719 multi_selection: false,
2720 init: function(view, node) {
2721 this._super(view, node);
2722 this.list_id = _.uniqueId("many2many");
2723 this.is_loaded = $.Deferred();
2724 this.initial_is_loaded = this.is_loaded;
2725 this.is_setted = $.Deferred();
2728 this._super.apply(this, arguments);
2732 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2733 this.dataset.m2m = this;
2734 this.dataset.on_unlink.add_last(function(ids) {
2735 self.on_ui_change();
2738 this.is_setted.then(function() {
2742 set_value: function(value) {
2743 value = value || [];
2744 if (value.length >= 1 && value[0] instanceof Array) {
2745 value = value[0][2];
2748 this.dataset.set_ids(value);
2750 self.reload_content();
2751 this.is_setted.resolve();
2753 get_value: function() {
2754 return [commands.replace_with(this.dataset.ids)];
2756 validate: function() {
2757 this.invalid = this.required && _(this.dataset.ids).isEmpty();
2759 is_readonly: function() {
2760 return this.readonly || this.force_readonly;
2762 load_view: function() {
2764 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2765 'addable': self.is_readonly() ? null : _t("Add"),
2766 'deletable': self.is_readonly() ? false : true,
2767 'selectable': self.multi_selection,
2768 'isClarkGable': self.is_readonly() ? false : true
2770 var embedded = (this.field.views || {}).tree;
2772 this.list_view.set_embedded_view(embedded);
2774 this.list_view.m2m_field = this;
2775 var loaded = $.Deferred();
2776 this.list_view.on_loaded.add_last(function() {
2777 self.initial_is_loaded.resolve();
2780 $.async_when().then(function () {
2781 self.list_view.appendTo($("#" + self.list_id));
2785 reload_content: function() {
2787 this.is_loaded = this.is_loaded.pipe(function() {
2788 return self.list_view.reload_content();
2791 update_dom: function() {
2792 this._super.apply(this, arguments);
2794 if (this.previous_readonly !== this.readonly) {
2795 this.previous_readonly = this.readonly;
2796 if (this.list_view) {
2797 this.is_loaded = this.is_loaded.pipe(function() {
2798 self.list_view.stop();
2799 return $.when(self.load_view()).then(function() {
2800 self.reload_content();
2808 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2809 get_context: function() {
2810 this.context = this.m2m.build_context();
2811 return this.context;
2817 * @extends openerp.web.ListView
2819 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2820 do_add_record: function () {
2821 var pop = new openerp.web.form.SelectCreatePopup(this);
2825 title: _t("Add: ") + this.name
2827 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2828 this.m2m_field.build_context()
2831 pop.on_select_elements.add(function(element_ids) {
2832 _.each(element_ids, function(element_id) {
2833 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2834 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2835 self.m2m_field.on_ui_change();
2836 self.reload_content();
2841 do_activate_record: function(index, id) {
2843 var pop = new openerp.web.form.FormOpenPopup(this);
2844 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2845 title: _t("Open: ") + this.name,
2846 readonly: this.widget_parent.is_readonly()
2848 pop.on_write_completed.add_last(function() {
2849 self.reload_content();
2856 * @extends openerp.web.OldWidget
2858 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2859 template: "SelectCreatePopup",
2863 * - initial_view: form or search (default search)
2864 * - disable_multiple_selection
2865 * - alternative_form_view
2866 * - create_function (defaults to a naive saving behavior)
2869 * - form_view_options
2870 * - list_view_options
2873 select_element: function(model, options, domain, context) {
2876 this.domain = domain || [];
2877 this.context = context || {};
2878 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2879 return self.create_row.apply(self, arguments);
2880 }, read_function: null});
2881 this.initial_ids = this.options.initial_ids;
2882 this.created_elements = [];
2883 this.render_element();
2884 openerp.web.form.dialog(this.$element, {
2888 title: options.title || ""
2895 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2897 this.dataset.create_function = function() {
2898 return self.options.create_function.apply(null, arguments).then(function(r) {
2899 self.created_elements.push(r.result);
2902 this.dataset.write_function = function() {
2903 return self.write_row.apply(self, arguments);
2905 this.dataset.read_function = this.options.read_function;
2906 this.dataset.parent_view = this.options.parent_view;
2907 this.dataset.child_name = this.options.child_name;
2908 this.dataset.on_default_get.add(this.on_default_get);
2909 if (this.options.initial_view == "search") {
2910 self.rpc('/web/session/eval_domain_and_context', {
2912 contexts: [this.context]
2913 }, function (results) {
2914 var search_defaults = {};
2915 _.each(results.context, function (value, key) {
2916 var match = /^search_default_(.*)$/.exec(key);
2918 search_defaults[match[1]] = value;
2921 self.setup_search_view(search_defaults);
2928 this.$element.dialog('close');
2931 setup_search_view: function(search_defaults) {
2933 if (this.searchview) {
2934 this.searchview.stop();
2936 this.searchview = new openerp.web.SearchView(this,
2937 this.dataset, false, search_defaults);
2938 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2939 if (self.initial_ids) {
2940 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2941 contexts, groupbys);
2942 self.initial_ids = undefined;
2944 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2947 this.searchview.on_loaded.add_last(function () {
2948 self.view_list = new openerp.web.form.SelectCreateListView(self,
2949 self.dataset, false,
2950 _.extend({'deletable': false,
2951 'selectable': !self.options.disable_multiple_selection
2952 }, self.options.list_view_options || {}));
2953 self.view_list.popup = self;
2954 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2955 self.view_list.do_show();
2956 }).pipe(function() {
2957 self.searchview.do_search();
2959 self.view_list.on_loaded.add_last(function() {
2960 var $buttons = self.view_list.$element.find(".oe-actions");
2961 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2962 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2963 $cbutton.click(function() {
2966 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2967 if(self.options.disable_multiple_selection) {
2970 $sbutton.click(function() {
2971 self.on_select_elements(self.selected_ids);
2976 this.searchview.appendTo($("#" + this.element_id + "_search"));
2978 do_search: function(domains, contexts, groupbys) {
2980 this.rpc('/web/session/eval_domain_and_context', {
2981 domains: domains || [],
2982 contexts: contexts || [],
2983 group_by_seq: groupbys || []
2984 }, function (results) {
2985 self.view_list.do_search(results.domain, results.context, results.group_by);
2988 create_row: function() {
2990 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2991 wdataset.parent_view = this.options.parent_view;
2992 wdataset.child_name = this.options.child_name;
2993 return wdataset.create.apply(wdataset, arguments);
2995 write_row: function() {
2997 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2998 wdataset.parent_view = this.options.parent_view;
2999 wdataset.child_name = this.options.child_name;
3000 return wdataset.write.apply(wdataset, arguments);
3002 on_select_elements: function(element_ids) {
3004 on_click_element: function(ids) {
3005 this.selected_ids = ids || [];
3006 if(this.selected_ids.length > 0) {
3007 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3009 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3012 new_object: function() {
3014 if (this.searchview) {
3015 this.searchview.hide();
3017 if (this.view_list) {
3018 this.view_list.$element.hide();
3020 this.dataset.index = null;
3021 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
3022 if (this.options.alternative_form_view) {
3023 this.view_form.set_embedded_view(this.options.alternative_form_view);
3025 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3026 this.view_form.on_loaded.add_last(function() {
3027 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3028 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
3029 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
3030 $nbutton.click(function() {
3031 $.when(self.view_form.do_save()).then(function() {
3032 self.view_form.reload_mutex.exec(function() {
3033 self.view_form.on_button_new();
3037 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
3038 $nbutton.click(function() {
3039 $.when(self.view_form.do_save()).then(function() {
3040 self.view_form.reload_mutex.exec(function() {
3045 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
3046 $cbutton.click(function() {
3050 this.view_form.do_show();
3052 check_exit: function() {
3053 if (this.created_elements.length > 0) {
3054 this.on_select_elements(this.created_elements);
3058 on_default_get: function(res) {}
3061 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
3062 do_add_record: function () {
3063 this.popup.new_object();
3065 select_record: function(index) {
3066 this.popup.on_select_elements([this.dataset.ids[index]]);
3069 do_select: function(ids, records) {
3070 this._super(ids, records);
3071 this.popup.on_click_element(ids);
3077 * @extends openerp.web.OldWidget
3079 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
3080 template: "FormOpenPopup",
3083 * - alternative_form_view
3084 * - auto_write (default true)
3088 * - form_view_options
3091 show_element: function(model, row_id, context, options) {
3093 this.row_id = row_id;
3094 this.context = context || {};
3095 this.options = _.defaults(options || {}, {"auto_write": true});
3096 this.render_element();
3097 this.$element.dialog({
3098 title: options.title || '',
3107 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3108 this.dataset.fop = this;
3109 this.dataset.ids = [this.row_id];
3110 this.dataset.index = 0;
3111 this.dataset.parent_view = this.options.parent_view;
3112 this.dataset.child_name = this.options.child_name;
3113 this.setup_form_view();
3115 on_write: function(id, data) {
3116 if (!this.options.auto_write)
3119 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3120 wdataset.parent_view = this.options.parent_view;
3121 wdataset.child_name = this.options.child_name;
3122 wdataset.write(id, data, {}, function(r) {
3123 self.on_write_completed();
3126 on_write_completed: function() {},
3127 setup_form_view: function() {
3129 var FormClass = this.options.readonly
3130 ? openerp.web.views.get_object('page')
3131 : openerp.web.views.get_object('form');
3132 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3133 if (this.options.alternative_form_view) {
3134 this.view_form.set_embedded_view(this.options.alternative_form_view);
3136 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3137 this.view_form.on_loaded.add_last(function() {
3138 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3139 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3140 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3141 $nbutton.click(function() {
3142 self.view_form.do_save().then(function() {
3146 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3147 $cbutton.click(function() {
3150 if (self.options.readonly) {
3152 $cbutton.text(_t("Close"));
3154 self.view_form.do_show();
3156 this.dataset.on_write.add(this.on_write);
3160 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3161 read_ids: function() {
3162 if (this.fop.options.read_function) {
3163 return this.fop.options.read_function.apply(null, arguments);
3165 return this._super.apply(this, arguments);
3170 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3171 template: 'FieldReference',
3172 init: function(view, node) {
3173 this._super(view, node);
3174 this.fields_view = {
3177 selection: view.fields_view.fields[this.name].selection
3184 this.get_fields_values = view.get_fields_values;
3185 this.get_selected_ids = view.get_selected_ids;
3186 this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3187 this.dataset = this.view.dataset;
3188 this.widgets_counter = 0;
3189 this.view_id = 'reference_' + _.uniqueId();
3192 this.fields_order = [];
3193 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3197 this.reference_ready = true;
3198 this.selection.on_value_changed.add_last(this.on_selection_changed);
3199 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3203 this.m2o.on_ui_change.add_last(this.on_ui_change);
3205 on_nop: function() {
3207 on_selection_changed: function() {
3208 if (this.reference_ready) {
3209 var sel = this.selection.get_value();
3210 this.m2o.field.relation = sel;
3211 this.m2o.set_value(null);
3212 this.m2o.$element.toggle(sel !== false);
3217 this.selection.start();
3220 is_valid: function() {
3221 return this.required === false || typeof(this.get_value()) === 'string';
3223 is_dirty: function() {
3224 return this.selection.is_dirty() || this.m2o.is_dirty();
3226 set_value: function(value) {
3228 this.reference_ready = false;
3229 var vals = [], sel_val, m2o_val;
3230 if (typeof(value) === 'string') {
3231 vals = value.split(',');
3233 sel_val = vals[0] || false;
3234 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3235 this.selection.set_value(sel_val);
3236 this.m2o.field.relation = sel_val;
3237 this.m2o.set_value(m2o_val);
3238 this.m2o.$element.toggle(sel_val !== false);
3239 this.reference_ready = true;
3241 get_value: function() {
3242 var model = this.selection.get_value(),
3243 id = this.m2o.get_value();
3244 if (typeof(model) === 'string' && typeof(id) === 'number') {
3245 return model + ',' + id;
3252 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3253 init: function(view, node) {
3254 this._super(view, node);
3255 this.iframe = this.element_id + '_iframe';
3256 this.binary_value = false;
3259 this._super.apply(this, arguments);
3260 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3261 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3262 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3264 human_filesize : function(size) {
3265 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3267 while (size >= 1024) {
3271 return size.toFixed(2) + ' ' + units[i];
3273 on_file_change: function(e) {
3274 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3275 // http://www.html5rocks.com/tutorials/file/dndfiles/
3276 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3277 window[this.iframe] = this.on_file_uploaded;
3278 if ($(e.target).val() != '') {
3279 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3280 this.$element.find('form.oe-binary-form').submit();
3281 this.$element.find('.oe-binary-progress').show();
3282 this.$element.find('.oe-binary').hide();
3285 on_file_uploaded: function(size, name, content_type, file_base64) {
3286 delete(window[this.iframe]);
3287 if (size === false) {
3288 this.do_warn("File Upload", "There was a problem while uploading your file");
3289 // TODO: use openerp web crashmanager
3290 console.warn("Error while uploading file : ", name);
3292 this.on_file_uploaded_and_valid.apply(this, arguments);
3293 this.on_ui_change();
3295 this.$element.find('.oe-binary-progress').hide();
3296 this.$element.find('.oe-binary').show();
3298 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3300 on_save_as: function() {
3302 this.session.get_file({
3303 url: '/web/binary/saveas_ajax',
3304 data: {data: JSON.stringify({
3305 model: this.view.dataset.model,
3306 id: (this.view.datarecord.id || ''),
3308 filename_field: (this.node.attrs.filename || ''),
3309 context: this.view.dataset.get_context()
3311 complete: $.unblockUI,
3312 error: openerp.webclient.crashmanager.on_rpc_error
3315 set_filename: function(value) {
3316 var filename = this.node.attrs.filename;
3317 if (this.view.fields[filename]) {
3318 this.view.fields[filename].set_value(value);
3319 this.view.fields[filename].on_ui_change();
3322 on_clear: function() {
3323 if (this.value !== false) {
3325 this.binary_value = false;
3326 this.on_ui_change();
3332 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3333 template: 'FieldBinaryFile',
3334 update_dom: function() {
3335 this._super.apply(this, arguments);
3336 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3337 this.$element.find('input[type=text]').prop('readonly', this.readonly);
3339 set_value: function(value) {
3340 this._super.apply(this, arguments);
3342 if (this.node.attrs.filename) {
3343 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3345 show_value = (value != null && value !== false) ? value : '';
3347 this.$element.find('input').eq(0).val(show_value);
3349 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3350 this.value = file_base64;
3351 this.binary_value = true;
3352 var show_value = name + " (" + this.human_filesize(size) + ")";
3353 this.$element.find('input').eq(0).val(show_value);
3354 this.set_filename(name);
3356 on_clear: function() {
3357 this._super.apply(this, arguments);
3358 this.$element.find('input').eq(0).val('');
3359 this.set_filename('');
3363 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3364 template: 'FieldBinaryImage',
3366 this._super.apply(this, arguments);
3367 this.$image = this.$element.find('img.oe-binary-image');
3369 update_dom: function() {
3370 this._super.apply(this, arguments);
3371 this.$element.find('.oe-binary').toggle(!this.readonly);
3373 set_value: function(value) {
3374 this._super.apply(this, arguments);
3375 this.set_image_maxwidth();
3376 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3377 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3378 this.$image.attr('src', url);
3380 set_image_maxwidth: function() {
3381 this.$image.css('max-width', this.$element.width());
3383 on_file_change: function() {
3384 this.set_image_maxwidth();
3385 this._super.apply(this, arguments);
3387 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3388 this.value = file_base64;
3389 this.binary_value = true;
3390 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3391 this.set_filename(name);
3393 on_clear: function() {
3394 this._super.apply(this, arguments);
3395 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3396 this.set_filename('');
3400 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3401 template: "EmptyComponent",
3404 this.selected_value = null;
3408 set_value: function(value) {
3410 this.selected_value = value;
3414 render_list: function() {
3416 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3417 function(x) { return _.str.trim(x); });
3418 shown = _.select(shown, function(x) { return x.length > 0; });
3420 if (shown.length == 0) {
3421 this.to_show = this.field.selection;
3423 this.to_show = _.select(this.field.selection, function(x) {
3424 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3428 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3429 this.$element.html(content);
3431 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3432 var color = colors[this.selected_value];
3434 var elem = this.$element.find("li.oe-arrow-list-selected span");
3435 elem.css("border-color", color);
3436 if (this.check_white(color))
3437 elem.css("color", "white");
3438 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3439 elem.css("border-left-color", "transparent");
3440 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3441 elem.css("border-color", "transparent");
3442 elem.css("border-left-color", color);
3445 check_white: function(color) {
3446 var div = $("<div></div>");
3447 div.css("display", "none");
3448 div.css("color", color);
3449 div.appendTo($("body"));
3450 var ncolor = div.css("color");
3452 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3456 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3457 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3465 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3466 render: function () {
3467 var $root = $('<div class="oe_form_html_view">');
3468 this.render_children(this, $root);
3469 return $root.html();
3471 render_children: function (object, $into) {
3473 fields = this.view.fields_view.fields;
3474 _(object.children).each(function (child) {
3475 if (typeof child === 'string') {
3477 } else if (child.tag === 'field') {
3479 new (self.view.registry.get_object('frame'))(
3480 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3483 var $child = $(document.createElement(child.tag))
3486 self.render_children(child, $child);
3494 * Registry of form widgets, called by :js:`openerp.web.FormView`
3496 openerp.web.form.widgets = new openerp.web.Registry({
3497 'frame' : 'openerp.web.form.WidgetFrame',
3498 'group' : 'openerp.web.form.WidgetGroup',
3499 'notebook' : 'openerp.web.form.WidgetNotebook',
3500 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3501 'separator' : 'openerp.web.form.WidgetSeparator',
3502 'label' : 'openerp.web.form.WidgetLabel',
3503 'button' : 'openerp.web.form.WidgetButton',
3504 'char' : 'openerp.web.form.FieldChar',
3505 'id' : 'openerp.web.form.FieldID',
3506 'email' : 'openerp.web.form.FieldEmail',
3507 'url' : 'openerp.web.form.FieldUrl',
3508 'text' : 'openerp.web.form.FieldText',
3509 'date' : 'openerp.web.form.FieldDate',
3510 'datetime' : 'openerp.web.form.FieldDatetime',
3511 'selection' : 'openerp.web.form.FieldSelection',
3512 'many2one' : 'openerp.web.form.FieldMany2One',
3513 'many2many' : 'openerp.web.form.FieldMany2Many',
3514 'one2many' : 'openerp.web.form.FieldOne2Many',
3515 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3516 'reference' : 'openerp.web.form.FieldReference',
3517 'boolean' : 'openerp.web.form.FieldBoolean',
3518 'float' : 'openerp.web.form.FieldFloat',
3519 'integer': 'openerp.web.form.FieldFloat',
3520 'float_time': 'openerp.web.form.FieldFloat',
3521 'progressbar': 'openerp.web.form.FieldProgressBar',
3522 'image': 'openerp.web.form.FieldBinaryImage',
3523 'binary': 'openerp.web.form.FieldBinaryFile',
3524 'statusbar': 'openerp.web.form.FieldStatus',
3525 'html': 'openerp.web.form.WidgetHtml'
3531 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: