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 && !self.embedded_view) {
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)) {
519 //console.log("FormView(", self, ") : Nothing to save");
520 save_deferral = $.Deferred().resolve({}).promise();
522 //console.log("FormView(", self, ") : About to save", values);
523 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
524 return self.on_saved(r);
527 return save_deferral.then(success);
531 return $.Deferred().reject();
535 on_invalid: function() {
537 _.each(this.fields, function(f) {
539 msg += "<li>" + f.string + "</li>";
543 this.do_warn("The following fields are invalid :", msg);
545 on_saved: function(r, success) {
547 // should not happen in the server, but may happen for internal purpose
548 return $.Deferred().reject();
550 return $.when(this.reload()).pipe(function () {
551 return $.when(r).then(success); }, null);
555 * Updates the form' dataset to contain the new record:
557 * * Adds the newly created record to the current dataset (at the end by
559 * * Selects that record (sets the dataset's index to point to the new
561 * * Updates the pager and sidebar displays
564 * @param {Function} success callback to execute after having updated the dataset
565 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
567 on_created: function(r, success, prepend_on_create) {
569 // should not happen in the server, but may happen for internal purpose
570 return $.Deferred().reject();
572 this.datarecord.id = r.result;
573 if (!prepend_on_create) {
574 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
575 this.dataset.index = this.dataset.ids.length - 1;
577 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
578 this.dataset.index = 0;
580 this.do_update_pager();
582 this.sidebar.attachments.do_update();
584 //openerp.log("The record has been created with id #" + this.datarecord.id);
586 return $.when(_.extend(r, {created: true})).then(success);
589 on_action: function (action) {
590 console.debug('Executing action', action);
594 return this.reload_mutex.exec(function() {
595 if (self.dataset.index == null || self.dataset.index < 0) {
596 return $.when(self.on_button_new());
598 return self.dataset.read_index(_.keys(self.fields_view.fields), {
599 context : { 'bin_size' : true }
600 }).pipe(self.on_record_loaded);
604 get_fields_values: function(blacklist) {
605 blacklist = blacklist || [];
607 var ids = this.get_selected_ids();
608 values["id"] = ids.length > 0 ? ids[0] : false;
609 _.each(this.fields, function(value, key) {
610 if (_.include(blacklist, key))
612 var val = value.get_value();
617 get_selected_ids: function() {
618 var id = this.dataset.ids[this.dataset.index];
619 return id ? [id] : [];
621 recursive_save: function() {
623 return $.when(this.do_save()).pipe(function(res) {
624 if (self.dataset.parent_view)
625 return self.dataset.parent_view.recursive_save();
628 is_dirty: function() {
629 return _.any(this.fields, function (value) {
630 return value.is_dirty();
633 is_interactible_record: function() {
634 var id = this.datarecord.id;
636 if (this.options.not_interactible_on_create)
638 } else if (typeof(id) === "string") {
639 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
644 sidebar_context: function () {
645 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
647 open_defaults_dialog: function () {
649 var fields = _.chain(this.fields)
650 .map(function (field, name) {
651 var value = field.get_value();
652 // ignore fields which are empty, invisible, readonly, o2m
657 || field.field.type === 'one2many'
658 || field.field.type === 'many2many') {
662 switch(field.field.type) {
664 displayed = _(field.values).find(function (option) {
665 return option[0] === value;
669 displayed = field.value[1] || value;
677 string: field.string,
679 displayed: displayed,
680 // convert undefined to false
681 change_default: !!field.field.change_default
685 .sortBy(function (field) { return field.string; })
687 var conditions = _.chain(fields)
688 .filter(function (field) { return field.change_default; })
691 var d = new openerp.web.Dialog(this, {
692 title: _t("Set Default"),
695 conditions: conditions
698 {text: _t("Close"), click: function () { d.close(); }},
699 {text: _t("Save default"), click: function () {
700 var $defaults = d.$element.find('#formview_default_fields');
701 var field_to_set = $defaults.val();
703 $defaults.parent().addClass('invalid');
706 var condition = d.$element.find('#formview_default_conditions').val(),
707 all_users = d.$element.find('#formview_default_all').is(':checked');
708 new openerp.web.DataSet(self, 'ir.values').call(
712 self.fields[field_to_set].get_value(),
716 ]).then(function () { d.close(); });
720 d.template = 'FormView.set_default';
724 openerp.web.FormDialog = openerp.web.Dialog.extend({
725 init: function(parent, options, view_id, dataset) {
726 this._super(parent, options);
727 this.dataset = dataset;
728 this.view_id = view_id;
733 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
737 this.form.appendTo(this.$element);
738 this.form.on_created.add_last(this.on_form_dialog_saved);
739 this.form.on_saved.add_last(this.on_form_dialog_saved);
742 select_id: function(id) {
743 if (this.form.dataset.select_id(id)) {
744 return this.form.do_show();
746 this.do_warn("Could not find id in dataset");
747 return $.Deferred().reject();
750 on_form_dialog_saved: function(r) {
756 openerp.web.form = {};
758 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
759 init: function(parent, form_view) {
760 var $section = parent.add_section(_t('Attachments'), 'attachments');
761 this.$div = $('<div class="oe-sidebar-attachments"></div>');
762 $section.append(this.$div);
764 this._super(parent, $section.attr('id'));
765 this.view = form_view;
767 do_update: function() {
768 if (!this.view.datarecord.id) {
769 this.on_attachments_loaded([]);
771 (new openerp.web.DataSetSearch(
772 this, 'ir.attachment', this.view.dataset.get_context(),
774 ['res_model', '=', this.view.dataset.model],
775 ['res_id', '=', this.view.datarecord.id],
776 ['type', 'in', ['binary', 'url']]
777 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
780 on_attachments_loaded: function(attachments) {
781 this.attachments = attachments;
782 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
783 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
784 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
786 on_attachment_changed: function(e) {
787 window[this.element_id + '_iframe'] = this.do_update;
788 var $e = $(e.target);
789 if ($e.val() != '') {
790 this.$element.find('form.oe-binary-form').submit();
791 $e.parent().find('input[type=file]').prop('disabled', true);
792 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
795 on_attachment_delete: function(e) {
796 var self = this, $e = $(e.currentTarget);
797 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
798 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
799 this.rpc('/web/dataset/unlink', {
800 model: 'ir.attachment',
801 ids: [parseInt($e.attr('data-id'))]
803 $e.parent().remove();
804 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
810 openerp.web.form.compute_domain = function(expr, fields) {
812 for (var i = expr.length - 1; i >= 0; i--) {
814 if (ex.length == 1) {
815 var top = stack.pop();
818 stack.push(stack.pop() || top);
821 stack.push(stack.pop() && top);
827 throw new Error(_.str.sprintf(
828 _t("Unknown operator %s in domain %s"),
829 ex, JSON.stringify(expr)));
833 var field = fields[ex[0]];
835 throw new Error(_.str.sprintf(
836 _t("Unknown field %s in domain %s"),
837 ex[0], JSON.stringify(expr)));
839 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
843 switch (op.toLowerCase()) {
846 stack.push(field_value == val);
850 stack.push(field_value != val);
853 stack.push(field_value < val);
856 stack.push(field_value > val);
859 stack.push(field_value <= val);
862 stack.push(field_value >= val);
865 if (!_.isArray(val)) val = [val];
866 stack.push(_(val).contains(field_value));
869 if (!_.isArray(val)) val = [val];
870 stack.push(!_(val).contains(field_value));
874 _t("Unsupported operator %s in domain %s"),
875 op, JSON.stringify(expr));
878 return _.all(stack, _.identity);
881 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
884 * @constructs openerp.web.form.Widget
885 * @extends openerp.web.OldWidget
890 init: function(view, node) {
893 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
894 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
895 this.type = this.type || node.tag;
896 this.element_name = this.element_name || this.type;
897 this.element_class = [
898 'formview', this.view.view_id, this.element_name,
899 this.view.widgets_counter++].join("_");
903 this.view.widgets[this.element_class] = this;
904 this.children = node.children;
905 this.colspan = parseInt(node.attrs.colspan || 1, 10);
906 this.decrease_max_width = 0;
908 this.string = this.string || node.attrs.string;
909 this.help = this.help || node.attrs.help;
910 this.invisible = this.modifiers['invisible'] === true;
911 this.classname = 'oe_form_' + this.type;
913 this.align = parseFloat(this.node.attrs.align);
914 if (isNaN(this.align) || this.align === 1) {
915 this.align = 'right';
916 } else if (this.align === 0) {
919 this.align = 'center';
923 this.width = this.node.attrs.width;
926 this.$element = this.view.$element.find(
927 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
930 this._super.apply(this, arguments);
933 process_modifiers: function() {
934 var compute_domain = openerp.web.form.compute_domain;
935 for (var a in this.modifiers) {
936 this[a] = compute_domain(this.modifiers[a], this.view.fields);
939 update_dom: function() {
940 this.$element.toggle(!this.invisible);
943 var template = this.template;
944 return QWeb.render(template, { "widget": this });
946 do_attach_tooltip: function(widget, trigger, options) {
947 widget = widget || this;
948 trigger = trigger || this.$element;
954 var template = widget.template + '.tooltip';
955 if (!QWeb.has_template(template)) {
956 template = 'WidgetLabel.tooltip';
958 return QWeb.render(template, {
959 debug: openerp.connection.debug,
962 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
967 trigger.tipsy(options);
969 _build_view_fields_values: function(blacklist) {
970 var a_dataset = this.view.dataset;
971 var fields_values = this.view.get_fields_values(blacklist);
972 var active_id = a_dataset.ids[a_dataset.index];
973 _.extend(fields_values, {
974 active_id: active_id || false,
975 active_ids: active_id ? [active_id] : [],
976 active_model: a_dataset.model,
979 if (a_dataset.parent_view) {
980 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
982 return fields_values;
984 _build_eval_context: function(blacklist) {
985 var a_dataset = this.view.dataset;
986 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
989 * Builds a new context usable for operations related to fields by merging
990 * the fields'context with the action's context.
992 build_context: function(blacklist) {
993 // only use the model's context if there is not context on the node
994 var v_context = this.node.attrs.context;
996 v_context = (this.field || {}).context || {};
999 if (v_context.__ref || true) { //TODO: remove true
1000 var fields_values = this._build_eval_context(blacklist);
1001 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1005 build_domain: function() {
1006 var f_domain = this.field.domain || [];
1007 var n_domain = this.node.attrs.domain || null;
1008 // if there is a domain on the node, overrides the model's domain
1009 var final_domain = n_domain !== null ? n_domain : f_domain;
1010 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1011 var fields_values = this._build_eval_context();
1012 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1014 return final_domain;
1018 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1019 template: 'WidgetFrame',
1020 init: function(view, node) {
1021 this._super(view, node);
1022 this.columns = parseInt(node.attrs.col || 4, 10);
1027 for (var i = 0; i < node.children.length; i++) {
1028 var n = node.children[i];
1029 if (n.tag == "newline") {
1032 this.handle_node(n);
1035 this.set_row_cells_with(this.table[this.table.length - 1]);
1037 add_row: function(){
1038 if (this.table.length) {
1039 this.set_row_cells_with(this.table[this.table.length - 1]);
1042 this.table.push(row);
1047 set_row_cells_with: function(row) {
1050 row_length = row.length;
1051 for (var i = 0; i < row.length; i++) {
1052 if (row[i].always_invisible) {
1055 bypass += row[i].width === undefined ? 0 : 1;
1056 max_width -= row[i].decrease_max_width;
1059 var size_unit = Math.round(max_width / (this.columns - bypass)),
1061 for (var i = 0; i < row.length; i++) {
1063 if (w.always_invisible) {
1066 colspan_sum += w.colspan;
1067 if (w.width === undefined) {
1068 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1070 w.width = width + '%';
1074 handle_node: function(node) {
1076 if (node.tag == 'field') {
1077 type = this.view.fields_view.fields[node.attrs.name] || {};
1078 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1079 // This way we can retain backward compatibility between addons and old clients
1080 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1081 node.attrs.nolabel = '1';
1084 var widget = new (this.view.registry.get_any(
1085 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1086 if (node.tag == 'field') {
1087 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1088 this.view.default_focus_field = widget;
1090 if (node.attrs.nolabel != '1') {
1091 var label = new (this.view.registry.get_object('label')) (this.view, node);
1092 label["for"] = widget;
1093 this.add_widget(label, widget.colspan + 1);
1096 this.add_widget(widget);
1098 add_widget: function(widget, colspan) {
1099 var current_row = this.table[this.table.length - 1];
1100 if (!widget.always_invisible) {
1101 colspan = colspan || widget.colspan;
1102 if (current_row.length && (this.x + colspan) > this.columns) {
1103 current_row = this.add_row();
1105 this.x += widget.colspan;
1107 current_row.push(widget);
1112 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1113 template: 'WidgetGroup'
1116 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1117 template: 'WidgetNotebook',
1118 init: function(view, node) {
1119 this._super(view, node);
1121 for (var i = 0; i < node.children.length; i++) {
1122 var n = node.children[i];
1123 if (n.tag == "page") {
1124 var page = new (this.view.registry.get_object('notebookpage'))(
1125 this.view, n, this, this.pages.length);
1126 this.pages.push(page);
1132 this._super.apply(this, arguments);
1133 this.$element.find('> ul > li').each(function (index, tab_li) {
1134 var page = self.pages[index],
1135 id = _.uniqueId(self.element_name + '-');
1136 page.element_id = id;
1137 $(tab_li).find('a').attr('href', '#' + id);
1139 this.$element.find('> div').each(function (index, page) {
1140 page.id = self.pages[index].element_id;
1142 this.$element.tabs();
1143 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1144 if (openerp.connection.debug) {
1145 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1150 do_select_first_visible_tab: function() {
1151 for (var i = 0; i < this.pages.length; i++) {
1152 var page = this.pages[i];
1153 if (page.invisible === false) {
1154 this.$element.tabs('select', page.index);
1161 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1162 template: 'WidgetNotebookPage',
1163 init: function(view, node, notebook, index) {
1164 this.notebook = notebook;
1166 this.element_name = 'page_' + index;
1167 this._super(view, node);
1170 this._super.apply(this, arguments);
1171 this.$element_tab = this.notebook.$element.find(
1172 '> ul > li:eq(' + this.index + ')');
1174 update_dom: function() {
1175 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1176 this.notebook.do_select_first_visible_tab();
1178 this.$element_tab.toggle(!this.invisible);
1179 this.$element.toggle(!this.invisible);
1183 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1184 template: 'WidgetSeparator',
1185 init: function(view, node) {
1186 this._super(view, node);
1187 this.orientation = node.attrs.orientation || 'horizontal';
1188 if (this.orientation === 'vertical') {
1191 this.classname += '_' + this.orientation;
1195 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1196 template: 'WidgetButton',
1197 init: function(view, node) {
1198 this._super(view, node);
1199 this.force_disabled = false;
1201 // We don't have button key bindings in the webclient
1202 this.string = this.string.replace(/_/g, '');
1204 if (node.attrs.default_focus == '1') {
1205 // TODO fme: provide enter key binding to widgets
1206 this.view.default_focus_button = this;
1210 this._super.apply(this, arguments);
1211 this.$element.find("button").click(this.on_click);
1212 if (this.help || openerp.connection.debug) {
1213 this.do_attach_tooltip();
1216 on_click: function() {
1218 this.force_disabled = true;
1219 this.check_disable();
1220 this.execute_action().always(function() {
1221 self.force_disabled = false;
1222 self.check_disable();
1225 execute_action: function() {
1227 var exec_action = function() {
1228 if (self.node.attrs.confirm) {
1229 var def = $.Deferred();
1230 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1231 title: _t('Confirm'),
1234 {text: _t("Cancel"), click: function() {
1236 $(this).dialog("close");
1239 {text: _t("Ok"), click: function() {
1240 self.on_confirmed().then(function() {
1243 $(this).dialog("close");
1248 return def.promise();
1250 return self.on_confirmed();
1253 if (!this.node.attrs.special) {
1254 return this.view.recursive_save().pipe(exec_action);
1256 return exec_action();
1259 on_confirmed: function() {
1262 var context = this.node.attrs.context;
1263 if (context && context.__ref) {
1264 context = new openerp.web.CompoundContext(context);
1265 context.set_eval_context(this._build_eval_context());
1268 return this.view.do_execute_action(
1269 _.extend({}, this.node.attrs, {context: context}),
1270 this.view.dataset, this.view.datarecord.id, function () {
1274 update_dom: function() {
1275 this._super.apply(this, arguments);
1276 this.check_disable();
1278 check_disable: function() {
1279 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1280 this.$element.find('button').prop('disabled', disabled);
1281 this.$element.find("button").css('color', disabled ? 'grey' : '');
1285 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1286 template: 'WidgetLabel',
1287 init: function(view, node) {
1288 this.element_name = 'label_' + node.attrs.name;
1290 this._super(view, node);
1292 if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1293 this.string = this.node.children[0];
1294 this.align = 'left';
1297 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1298 this.template = "WidgetParagraph";
1299 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1300 // Widgets default to right-aligned, but paragraph defaults to
1302 if (isNaN(parseFloat(this.node.attrs.align))) {
1303 this.align = 'left';
1306 this.multilines = this.string && _.str.lines(this.string).length > 1;
1310 this.decrease_max_width = 1;
1314 render: function () {
1315 if (this['for'] && this.type !== 'label') {
1316 return QWeb.render(this.template, {widget: this['for']});
1318 // Actual label widgets should not have a false and have type label
1319 return QWeb.render(this.template, {widget: this});
1324 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1325 this.do_attach_tooltip(self['for']);
1327 this.$element.find("label").dblclick(function() {
1328 var widget = self['for'] || self;
1329 openerp.log(widget.element_class , widget);
1335 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1337 * @constructs openerp.web.form.Field
1338 * @extends openerp.web.form.Widget
1343 init: function(view, node) {
1344 this.name = node.attrs.name;
1345 this.value = undefined;
1346 view.fields[this.name] = this;
1347 view.fields_order.push(this.name);
1348 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1349 this.element_name = "field_" + this.name + "_" + this.type;
1351 this._super(view, node);
1353 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1356 this.field = view.fields_view.fields[node.attrs.name] || {};
1357 this.string = node.attrs.string || this.field.string;
1358 this.help = node.attrs.help || this.field.help;
1359 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1360 this.readonly = this.modifiers['readonly'] === true;
1361 this.required = this.modifiers['required'] === true;
1362 this.invalid = this.dirty = false;
1364 this.classname = 'oe_form_field_' + this.type;
1367 this._super.apply(this, arguments);
1368 if (this.field.translate) {
1369 this.view.translatable_fields.push(this);
1370 this.$element.addClass('oe_form_field_translatable');
1371 this.$element.find('.oe_field_translate').click(this.on_translate);
1373 if (this.nolabel && openerp.connection.debug) {
1374 this.do_attach_tooltip(this, this.$element);
1377 set_value: function(value) {
1379 this.invalid = false;
1381 this.on_value_changed();
1383 set_value_from_ui: function() {
1384 this.on_value_changed();
1386 on_value_changed: function() {
1388 on_translate: function() {
1389 this.view.open_translate_dialog(this);
1391 get_value: function() {
1394 is_valid: function() {
1395 return !this.invalid;
1397 is_dirty: function() {
1398 return this.dirty && !this.readonly;
1400 get_on_change_value: function() {
1401 return this.get_value();
1403 update_dom: function(show_invalid) {
1404 this._super.apply(this, arguments);
1405 if (this.field.translate) {
1406 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1408 if (!this.disable_utility_classes) {
1409 this.$element.toggleClass('disabled', this.readonly);
1410 this.$element.toggleClass('required', this.required);
1412 this.$element.toggleClass('invalid', !this.is_valid());
1416 on_ui_change: function() {
1419 if (this.is_valid()) {
1420 this.set_value_from_ui();
1421 this.view.do_onchange(this);
1422 this.view.on_form_changed(true);
1423 this.view.do_notify_change();
1425 this.update_dom(true);
1428 validate: function() {
1429 this.invalid = false;
1431 focus: function($element) {
1433 setTimeout(function() {
1441 get_definition_options: function() {
1442 if (!this.definition_options) {
1443 var str = this.node.attrs.options || '{}';
1444 this.definition_options = JSON.parse(str);
1446 return this.definition_options;
1450 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1451 template: 'FieldChar',
1452 init: function (view, node) {
1453 this._super(view, node);
1454 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1457 this._super.apply(this, arguments);
1458 this.$element.find('input').change(this.on_ui_change);
1460 set_value: function(value) {
1461 this._super.apply(this, arguments);
1462 var show_value = openerp.web.format_value(value, this, '');
1463 this.$element.find('input').val(show_value);
1466 update_dom: function() {
1467 this._super.apply(this, arguments);
1468 this.$element.find('input').prop('readonly', this.readonly);
1470 set_value_from_ui: function() {
1471 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1474 validate: function() {
1475 this.invalid = false;
1477 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1478 this.invalid = this.required && value === '';
1480 this.invalid = true;
1483 focus: function($element) {
1484 this._super($element || this.$element.find('input:first'));
1488 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1489 update_dom: function() {
1490 this._super.apply(this, arguments);
1491 this.$element.find('input').prop('readonly', true);
1495 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1496 template: 'FieldEmail',
1498 this._super.apply(this, arguments);
1499 this.$element.find('button').click(this.on_button_clicked);
1501 on_button_clicked: function() {
1502 if (!this.value || !this.is_valid()) {
1503 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1505 location.href = 'mailto:' + this.value;
1510 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1511 template: 'FieldUrl',
1513 this._super.apply(this, arguments);
1514 this.$element.find('button').click(this.on_button_clicked);
1516 on_button_clicked: function() {
1518 this.do_warn("Resource error", "This resource is empty");
1520 window.open(this.value);
1525 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1526 init: function (view, node) {
1527 this._super(view, node);
1528 if (node.attrs.digits) {
1529 this.parse_digits(node.attrs.digits);
1531 this.digits = view.fields_view.fields[node.attrs.name].digits;
1534 parse_digits: function (digits_attr) {
1535 // could use a Python parser instead.
1536 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1537 return [parseInt(match[1], 10), parseInt(match[2], 10)];
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 values = values.slice(0, self.limit);
2061 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2062 dataset.name_search(search_val, self.build_domain(), 'ilike'
2063 , false, function(data) {
2064 self._change_int_value(null);
2065 self._search_create_popup("search", data);
2070 var raw_result = _(data.result).map(function(x) {return x[1];});
2071 if (search_val.length > 0 &&
2072 !_.include(raw_result, search_val) &&
2073 (!self.value || search_val !== self.value[1])) {
2074 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2075 $('<span />').text(search_val).html()), action: function() {
2076 self._quick_create(search_val);
2080 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2081 self._change_int_value(null);
2082 self._search_create_popup("form", undefined, {"default_name": search_val});
2087 this.abort_last = dataset.abort_last;
2089 _quick_create: function(name) {
2091 var slow_create = function () {
2092 self._change_int_value(null);
2093 self._search_create_popup("form", undefined, {"default_name": name});
2095 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2096 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2097 dataset.name_create(name, function(data) {
2098 self._change_int_ext_value(data);
2099 }).fail(function(error, event) {
2100 event.preventDefault();
2106 // all search/create popup handling
2107 _search_create_popup: function(view, ids, context) {
2109 var pop = new openerp.web.form.SelectCreatePopup(this);
2111 self.field.relation,
2113 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2114 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2116 disable_multiple_selection: true
2118 self.build_domain(),
2119 new openerp.web.CompoundContext(self.build_context(), context || {})
2121 pop.on_select_elements.add(function(element_ids) {
2122 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2123 dataset.name_get([element_ids[0]], function(data) {
2124 self._change_int_ext_value(data[0]);
2128 _change_int_ext_value: function(value) {
2129 this._change_int_value(value);
2130 this.$input.val(this.value ? this.value[1] : "");
2132 _change_int_value: function(value) {
2134 var back_orig_value = this.original_value;
2135 if (this.value === null || this.value) {
2136 this.original_value = this.value;
2138 if (back_orig_value === undefined) { // first use after a set_value()
2141 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2142 !== (this.value ? this.value[0] : null))) {
2143 this.on_ui_change();
2146 set_value: function(value) {
2147 value = value || null;
2148 this.invalid = false;
2150 this.tmp_value = value;
2152 self.on_value_changed();
2153 var real_set_value = function(rval) {
2154 self.tmp_value = undefined;
2156 self.original_value = undefined;
2157 self._change_int_ext_value(rval);
2159 if (value && !(value instanceof Array)) {
2160 // name_get in a m2o does not use the context of the field
2161 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2162 dataset.name_get([value], function(data) {
2163 real_set_value(data[0]);
2164 }).fail(function() {self.tmp_value = undefined;});
2166 $.async_when().then(function() {real_set_value(value);});
2169 get_value: function() {
2170 if (this.tmp_value !== undefined) {
2171 if (this.tmp_value instanceof Array) {
2172 return this.tmp_value[0];
2174 return this.tmp_value ? this.tmp_value : false;
2176 if (this.value === undefined)
2177 return this.original_value ? this.original_value[0] : false;
2178 return this.value ? this.value[0] : false;
2180 validate: function() {
2181 this.invalid = false;
2182 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2184 this.invalid = this.required;
2187 open_related: function(related) {
2191 var additional_context = {
2192 active_id: self.value[0],
2193 active_ids: [self.value[0]],
2194 active_model: self.field.relation
2196 self.rpc("/web/action/load", {
2197 action_id: related[2].id,
2198 context: additional_context
2199 }, function(result) {
2200 result.result.context = _.extend(result.result.context || {}, additional_context);
2201 self.do_action(result.result);
2204 focus: function ($element) {
2205 this._super($element || this.$input);
2207 update_dom: function() {
2208 this._super.apply(this, arguments);
2209 this.$input.prop('readonly', this.readonly);
2214 # Values: (0, 0, { fields }) create
2215 # (1, ID, { fields }) update
2216 # (2, ID) remove (delete)
2217 # (3, ID) unlink one (target id or target of relation)
2219 # (5) unlink all (only valid for one2many)
2224 'create': function (values) {
2225 return [commands.CREATE, false, values];
2227 // (1, id, {values})
2229 'update': function (id, values) {
2230 return [commands.UPDATE, id, values];
2234 'delete': function (id) {
2235 return [commands.DELETE, id, false];
2237 // (3, id[, _]) removes relation, but not linked record itself
2239 'forget': function (id) {
2240 return [commands.FORGET, id, false];
2244 'link_to': function (id) {
2245 return [commands.LINK_TO, id, false];
2249 'delete_all': function () {
2250 return [5, false, false];
2252 // (6, _, ids) replaces all linked records with provided ids
2254 'replace_with': function (ids) {
2255 return [6, false, ids];
2258 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2259 template: 'FieldOne2Many',
2260 multi_selection: false,
2261 init: function(view, node) {
2262 this._super(view, node);
2263 this.is_loaded = $.Deferred();
2264 this.initial_is_loaded = this.is_loaded;
2265 this.is_setted = $.Deferred();
2266 this.form_last_update = $.Deferred();
2267 this.init_form_last_update = this.form_last_update;
2268 this.disable_utility_classes = true;
2271 this._super.apply(this, arguments);
2275 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2276 this.dataset.o2m = this;
2277 this.dataset.parent_view = this.view;
2278 this.dataset.child_name = this.name;
2279 //this.dataset.child_name =
2280 this.dataset.on_change.add_last(function() {
2281 self.trigger_on_change();
2284 this.is_setted.then(function() {
2288 trigger_on_change: function() {
2289 var tmp = this.doing_on_change;
2290 this.doing_on_change = true;
2291 this.on_ui_change();
2292 this.doing_on_change = tmp;
2294 is_readonly: function() {
2295 return this.readonly || this.force_readonly;
2297 load_views: function() {
2300 var modes = this.node.attrs.mode;
2301 modes = !!modes ? modes.split(",") : ["tree"];
2303 _.each(modes, function(mode) {
2306 view_type: mode == "tree" ? "list" : mode,
2307 options: { sidebar : false }
2309 if (self.field.views && self.field.views[mode]) {
2310 view.embedded_view = self.field.views[mode];
2312 if(view.view_type === "list") {
2313 view.options.selectable = self.multi_selection;
2314 if (self.is_readonly()) {
2315 view.options.addable = null;
2316 view.options.deletable = null;
2317 view.options.isClarkGable = false;
2319 } else if (view.view_type === "form") {
2320 if (self.is_readonly()) {
2321 view.view_type = 'page';
2323 view.options.not_interactible_on_create = true;
2329 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2330 this.viewmanager.template = 'One2Many.viewmanager';
2331 this.viewmanager.registry = openerp.web.views.extend({
2332 list: 'openerp.web.form.One2ManyListView',
2333 form: 'openerp.web.form.One2ManyFormView',
2334 page: 'openerp.web.PageView'
2336 var once = $.Deferred().then(function() {
2337 self.init_form_last_update.resolve();
2339 var def = $.Deferred().then(function() {
2340 self.initial_is_loaded.resolve();
2342 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2343 if (view_type == "list") {
2344 controller.o2m = self;
2345 if (self.is_readonly())
2346 controller.set_editable(false);
2347 } else if (view_type == "form" || view_type == 'page') {
2348 if (view_type == 'page' || self.is_readonly()) {
2349 $(".oe_form_buttons", controller.$element).children().remove();
2351 controller.on_record_loaded.add_last(function() {
2354 controller.on_pager_action.add_first(function() {
2355 self.save_any_view();
2357 } else if (view_type == "graph") {
2358 self.reload_current_view()
2362 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2363 $.when(self.save_any_view()).then(function() {
2364 if(n_mode === "list")
2365 $.async_when().then(function() {self.reload_current_view();});
2368 this.is_setted.then(function() {
2369 $.async_when().then(function () {
2370 self.viewmanager.appendTo(self.$element);
2375 reload_current_view: function() {
2377 return self.is_loaded = self.is_loaded.pipe(function() {
2378 var active_view = self.viewmanager.active_view;
2379 var view = self.viewmanager.views[active_view].controller;
2380 if(active_view === "list") {
2381 return view.reload_content();
2382 } else if (active_view === "form" || active_view === 'page') {
2383 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2384 self.dataset.index = 0;
2386 var act = function() {
2387 return view.do_show();
2389 self.form_last_update = self.form_last_update.pipe(act, act);
2390 return self.form_last_update;
2391 } else if (active_view === "graph") {
2392 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2396 set_value: function(value) {
2397 value = value || [];
2399 this.dataset.reset_ids([]);
2400 if(value.length >= 1 && value[0] instanceof Array) {
2402 _.each(value, function(command) {
2403 var obj = {values: command[2]};
2404 switch (command[0]) {
2405 case commands.CREATE:
2406 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2408 self.dataset.to_create.push(obj);
2409 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2412 case commands.UPDATE:
2413 obj['id'] = command[1];
2414 self.dataset.to_write.push(obj);
2415 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2418 case commands.DELETE:
2419 self.dataset.to_delete.push({id: command[1]});
2421 case commands.LINK_TO:
2422 ids.push(command[1]);
2424 case commands.DELETE_ALL:
2425 self.dataset.delete_all = true;
2430 this.dataset.set_ids(ids);
2431 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2433 this.dataset.delete_all = true;
2434 _.each(value, function(command) {
2435 var obj = {values: command};
2436 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2438 self.dataset.to_create.push(obj);
2439 self.dataset.cache.push(_.clone(obj));
2443 this.dataset.set_ids(ids);
2446 this.dataset.reset_ids(value);
2448 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2449 this.dataset.index = 0;
2451 self.is_setted.resolve();
2452 return self.reload_current_view();
2454 get_value: function() {
2458 this.save_any_view();
2459 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2460 val = val.concat(_.map(this.dataset.ids, function(id) {
2461 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2463 return commands.create(alter_order.values);
2465 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2467 return commands.update(alter_order.id, alter_order.values);
2469 return commands.link_to(id);
2471 return val.concat(_.map(
2472 this.dataset.to_delete, function(x) {
2473 return commands['delete'](x.id);}));
2475 save_any_view: function() {
2476 if (this.doing_on_change)
2478 return this.session.synchronized_mode(_.bind(function() {
2479 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2480 this.viewmanager.views[this.viewmanager.active_view] &&
2481 this.viewmanager.views[this.viewmanager.active_view].controller) {
2482 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2483 if (this.viewmanager.active_view === "form") {
2484 if (!view.is_initialized.isResolved()) {
2487 var res = $.when(view.do_save());
2488 if (!res.isResolved() && !res.isRejected()) {
2489 console.warn("Asynchronous get_value() is not supported in form view.");
2492 } else if (this.viewmanager.active_view === "list") {
2493 var res = $.when(view.ensure_saved());
2494 if (!res.isResolved() && !res.isRejected()) {
2495 console.warn("Asynchronous get_value() is not supported in list view.");
2503 is_valid: function() {
2505 return this._super();
2507 validate: function() {
2508 this.invalid = false;
2509 if (!this.viewmanager.views[this.viewmanager.active_view])
2511 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2512 if (this.viewmanager.active_view === "form") {
2513 for (var f in view.fields) {
2515 if (!f.is_valid()) {
2516 this.invalid = true;
2522 is_dirty: function() {
2523 this.save_any_view();
2524 return this._super();
2526 update_dom: function() {
2527 this._super.apply(this, arguments);
2529 if (this.previous_readonly !== this.readonly) {
2530 this.previous_readonly = this.readonly;
2531 if (this.viewmanager) {
2532 this.is_loaded = this.is_loaded.pipe(function() {
2533 self.viewmanager.stop();
2534 return $.when(self.load_views()).then(function() {
2535 self.reload_current_view();
2543 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2544 get_context: function() {
2545 this.context = this.o2m.build_context([this.o2m.name]);
2546 return this.context;
2550 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2551 _template: 'One2Many.listview',
2552 do_add_record: function () {
2553 if (this.options.editable) {
2554 this._super.apply(this, arguments);
2557 var pop = new openerp.web.form.SelectCreatePopup(this);
2558 pop.on_default_get.add(self.dataset.on_default_get);
2560 self.o2m.field.relation,
2562 title: _t("Create: ") + self.name,
2563 initial_view: "form",
2564 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2565 create_function: function(data, callback, error_callback) {
2566 return self.o2m.dataset.create(data).then(function(r) {
2567 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2568 self.o2m.dataset.on_change();
2569 }).then(callback, error_callback);
2571 read_function: function() {
2572 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2574 parent_view: self.o2m.view,
2575 child_name: self.o2m.name,
2576 form_view_options: {'not_interactible_on_create':true}
2578 self.o2m.build_domain(),
2579 self.o2m.build_context()
2581 pop.on_select_elements.add_last(function() {
2582 self.o2m.reload_current_view();
2586 do_activate_record: function(index, id) {
2588 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2589 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2590 title: _t("Open: ") + self.name,
2592 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2593 parent_view: self.o2m.view,
2594 child_name: self.o2m.name,
2595 read_function: function() {
2596 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2598 form_view_options: {'not_interactible_on_create':true},
2599 readonly: self.o2m.is_readonly()
2601 pop.on_write.add(function(id, data) {
2602 self.o2m.dataset.write(id, data, {}, function(r) {
2603 self.o2m.reload_current_view();
2607 do_button_action: function (name, id, callback) {
2609 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2610 return this._super(name, id, _.bind(def.resolve, def));
2614 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2615 form_template: 'One2Many.formview',
2616 on_loaded: function(data) {
2619 this.$form_header.find('button.oe_form_button_create').click(function() {
2620 self.do_save().then(self.on_button_new);
2623 do_notify_change: function() {
2624 if (this.dataset.parent_view) {
2625 this.dataset.parent_view.do_notify_change();
2627 this._super.apply(this, arguments);
2632 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2633 template: 'FieldMany2Many',
2634 multi_selection: false,
2635 init: function(view, node) {
2636 this._super(view, node);
2637 this.list_id = _.uniqueId("many2many");
2638 this.is_loaded = $.Deferred();
2639 this.initial_is_loaded = this.is_loaded;
2640 this.is_setted = $.Deferred();
2643 this._super.apply(this, arguments);
2647 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2648 this.dataset.m2m = this;
2649 this.dataset.on_unlink.add_last(function(ids) {
2650 self.on_ui_change();
2653 this.is_setted.then(function() {
2657 set_value: function(value) {
2658 value = value || [];
2659 if (value.length >= 1 && value[0] instanceof Array) {
2660 value = value[0][2];
2663 this.dataset.set_ids(value);
2665 self.reload_content();
2666 this.is_setted.resolve();
2668 get_value: function() {
2669 return [commands.replace_with(this.dataset.ids)];
2671 validate: function() {
2672 this.invalid = false;
2674 is_readonly: function() {
2675 return this.readonly || this.force_readonly;
2677 load_view: function() {
2679 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2680 'addable': self.is_readonly() ? null : _t("Add"),
2681 'deletable': self.is_readonly() ? false : true,
2682 'selectable': self.multi_selection,
2683 'isClarkGable': self.is_readonly() ? false : true
2685 var embedded = (this.field.views || {}).tree;
2687 this.list_view.set_embedded_view(embedded);
2689 this.list_view.m2m_field = this;
2690 var loaded = $.Deferred();
2691 this.list_view.on_loaded.add_last(function() {
2692 self.initial_is_loaded.resolve();
2695 $.async_when().then(function () {
2696 self.list_view.appendTo($("#" + self.list_id));
2700 reload_content: function() {
2702 this.is_loaded = this.is_loaded.pipe(function() {
2703 return self.list_view.reload_content();
2706 update_dom: function() {
2707 this._super.apply(this, arguments);
2709 if (this.previous_readonly !== this.readonly) {
2710 this.previous_readonly = this.readonly;
2711 if (this.list_view) {
2712 this.is_loaded = this.is_loaded.pipe(function() {
2713 self.list_view.stop();
2714 return $.when(self.load_view()).then(function() {
2715 self.reload_content();
2723 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2724 get_context: function() {
2725 this.context = this.m2m.build_context();
2726 return this.context;
2732 * @extends openerp.web.ListView
2734 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2735 do_add_record: function () {
2736 var pop = new openerp.web.form.SelectCreatePopup(this);
2740 title: _t("Add: ") + this.name
2742 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2743 this.m2m_field.build_context()
2746 pop.on_select_elements.add(function(element_ids) {
2747 _.each(element_ids, function(element_id) {
2748 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2749 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2750 self.m2m_field.on_ui_change();
2751 self.reload_content();
2756 do_activate_record: function(index, id) {
2758 var pop = new openerp.web.form.FormOpenPopup(this);
2759 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2760 title: _t("Open: ") + this.name,
2761 readonly: this.widget_parent.is_readonly()
2763 pop.on_write_completed.add_last(function() {
2764 self.reload_content();
2771 * @extends openerp.web.OldWidget
2773 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2774 template: "SelectCreatePopup",
2778 * - initial_view: form or search (default search)
2779 * - disable_multiple_selection
2780 * - alternative_form_view
2781 * - create_function (defaults to a naive saving behavior)
2784 * - form_view_options
2785 * - list_view_options
2788 select_element: function(model, options, domain, context) {
2791 this.domain = domain || [];
2792 this.context = context || {};
2793 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2794 return self.create_row.apply(self, arguments);
2795 }, read_function: null});
2796 this.initial_ids = this.options.initial_ids;
2797 this.created_elements = [];
2798 this.render_element();
2799 openerp.web.form.dialog(this.$element, {
2803 title: options.title || ""
2810 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2812 this.dataset.create_function = function() {
2813 return self.options.create_function.apply(null, arguments).then(function(r) {
2814 self.created_elements.push(r.result);
2817 this.dataset.write_function = function() {
2818 return self.write_row.apply(self, arguments);
2820 this.dataset.read_function = this.options.read_function;
2821 this.dataset.parent_view = this.options.parent_view;
2822 this.dataset.child_name = this.options.child_name;
2823 this.dataset.on_default_get.add(this.on_default_get);
2824 if (this.options.initial_view == "search") {
2825 self.rpc('/web/session/eval_domain_and_context', {
2827 contexts: [this.context]
2828 }, function (results) {
2829 var search_defaults = {};
2830 _.each(results.context, function (value, key) {
2831 var match = /^search_default_(.*)$/.exec(key);
2833 search_defaults[match[1]] = value;
2836 self.setup_search_view(search_defaults);
2843 this.$element.dialog('close');
2846 setup_search_view: function(search_defaults) {
2848 if (this.searchview) {
2849 this.searchview.stop();
2851 this.searchview = new openerp.web.SearchView(this,
2852 this.dataset, false, search_defaults);
2853 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2854 if (self.initial_ids) {
2855 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2856 contexts, groupbys);
2857 self.initial_ids = undefined;
2859 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2862 this.searchview.on_loaded.add_last(function () {
2863 self.view_list = new openerp.web.form.SelectCreateListView(self,
2864 self.dataset, false,
2865 _.extend({'deletable': false,
2866 'selectable': !self.options.disable_multiple_selection
2867 }, self.options.list_view_options || {}));
2868 self.view_list.popup = self;
2869 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2870 self.view_list.do_show();
2871 }).pipe(function() {
2872 self.searchview.do_search();
2874 self.view_list.on_loaded.add_last(function() {
2875 var $buttons = self.view_list.$element.find(".oe-actions");
2876 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2877 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2878 $cbutton.click(function() {
2881 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2882 if(self.options.disable_multiple_selection) {
2885 $sbutton.click(function() {
2886 self.on_select_elements(self.selected_ids);
2891 this.searchview.appendTo($("#" + this.element_id + "_search"));
2893 do_search: function(domains, contexts, groupbys) {
2895 this.rpc('/web/session/eval_domain_and_context', {
2896 domains: domains || [],
2897 contexts: contexts || [],
2898 group_by_seq: groupbys || []
2899 }, function (results) {
2900 self.view_list.do_search(results.domain, results.context, results.group_by);
2903 create_row: function() {
2905 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2906 wdataset.parent_view = this.options.parent_view;
2907 wdataset.child_name = this.options.child_name;
2908 return wdataset.create.apply(wdataset, arguments);
2910 write_row: function() {
2912 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2913 wdataset.parent_view = this.options.parent_view;
2914 wdataset.child_name = this.options.child_name;
2915 return wdataset.write.apply(wdataset, arguments);
2917 on_select_elements: function(element_ids) {
2919 on_click_element: function(ids) {
2920 this.selected_ids = ids || [];
2921 if(this.selected_ids.length > 0) {
2922 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2924 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2927 new_object: function() {
2929 if (this.searchview) {
2930 this.searchview.hide();
2932 if (this.view_list) {
2933 this.view_list.$element.hide();
2935 this.dataset.index = null;
2936 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2937 if (this.options.alternative_form_view) {
2938 this.view_form.set_embedded_view(this.options.alternative_form_view);
2940 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2941 this.view_form.on_loaded.add_last(function() {
2942 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2943 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2944 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2945 $nbutton.click(function() {
2946 $.when(self.view_form.do_save()).then(function() {
2947 self.view_form.reload_mutex.exec(function() {
2948 self.view_form.on_button_new();
2952 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2953 $nbutton.click(function() {
2954 $.when(self.view_form.do_save()).then(function() {
2955 self.view_form.reload_mutex.exec(function() {
2960 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2961 $cbutton.click(function() {
2965 this.view_form.do_show();
2967 check_exit: function() {
2968 if (this.created_elements.length > 0) {
2969 this.on_select_elements(this.created_elements);
2973 on_default_get: function(res) {}
2976 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2977 do_add_record: function () {
2978 this.popup.new_object();
2980 select_record: function(index) {
2981 this.popup.on_select_elements([this.dataset.ids[index]]);
2984 do_select: function(ids, records) {
2985 this._super(ids, records);
2986 this.popup.on_click_element(ids);
2992 * @extends openerp.web.OldWidget
2994 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2995 template: "FormOpenPopup",
2998 * - alternative_form_view
2999 * - auto_write (default true)
3003 * - form_view_options
3006 show_element: function(model, row_id, context, options) {
3008 this.row_id = row_id;
3009 this.context = context || {};
3010 this.options = _.defaults(options || {}, {"auto_write": true});
3011 this.render_element();
3012 this.$element.dialog({
3013 title: options.title || '',
3022 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3023 this.dataset.fop = this;
3024 this.dataset.ids = [this.row_id];
3025 this.dataset.index = 0;
3026 this.dataset.parent_view = this.options.parent_view;
3027 this.dataset.child_name = this.options.child_name;
3028 this.setup_form_view();
3030 on_write: function(id, data) {
3031 if (!this.options.auto_write)
3034 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3035 wdataset.parent_view = this.options.parent_view;
3036 wdataset.child_name = this.options.child_name;
3037 wdataset.write(id, data, {}, function(r) {
3038 self.on_write_completed();
3041 on_write_completed: function() {},
3042 setup_form_view: function() {
3044 var FormClass = this.options.readonly
3045 ? openerp.web.views.get_object('page')
3046 : openerp.web.views.get_object('form');
3047 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3048 if (this.options.alternative_form_view) {
3049 this.view_form.set_embedded_view(this.options.alternative_form_view);
3051 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3052 this.view_form.on_loaded.add_last(function() {
3053 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3054 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3055 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3056 $nbutton.click(function() {
3057 self.view_form.do_save().then(function() {
3061 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3062 $cbutton.click(function() {
3065 if (self.options.readonly) {
3067 $cbutton.text(_t("Close"));
3069 self.view_form.do_show();
3071 this.dataset.on_write.add(this.on_write);
3075 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3076 read_ids: function() {
3077 if (this.fop.options.read_function) {
3078 return this.fop.options.read_function.apply(null, arguments);
3080 return this._super.apply(this, arguments);
3085 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3086 template: 'FieldReference',
3087 init: function(view, node) {
3088 this._super(view, node);
3089 this.fields_view = {
3092 selection: view.fields_view.fields[this.name].selection
3099 this.get_fields_values = view.get_fields_values;
3100 this.get_selected_ids = view.get_selected_ids;
3101 this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3102 this.dataset = this.view.dataset;
3103 this.widgets_counter = 0;
3104 this.view_id = 'reference_' + _.uniqueId();
3107 this.fields_order = [];
3108 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3112 this.reference_ready = true;
3113 this.selection.on_value_changed.add_last(this.on_selection_changed);
3114 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3118 this.m2o.on_ui_change.add_last(this.on_ui_change);
3120 on_nop: function() {
3122 on_selection_changed: function() {
3123 if (this.reference_ready) {
3124 var sel = this.selection.get_value();
3125 this.m2o.field.relation = sel;
3126 this.m2o.set_value(null);
3127 this.m2o.$element.toggle(sel !== false);
3132 this.selection.start();
3135 is_valid: function() {
3136 return this.required === false || typeof(this.get_value()) === 'string';
3138 is_dirty: function() {
3139 return this.selection.is_dirty() || this.m2o.is_dirty();
3141 set_value: function(value) {
3143 this.reference_ready = false;
3144 var vals = [], sel_val, m2o_val;
3145 if (typeof(value) === 'string') {
3146 vals = value.split(',');
3148 sel_val = vals[0] || false;
3149 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3150 this.selection.set_value(sel_val);
3151 this.m2o.field.relation = sel_val;
3152 this.m2o.set_value(m2o_val);
3153 this.m2o.$element.toggle(sel_val !== false);
3154 this.reference_ready = true;
3156 get_value: function() {
3157 var model = this.selection.get_value(),
3158 id = this.m2o.get_value();
3159 if (typeof(model) === 'string' && typeof(id) === 'number') {
3160 return model + ',' + id;
3167 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3168 init: function(view, node) {
3169 this._super(view, node);
3170 this.iframe = this.element_id + '_iframe';
3171 this.binary_value = false;
3174 this._super.apply(this, arguments);
3175 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3176 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3177 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3179 human_filesize : function(size) {
3180 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3182 while (size >= 1024) {
3186 return size.toFixed(2) + ' ' + units[i];
3188 on_file_change: function(e) {
3189 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3190 // http://www.html5rocks.com/tutorials/file/dndfiles/
3191 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3192 window[this.iframe] = this.on_file_uploaded;
3193 if ($(e.target).val() != '') {
3194 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3195 this.$element.find('form.oe-binary-form').submit();
3196 this.$element.find('.oe-binary-progress').show();
3197 this.$element.find('.oe-binary').hide();
3200 on_file_uploaded: function(size, name, content_type, file_base64) {
3201 delete(window[this.iframe]);
3202 if (size === false) {
3203 this.do_warn("File Upload", "There was a problem while uploading your file");
3204 // TODO: use openerp web crashmanager
3205 console.warn("Error while uploading file : ", name);
3207 this.on_file_uploaded_and_valid.apply(this, arguments);
3208 this.on_ui_change();
3210 this.$element.find('.oe-binary-progress').hide();
3211 this.$element.find('.oe-binary').show();
3213 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3215 on_save_as: function() {
3217 this.session.get_file({
3218 url: '/web/binary/saveas_ajax',
3219 data: {data: JSON.stringify({
3220 model: this.view.dataset.model,
3221 id: (this.view.datarecord.id || ''),
3223 filename_field: (this.node.attrs.filename || ''),
3224 context: this.view.dataset.get_context()
3226 complete: $.unblockUI,
3227 error: openerp.webclient.crashmanager.on_rpc_error
3230 on_clear: function() {
3231 if (this.value !== false) {
3233 this.binary_value = false;
3234 this.on_ui_change();
3240 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3241 template: 'FieldBinaryFile',
3242 update_dom: function() {
3243 this._super.apply(this, arguments);
3244 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3245 this.$element.find('input[type=text]').prop('readonly', this.readonly);
3247 set_value: function(value) {
3248 this._super.apply(this, arguments);
3250 if (this.node.attrs.filename) {
3251 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3253 show_value = (value != null && value !== false) ? value : '';
3255 this.$element.find('input').eq(0).val(show_value);
3257 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3258 this.value = file_base64;
3259 this.binary_value = true;
3260 var show_value = name + " (" + this.human_filesize(size) + ")";
3261 this.$element.find('input').eq(0).val(show_value);
3262 this.set_filename(name);
3264 set_filename: function(value) {
3265 var filename = this.node.attrs.filename;
3266 if (this.view.fields[filename]) {
3267 this.view.fields[filename].set_value(value);
3268 this.view.fields[filename].on_ui_change();
3271 on_clear: function() {
3272 this._super.apply(this, arguments);
3273 this.$element.find('input').eq(0).val('');
3274 this.set_filename('');
3278 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3279 template: 'FieldBinaryImage',
3281 this._super.apply(this, arguments);
3282 this.$image = this.$element.find('img.oe-binary-image');
3284 update_dom: function() {
3285 this._super.apply(this, arguments);
3286 this.$element.find('.oe-binary').toggle(!this.readonly);
3288 set_value: function(value) {
3289 this._super.apply(this, arguments);
3290 this.set_image_maxwidth();
3291 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3292 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3293 this.$image.attr('src', url);
3295 set_image_maxwidth: function() {
3296 this.$image.css('max-width', this.$element.width());
3298 on_file_change: function() {
3299 this.set_image_maxwidth();
3300 this._super.apply(this, arguments);
3302 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3303 this.value = file_base64;
3304 this.binary_value = true;
3305 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3307 on_clear: function() {
3308 this._super.apply(this, arguments);
3309 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3313 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3314 template: "EmptyComponent",
3317 this.selected_value = null;
3321 set_value: function(value) {
3323 this.selected_value = value;
3327 render_list: function() {
3329 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3330 function(x) { return _.str.trim(x); });
3331 shown = _.select(shown, function(x) { return x.length > 0; });
3333 if (shown.length == 0) {
3334 this.to_show = this.field.selection;
3336 this.to_show = _.select(this.field.selection, function(x) {
3337 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3341 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3342 this.$element.html(content);
3344 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3345 var color = colors[this.selected_value];
3347 var elem = this.$element.find("li.oe-arrow-list-selected span");
3348 elem.css("border-color", color);
3349 if (this.check_white(color))
3350 elem.css("color", "white");
3351 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3352 elem.css("border-left-color", "rgba(0,0,0,0)");
3353 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3354 elem.css("border-color", "rgba(0,0,0,0)");
3355 elem.css("border-left-color", color);
3358 check_white: function(color) {
3359 var div = $("<div></div>");
3360 div.css("display", "none");
3361 div.css("color", color);
3362 div.appendTo($("body"));
3363 var ncolor = div.css("color");
3365 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3369 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3370 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3378 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3379 render: function () {
3380 var $root = $('<div class="oe_form_html_view">');
3381 this.render_children(this, $root);
3382 return $root.html();
3384 render_children: function (object, $into) {
3386 fields = this.view.fields_view.fields;
3387 _(object.children).each(function (child) {
3388 if (typeof child === 'string') {
3390 } else if (child.tag === 'field') {
3392 new (self.view.registry.get_object('frame'))(
3393 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3396 var $child = $(document.createElement(child.tag))
3399 self.render_children(child, $child);
3407 * Registry of form widgets, called by :js:`openerp.web.FormView`
3409 openerp.web.form.widgets = new openerp.web.Registry({
3410 'frame' : 'openerp.web.form.WidgetFrame',
3411 'group' : 'openerp.web.form.WidgetGroup',
3412 'notebook' : 'openerp.web.form.WidgetNotebook',
3413 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3414 'separator' : 'openerp.web.form.WidgetSeparator',
3415 'label' : 'openerp.web.form.WidgetLabel',
3416 'button' : 'openerp.web.form.WidgetButton',
3417 'char' : 'openerp.web.form.FieldChar',
3418 'id' : 'openerp.web.form.FieldID',
3419 'email' : 'openerp.web.form.FieldEmail',
3420 'url' : 'openerp.web.form.FieldUrl',
3421 'text' : 'openerp.web.form.FieldText',
3422 'date' : 'openerp.web.form.FieldDate',
3423 'datetime' : 'openerp.web.form.FieldDatetime',
3424 'selection' : 'openerp.web.form.FieldSelection',
3425 'many2one' : 'openerp.web.form.FieldMany2One',
3426 'many2many' : 'openerp.web.form.FieldMany2Many',
3427 'one2many' : 'openerp.web.form.FieldOne2Many',
3428 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3429 'reference' : 'openerp.web.form.FieldReference',
3430 'boolean' : 'openerp.web.form.FieldBoolean',
3431 'float' : 'openerp.web.form.FieldFloat',
3432 'integer': 'openerp.web.form.FieldFloat',
3433 'float_time': 'openerp.web.form.FieldFloat',
3434 'progressbar': 'openerp.web.form.FieldProgressBar',
3435 'image': 'openerp.web.form.FieldBinaryImage',
3436 'binary': 'openerp.web.form.FieldBinaryFile',
3437 'statusbar': 'openerp.web.form.FieldStatus',
3438 'html': 'openerp.web.form.WidgetHtml'
3444 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: