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 identifier_prefix: 'formview-',
17 display_name: _lt('Form'),
19 * @constructs openerp.web.FormView
20 * @extends openerp.web.View
22 * @param {openerp.web.Session} session the current openerp session
23 * @param {openerp.web.DataSet} dataset the dataset this view will work with
24 * @param {String} view_id the identifier of the OpenERP view object
25 * @param {Object} options
26 * - sidebar : [true|false]
27 * - resize_textareas : [true|false|max_height]
29 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
31 init: function(parent, dataset, view_id, options) {
33 this.set_default_options(options);
34 this.dataset = dataset;
35 this.model = dataset.model;
36 this.view_id = view_id || false;
37 this.fields_view = {};
39 this.widgets_counter = 0;
41 this.fields_order = [];
43 this.show_invalid = true;
44 this.default_focus_field = null;
45 this.default_focus_button = null;
46 this.registry = openerp.web.form.widgets;
47 this.has_been_loaded = $.Deferred();
48 this.$form_header = null;
49 this.translatable_fields = [];
50 _.defaults(this.options, {
51 "not_interactible_on_create": false
53 this.mutating_lock = $.Deferred();
54 this.initial_mutating_lock = this.mutating_lock;
55 this.on_change_lock = $.Deferred().resolve();
56 this.reload_lock = $.Deferred().resolve();
60 return this.init_view();
62 init_view: function() {
63 if (this.embedded_view) {
64 var def = $.Deferred().then(this.on_loaded);
66 $.async_when().then(function() {def.resolve(self.embedded_view);});
69 var context = new openerp.web.CompoundContext(this.dataset.get_context());
70 return this.rpc("/web/view/load", {
72 "view_id": this.view_id,
74 toolbar: this.options.sidebar,
81 this.sidebar.attachments.stop();
84 _.each(this.widgets, function(w) {
89 reposition: function ($e) {
93 on_loaded: function(data) {
96 this.fields_order = [];
97 this.fields_view = data;
98 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
100 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
102 this.$element.html(this.rendered);
103 _.each(this.widgets, function(w) {
106 this.$form_header = this.$element.find('.oe_form_header:first');
107 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
108 var action = $(this).data('pager-action');
109 self.on_pager_action(action);
112 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
113 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
115 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
116 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
117 this.sidebar.start();
118 this.sidebar.do_unfold();
119 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
120 this.sidebar.add_toolbar(this.fields_view.toolbar);
121 this.set_common_sidebar_sections(this.sidebar);
123 this.has_been_loaded.resolve();
126 do_load_state: function(state) {
127 if (state.id && this.datarecord.id != state.id) {
128 var idx = this.dataset.get_id_index(state.id);
130 this.dataset.ids.push(state.id)
131 this.dataset.index = this.dataset.ids.length - 1;
137 do_show: function () {
139 this.$element.show().css('visibility', 'hidden');
140 return this.has_been_loaded.pipe(function() {
142 if (self.dataset.index === null) {
143 // null index means we should start a new record
144 result = self.on_button_new();
146 result = self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
148 result.pipe(function() {
149 self.$element.css('visibility', 'visible');
152 self.sidebar.$element.show();
157 do_hide: function () {
160 this.sidebar.$element.hide();
163 on_record_loaded: function(record) {
164 var self = this, set_values = [];
166 throw new Error("Form: No record received");
168 this.datarecord = record;
170 _(this.fields).each(function (field, f) {
172 var result = field.set_value(self.datarecord[f] || false);
173 set_values.push(result);
174 $.when(result).then(function() {
178 return $.when.apply(null, set_values).pipe(function() {
180 self.show_invalid = false;
181 // New record: Second pass in order to trigger the onchanges
182 // respecting the fields order defined in the view
183 _.each(self.fields_order, function(field_name) {
184 if (record[field_name] !== undefined) {
185 var field = self.fields[field_name];
187 self.do_onchange(field);
191 self.on_form_changed();
192 self.initial_mutating_lock.resolve();
193 self.show_invalid = true;
194 self.do_update_pager(record.id == null);
196 self.sidebar.attachments.do_update();
198 if (self.default_focus_field && !self.embedded_view) {
199 self.default_focus_field.focus();
202 self.do_push_state({id:record.id});
206 on_form_changed: function() {
207 for (var w in this.widgets) {
209 w.process_modifiers();
213 on_pager_action: function(action) {
214 if (this.can_be_discarded()) {
217 this.dataset.index = 0;
220 this.dataset.previous();
226 this.dataset.index = this.dataset.ids.length - 1;
232 do_update_pager: function(hide_index) {
233 var $pager = this.$form_header.find('div.oe_form_pager');
234 var index = hide_index ? '-' : this.dataset.index + 1;
235 $pager.find('button').prop('disabled', this.dataset.ids.length < 2)
236 $pager.find('span.oe_pager_index').html(index);
237 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
239 parse_on_change: function (on_change, widget) {
241 var onchange = _.str.trim(on_change);
242 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
247 var method = call[1];
248 if (!_.str.trim(call[2])) {
249 return {method: method, args: [], context_index: null}
252 var argument_replacement = {
253 'False': function () {return false;},
254 'True': function () {return true;},
255 'None': function () {return null;},
256 'context': function (i) {
258 var ctx = widget.build_context ? widget.build_context() : {};
262 var parent_fields = null, context_index = null;
263 var args = _.map(call[2].split(','), function (a, i) {
264 var field = _.str.trim(a);
266 // literal constant or context
267 if (field in argument_replacement) {
268 return argument_replacement[field](i);
271 if (/^-?\d+(\.\d+)?$/.test(field)) {
272 return Number(field);
275 if (self.fields[field]) {
276 var value = self.fields[field].get_on_change_value();
277 return value == null ? false : value;
280 var splitted = field.split('.');
281 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
282 if (parent_fields === null) {
283 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
285 var p_val = parent_fields[_.str.trim(splitted[1])];
286 if (p_val !== undefined) {
287 return p_val == null ? false : p_val;
291 var first_char = field[0], last_char = field[field.length-1];
292 if ((first_char === '"' && last_char === '"')
293 || (first_char === "'" && last_char === "'")) {
294 return field.slice(1, -1);
297 throw new Error("Could not get field with name '" + field +
298 "' for onchange '" + onchange + "'");
304 context_index: context_index
307 do_onchange: function(widget, processed) {
309 var act = function() {
311 processed = processed || [];
312 var on_change = widget.node.attrs.on_change;
314 var change_spec = self.parse_on_change(on_change, widget);
317 url: '/web/dataset/call',
320 return self.rpc(ajax, {
321 model: self.dataset.model,
322 method: change_spec.method,
323 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
324 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
325 }).pipe(function(response) {
326 return self.on_processed_onchange(response, processed);
329 console.warn("Wrong on_change format", on_change);
334 return $.Deferred().reject();
337 this.on_change_lock = this.on_change_lock.pipe(act, act);
338 return this.on_change_lock;
340 on_processed_onchange: function(response, processed) {
342 var result = response;
344 for (var f in result.value) {
345 var field = this.fields[f];
346 // If field is not defined in the view, just ignore it
348 var value = result.value[f];
349 processed.push(field.name);
350 if (field.get_value() != value) {
351 field.set_value(value);
353 if (_.indexOf(processed, field.name) < 0) {
354 this.do_onchange(field, processed);
359 this.on_form_changed();
361 if (!_.isEmpty(result.warning)) {
362 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
365 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
372 return $.Deferred().resolve();
375 return $.Deferred().reject();
378 on_button_save: function() {
380 return this.do_save().then(function(result) {
381 self.do_prev_view(result.created);
384 on_button_cancel: function() {
385 return this.do_prev_view();
387 on_button_new: function() {
389 var def = $.Deferred();
390 $.when(this.has_been_loaded).then(function() {
391 if (self.can_be_discarded()) {
392 var keys = _.keys(self.fields_view.fields);
394 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
398 self.on_record_loaded({}).then(function() {
404 return def.promise();
406 can_be_discarded: function() {
407 return true; // FIXME: Disabled until the page view and button refactoring is done
408 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
411 * Triggers saving the form's record. Chooses between creating a new
412 * record or saving an existing one depending on whether the record
413 * already has an id property.
415 * @param {Function} success callback on save success
416 * @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)
418 do_save: function(success, prepend_on_create) {
420 var action = function() {
422 if (!self.initial_mutating_lock.isResolved() && !self.initial_mutating_lock.isRejected())
424 var form_invalid = false,
426 first_invalid_field = null;
427 for (var f in self.fields) {
432 if (!first_invalid_field) {
433 first_invalid_field = f;
435 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
436 // Special case 'id' field, do not save this field
437 // on 'create' : save all non readonly fields
438 // on 'edit' : save non readonly modified fields
439 values[f.name] = f.get_value();
443 first_invalid_field.focus();
445 return $.Deferred().reject();
448 if (!self.datarecord.id) {
449 console.log("FormView(", self, ") : About to create", values);
450 save_deferral = self.dataset.create(values).pipe(function(r) {
451 return self.on_created(r, undefined, prepend_on_create);
453 } else if (_.isEmpty(values)) {
454 console.log("FormView(", self, ") : Nothing to save");
455 save_deferral = $.Deferred().resolve({}).promise();
457 console.log("FormView(", self, ") : About to save", values);
458 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
459 return self.on_saved(r);
462 return save_deferral.then(success);
466 return $.Deferred().reject();
469 this.mutating_lock = this.mutating_lock.pipe(action, action);
470 return this.mutating_lock;
472 on_invalid: function() {
474 _.each(this.fields, function(f) {
476 msg += "<li>" + f.string + "</li>";
480 this.do_warn("The following fields are invalid :", msg);
482 on_saved: function(r, success) {
484 // should not happen in the server, but may happen for internal purpose
485 return $.Deferred().reject();
487 return $.when(this.reload()).pipe(function () {
488 return $.when(r).then(success); }, null);
492 * Updates the form' dataset to contain the new record:
494 * * Adds the newly created record to the current dataset (at the end by
496 * * Selects that record (sets the dataset's index to point to the new
498 * * Updates the pager and sidebar displays
501 * @param {Function} success callback to execute after having updated the dataset
502 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
504 on_created: function(r, success, prepend_on_create) {
506 // should not happen in the server, but may happen for internal purpose
507 return $.Deferred().reject();
509 this.datarecord.id = r.result;
510 if (!prepend_on_create) {
511 this.dataset.ids.push(this.datarecord.id);
512 this.dataset.index = this.dataset.ids.length - 1;
514 this.dataset.ids.unshift(this.datarecord.id);
515 this.dataset.index = 0;
517 this.do_update_pager();
519 this.sidebar.attachments.do_update();
521 openerp.log("The record has been created with id #" + this.datarecord.id);
523 return $.when(_.extend(r, {created: true})).then(success);
526 on_action: function (action) {
527 console.debug('Executing action', action);
531 var act = function() {
532 if (self.dataset.index == null || self.dataset.index < 0) {
533 return $.when(self.on_button_new());
535 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
538 this.reload_lock = this.reload_lock.pipe(act, act);
539 return this.reload_lock;
541 get_fields_values: function(blacklist) {
542 blacklist = blacklist || [];
544 _.each(this.fields, function(value, key) {
545 if (_.include(blacklist, key))
547 var val = value.get_value();
552 get_selected_ids: function() {
553 var id = this.dataset.ids[this.dataset.index];
554 return id ? [id] : [];
556 recursive_save: function() {
558 return $.when(this.do_save()).pipe(function(res) {
559 if (self.dataset.parent_view)
560 return self.dataset.parent_view.recursive_save();
563 is_dirty: function() {
564 return _.any(this.fields, function (value) {
565 return value.is_dirty();
568 is_interactible_record: function() {
569 var id = this.datarecord.id;
571 if (this.options.not_interactible_on_create)
573 } else if (typeof(id) === "string") {
574 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
579 sidebar_context: function () {
580 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
583 openerp.web.FormDialog = openerp.web.Dialog.extend({
584 init: function(parent, options, view_id, dataset) {
585 this._super(parent, options);
586 this.dataset = dataset;
587 this.view_id = view_id;
592 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
596 this.form.appendTo(this.$element);
597 this.form.on_created.add_last(this.on_form_dialog_saved);
598 this.form.on_saved.add_last(this.on_form_dialog_saved);
601 select_id: function(id) {
602 if (this.form.dataset.select_id(id)) {
603 return this.form.do_show();
605 this.do_warn("Could not find id in dataset");
606 return $.Deferred().reject();
609 on_form_dialog_saved: function(r) {
615 openerp.web.form = {};
617 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
618 init: function(parent, form_view) {
619 var $section = parent.add_section(_t('Attachments'), 'attachments');
620 this.$div = $('<div class="oe-sidebar-attachments"></div>');
621 $section.append(this.$div);
623 this._super(parent, $section.attr('id'));
624 this.view = form_view;
626 do_update: function() {
627 if (!this.view.datarecord.id) {
628 this.on_attachments_loaded([]);
630 (new openerp.web.DataSetSearch(
631 this, 'ir.attachment', this.view.dataset.get_context(),
633 ['res_model', '=', this.view.dataset.model],
634 ['res_id', '=', this.view.datarecord.id],
635 ['type', 'in', ['binary', 'url']]
636 ])).read_slice(['name', 'url', 'type'], {}, this.on_attachments_loaded);
639 on_attachments_loaded: function(attachments) {
640 this.attachments = attachments;
641 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
642 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
643 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
645 on_attachment_changed: function(e) {
646 window[this.element_id + '_iframe'] = this.do_update;
647 var $e = $(e.target);
648 if ($e.val() != '') {
649 this.$element.find('form.oe-binary-form').submit();
650 $e.parent().find('input[type=file]').prop('disabled', true);
651 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
654 on_attachment_delete: function(e) {
655 var self = this, $e = $(e.currentTarget);
656 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
657 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
658 this.rpc('/web/dataset/unlink', {
659 model: 'ir.attachment',
660 ids: [parseInt($e.attr('data-id'))]
662 $e.parent().remove();
663 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
669 openerp.web.form.compute_domain = function(expr, fields) {
671 for (var i = expr.length - 1; i >= 0; i--) {
673 if (ex.length == 1) {
674 var top = stack.pop();
677 stack.push(stack.pop() || top);
680 stack.push(stack.pop() && top);
686 throw new Error('Unknown domain operator ' + ex);
690 var field = fields[ex[0]];
692 throw new Error("Domain references unknown field : " + ex[0]);
694 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
698 switch (op.toLowerCase()) {
701 stack.push(field_value == val);
705 stack.push(field_value != val);
708 stack.push(field_value < val);
711 stack.push(field_value > val);
714 stack.push(field_value <= val);
717 stack.push(field_value >= val);
720 stack.push(_(val).contains(field_value));
723 stack.push(!_(val).contains(field_value));
726 console.warn("Unsupported operator in modifiers :", op);
729 return _.all(stack, _.identity);
732 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
734 identifier_prefix: 'formview-widget-',
736 * @constructs openerp.web.form.Widget
737 * @extends openerp.web.Widget
742 init: function(view, node) {
745 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
746 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
747 this.type = this.type || node.tag;
748 this.element_name = this.element_name || this.type;
749 this.element_class = [
750 'formview', this.view.view_id, this.element_name,
751 this.view.widgets_counter++].join("_");
755 this.view.widgets[this.element_class] = this;
756 this.children = node.children;
757 this.colspan = parseInt(node.attrs.colspan || 1, 10);
758 this.decrease_max_width = 0;
760 this.string = this.string || node.attrs.string;
761 this.help = this.help || node.attrs.help;
762 this.invisible = this.modifiers['invisible'] === true;
763 this.classname = 'oe_form_' + this.type;
765 this.align = parseFloat(this.node.attrs.align);
766 if (isNaN(this.align) || this.align === 1) {
767 this.align = 'right';
768 } else if (this.align === 0) {
771 this.align = 'center';
775 this.width = this.node.attrs.width;
778 this.$element = this.view.$element.find(
779 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
781 process_modifiers: function() {
782 var compute_domain = openerp.web.form.compute_domain;
783 for (var a in this.modifiers) {
784 this[a] = compute_domain(this.modifiers[a], this.view.fields);
787 update_dom: function() {
788 this.$element.toggle(!this.invisible);
791 var template = this.template;
792 return QWeb.render(template, { "widget": this });
794 do_attach_tooltip: function(widget, trigger, options) {
795 widget = widget || this;
796 trigger = trigger || this.$element;
800 content: function() {
801 var template = widget.template + '.tooltip';
802 if (!QWeb.has_template(template)) {
803 template = 'WidgetLabel.tooltip';
805 return QWeb.render(template, {
806 debug: openerp.connection.debug,
811 trigger.tipTip(options);
813 _build_view_fields_values: function(blacklist) {
814 var a_dataset = this.view.dataset;
815 var fields_values = this.view.get_fields_values(blacklist);
816 var active_id = a_dataset.ids[a_dataset.index];
817 _.extend(fields_values, {
818 active_id: active_id || false,
819 active_ids: active_id ? [active_id] : [],
820 active_model: a_dataset.model,
823 if (a_dataset.parent_view) {
824 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
826 return fields_values;
828 _build_eval_context: function(blacklist) {
829 var a_dataset = this.view.dataset;
830 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
833 * Builds a new context usable for operations related to fields by merging
834 * the fields'context with the action's context.
836 build_context: function(blacklist) {
837 var f_context = (this.field || {}).context || {};
838 if (!!f_context.__ref || true) { //TODO: remove true
839 var fields_values = this._build_eval_context(blacklist);
840 f_context = new openerp.web.CompoundContext(f_context).set_eval_context(fields_values);
842 // maybe the default_get should only be used when we do a default_get?
843 var v_contexts = _.compact([this.node.attrs.default_get || null,
844 this.node.attrs.context || null]);
845 var v_context = new openerp.web.CompoundContext();
846 _.each(v_contexts, function(x) {v_context.add(x);});
847 if (_.detect(v_contexts, function(x) {return !!x.__ref;}) || true) { //TODO: remove true
848 var fields_values = this._build_eval_context(blacklist);
849 v_context.set_eval_context(fields_values);
851 // if there is a context on the node, overrides the model's context
852 var ctx = v_contexts.length > 0 ? v_context : f_context;
855 build_domain: function() {
856 var f_domain = this.field.domain || [];
857 var n_domain = this.node.attrs.domain || null;
858 // if there is a domain on the node, overrides the model's domain
859 var final_domain = n_domain !== null ? n_domain : f_domain;
860 if (!(final_domain instanceof Array) || true) { //TODO: remove true
861 var fields_values = this._build_eval_context();
862 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
868 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
869 template: 'WidgetFrame',
870 init: function(view, node) {
871 this._super(view, node);
872 this.columns = parseInt(node.attrs.col || 4, 10);
877 for (var i = 0; i < node.children.length; i++) {
878 var n = node.children[i];
879 if (n.tag == "newline") {
885 this.set_row_cells_with(this.table[this.table.length - 1]);
888 if (this.table.length) {
889 this.set_row_cells_with(this.table[this.table.length - 1]);
892 this.table.push(row);
897 set_row_cells_with: function(row) {
900 row_length = row.length;
901 for (var i = 0; i < row.length; i++) {
902 if (row[i].always_invisible) {
905 bypass += row[i].width === undefined ? 0 : 1;
906 max_width -= row[i].decrease_max_width;
909 var size_unit = Math.round(max_width / (this.columns - bypass)),
911 for (var i = 0; i < row.length; i++) {
913 if (w.always_invisible) {
916 colspan_sum += w.colspan;
917 if (w.width === undefined) {
918 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
920 w.width = width + '%';
924 handle_node: function(node) {
926 if (node.tag == 'field') {
927 type = this.view.fields_view.fields[node.attrs.name] || {};
928 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
929 // This way we can retain backward compatibility between addons and old clients
930 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
931 node.attrs.nolabel = '1';
934 var widget = new (this.view.registry.get_any(
935 [node.attrs.widget, type.type, node.tag])) (this.view, node);
936 if (node.tag == 'field') {
937 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
938 this.view.default_focus_field = widget;
940 if (node.attrs.nolabel != '1') {
941 var label = new (this.view.registry.get_object('label')) (this.view, node);
942 label["for"] = widget;
943 this.add_widget(label, widget.colspan + 1);
946 this.add_widget(widget);
948 add_widget: function(widget, colspan) {
949 var current_row = this.table[this.table.length - 1];
950 if (!widget.always_invisible) {
951 colspan = colspan || widget.colspan;
952 if (current_row.length && (this.x + colspan) > this.columns) {
953 current_row = this.add_row();
955 this.x += widget.colspan;
957 current_row.push(widget);
962 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
963 template: 'WidgetGroup'
966 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
967 template: 'WidgetNotebook',
968 init: function(view, node) {
969 this._super(view, node);
971 for (var i = 0; i < node.children.length; i++) {
972 var n = node.children[i];
973 if (n.tag == "page") {
974 var page = new (this.view.registry.get_object('notebookpage'))(
975 this.view, n, this, this.pages.length);
976 this.pages.push(page);
982 this._super.apply(this, arguments);
983 this.$element.find('> ul > li').each(function (index, tab_li) {
984 var page = self.pages[index],
985 id = _.uniqueId(self.element_name + '-');
986 page.element_id = id;
987 $(tab_li).find('a').attr('href', '#' + id);
989 this.$element.find('> div').each(function (index, page) {
990 page.id = self.pages[index].element_id;
992 this.$element.tabs();
993 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
994 if (openerp.connection.debug) {
995 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
996 defaultPosition: 'top'
1000 do_select_first_visible_tab: function() {
1001 for (var i = 0; i < this.pages.length; i++) {
1002 var page = this.pages[i];
1003 if (page.invisible === false) {
1004 this.$element.tabs('select', page.index);
1011 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1012 template: 'WidgetNotebookPage',
1013 init: function(view, node, notebook, index) {
1014 this.notebook = notebook;
1016 this.element_name = 'page_' + index;
1017 this._super(view, node);
1020 this._super.apply(this, arguments);
1021 this.$element_tab = this.notebook.$element.find(
1022 '> ul > li:eq(' + this.index + ')');
1024 update_dom: function() {
1025 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1026 this.notebook.do_select_first_visible_tab();
1028 this.$element_tab.toggle(!this.invisible);
1029 this.$element.toggle(!this.invisible);
1033 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1034 template: 'WidgetSeparator',
1035 init: function(view, node) {
1036 this._super(view, node);
1037 this.orientation = node.attrs.orientation || 'horizontal';
1038 if (this.orientation === 'vertical') {
1041 this.classname += '_' + this.orientation;
1045 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1046 template: 'WidgetButton',
1047 init: function(view, node) {
1048 this._super(view, node);
1049 this.force_disabled = false;
1051 // We don't have button key bindings in the webclient
1052 this.string = this.string.replace(/_/g, '');
1054 if (node.attrs.default_focus == '1') {
1055 // TODO fme: provide enter key binding to widgets
1056 this.view.default_focus_button = this;
1060 this._super.apply(this, arguments);
1061 this.$element.find("button").click(this.on_click);
1062 if (this.help || openerp.connection.debug) {
1063 this.do_attach_tooltip();
1066 on_click: function() {
1068 this.force_disabled = true;
1069 this.check_disable();
1070 this.execute_action().always(function() {
1071 self.force_disabled = false;
1072 self.check_disable();
1076 execute_action: function() {
1078 var exec_action = function() {
1079 if (self.node.attrs.confirm) {
1080 var def = $.Deferred();
1081 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1082 title: _t('Confirm'),
1085 {text: _t("Ok"), click: function() {
1086 self.on_confirmed().then(function() {
1089 $(this).dialog("close");
1092 {text: _t("Cancel"), click: function() {
1094 $(this).dialog("close");
1099 return def.promise();
1101 return self.on_confirmed();
1104 if (!this.node.attrs.special) {
1105 return this.view.recursive_save().pipe(exec_action);
1107 return exec_action();
1110 on_confirmed: function() {
1113 var context = this.node.attrs.context;
1114 if (context && context.__ref) {
1115 context = new openerp.web.CompoundContext(context);
1116 context.set_eval_context(this._build_eval_context());
1119 return this.view.do_execute_action(
1120 _.extend({}, this.node.attrs, {context: context}),
1121 this.view.dataset, this.view.datarecord.id, function () {
1125 update_dom: function() {
1127 this.check_disable();
1129 check_disable: function() {
1130 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1131 this.$element.find('button').prop('disabled', disabled);
1132 this.$element.find("button").css('color', disabled ? 'grey' : '');
1136 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1137 template: 'WidgetLabel',
1138 init: function(view, node) {
1139 this.element_name = 'label_' + node.attrs.name;
1141 this._super(view, node);
1143 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1144 this.template = "WidgetParagraph";
1145 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1146 // Widgets default to right-aligned, but paragraph defaults to
1148 if (isNaN(parseFloat(this.node.attrs.align))) {
1149 this.align = 'left';
1154 this.decrease_max_width = 1;
1158 render: function () {
1159 if (this['for'] && this.type !== 'label') {
1160 return QWeb.render(this.template, {widget: this['for']});
1162 // Actual label widgets should not have a false and have type label
1163 return QWeb.render(this.template, {widget: this});
1168 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1169 this.do_attach_tooltip(self['for']);
1171 this.$element.find("label").dblclick(function() {
1172 var widget = self['for'] || self;
1173 openerp.log(widget.element_class , widget);
1179 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1181 * @constructs openerp.web.form.Field
1182 * @extends openerp.web.form.Widget
1187 init: function(view, node) {
1188 this.name = node.attrs.name;
1189 this.value = undefined;
1190 view.fields[this.name] = this;
1191 view.fields_order.push(this.name);
1192 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1193 this.element_name = "field_" + this.name + "_" + this.type;
1195 this._super(view, node);
1197 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1200 this.field = view.fields_view.fields[node.attrs.name] || {};
1201 this.string = node.attrs.string || this.field.string;
1202 this.help = node.attrs.help || this.field.help;
1203 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1204 this.readonly = this.modifiers['readonly'] === true;
1205 this.required = this.modifiers['required'] === true;
1206 this.invalid = this.dirty = false;
1208 this.classname = 'oe_form_field_' + this.type;
1211 this._super.apply(this, arguments);
1212 if (this.field.translate) {
1213 this.view.translatable_fields.push(this);
1214 this.$element.find('.oe_field_translate').click(this.on_translate);
1216 if (this.nolabel && openerp.connection.debug) {
1217 this.do_attach_tooltip(this, this.$element, {
1218 defaultPosition: 'top'
1222 set_value: function(value) {
1224 this.invalid = false;
1226 this.on_value_changed();
1228 set_value_from_ui: function() {
1229 this.on_value_changed();
1231 on_value_changed: function() {
1233 on_translate: function() {
1234 this.view.open_translate_dialog(this);
1236 get_value: function() {
1239 is_valid: function() {
1240 return !this.invalid;
1242 is_dirty: function() {
1243 return this.dirty && !this.readonly;
1245 get_on_change_value: function() {
1246 return this.get_value();
1248 update_dom: function() {
1249 this._super.apply(this, arguments);
1250 if (this.field.translate) {
1251 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1253 if (!this.disable_utility_classes) {
1254 this.$element.toggleClass('disabled', this.readonly);
1255 this.$element.toggleClass('required', this.required);
1256 if (this.view.show_invalid) {
1257 this.$element.toggleClass('invalid', !this.is_valid());
1261 on_ui_change: function() {
1264 if (this.is_valid()) {
1265 this.set_value_from_ui();
1266 this.view.do_onchange(this);
1267 this.view.on_form_changed();
1272 validate: function() {
1273 this.invalid = false;
1280 get_definition_options: function() {
1281 if (!this.definition_options) {
1282 var str = this.node.attrs.options || '{}';
1283 this.definition_options = JSON.parse(str);
1285 return this.definition_options;
1289 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1290 template: 'FieldChar',
1291 init: function (view, node) {
1292 this._super(view, node);
1293 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1296 this._super.apply(this, arguments);
1297 this.$element.find('input').change(this.on_ui_change);
1299 set_value: function(value) {
1300 this._super.apply(this, arguments);
1301 var show_value = openerp.web.format_value(value, this, '');
1302 this.$element.find('input').val(show_value);
1305 update_dom: function() {
1306 this._super.apply(this, arguments);
1307 this.$element.find('input').prop('disabled', this.readonly);
1309 set_value_from_ui: function() {
1310 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1313 validate: function() {
1314 this.invalid = false;
1316 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1317 this.invalid = this.required && value === '';
1319 this.invalid = true;
1323 this.$element.find('input').focus();
1327 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1328 template: 'FieldEmail',
1330 this._super.apply(this, arguments);
1331 this.$element.find('button').click(this.on_button_clicked);
1333 on_button_clicked: function() {
1334 if (!this.value || !this.is_valid()) {
1335 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1337 location.href = 'mailto:' + this.value;
1342 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1343 template: 'FieldUrl',
1345 this._super.apply(this, arguments);
1346 this.$element.find('button').click(this.on_button_clicked);
1348 on_button_clicked: function() {
1350 this.do_warn("Resource error", "This resource is empty");
1352 window.open(this.value);
1357 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1358 init: function (view, node) {
1359 this._super(view, node);
1360 if (node.attrs.digits) {
1361 this.parse_digits(node.attrs.digits);
1363 this.digits = view.fields_view.fields[node.attrs.name].digits;
1366 parse_digits: function (digits_attr) {
1367 // could use a Python parser instead.
1368 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1369 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1371 set_value: function(value) {
1372 if (value === false || value === undefined) {
1373 // As in GTK client, floats default to 0
1376 this._super.apply(this, [value]);
1380 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1381 template: "web.datetimepicker",
1382 jqueryui_object: 'datetimepicker',
1383 type_of_date: "datetime",
1384 init: function(parent) {
1385 this._super(parent);
1386 this.name = parent.name;
1390 this.$input = this.$element.find('input.oe_datepicker_master');
1391 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1392 this.$input.change(this.on_change);
1394 onSelect: this.on_picker_select,
1398 showButtonPanel: true
1400 this.$element.find('img.oe_datepicker_trigger').click(function() {
1401 if (!self.readonly) {
1402 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1403 self.$input_picker.show();
1404 self.picker('show');
1405 self.$input_picker.hide();
1408 this.set_readonly(false);
1411 picker: function() {
1412 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1414 on_picker_select: function(text, instance) {
1415 var date = this.picker('getDate');
1416 this.$input.val(date ? this.format_client(date) : '').change();
1418 set_value: function(value) {
1420 this.$input.val(value ? this.format_client(value) : '');
1422 get_value: function() {
1425 set_value_from_ui: function() {
1426 var value = this.$input.val() || false;
1427 this.value = this.parse_client(value);
1429 set_readonly: function(readonly) {
1430 this.readonly = readonly;
1431 this.$input.prop('disabled', this.readonly);
1432 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1434 is_valid: function(required) {
1435 var value = this.$input.val();
1440 this.parse_client(value);
1448 this.$input.focus();
1450 parse_client: function(v) {
1451 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1453 format_client: function(v) {
1454 return openerp.web.format_value(v, {"widget": this.type_of_date});
1456 on_change: function() {
1457 if (this.is_valid()) {
1458 this.set_value_from_ui();
1463 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1464 jqueryui_object: 'datepicker',
1465 type_of_date: "date"
1468 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1469 template: "EmptyComponent",
1470 build_widget: function() {
1471 return new openerp.web.DateTimeWidget(this);
1475 this._super.apply(this, arguments);
1476 this.datewidget = this.build_widget();
1477 this.datewidget.on_change.add_last(this.on_ui_change);
1478 this.datewidget.appendTo(this.$element);
1480 set_value: function(value) {
1482 this.datewidget.set_value(value);
1484 get_value: function() {
1485 return this.datewidget.get_value();
1487 update_dom: function() {
1488 this._super.apply(this, arguments);
1489 this.datewidget.set_readonly(this.readonly);
1491 validate: function() {
1492 this.invalid = !this.datewidget.is_valid(this.required);
1495 this.datewidget.focus();
1499 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1500 build_widget: function() {
1501 return new openerp.web.DateWidget(this);
1505 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1506 template: 'FieldText',
1508 this._super.apply(this, arguments);
1509 this.$element.find('textarea').change(this.on_ui_change);
1510 this.resized = false;
1512 set_value: function(value) {
1513 this._super.apply(this, arguments);
1514 var show_value = openerp.web.format_value(value, this, '');
1515 this.$element.find('textarea').val(show_value);
1516 if (!this.resized && this.view.options.resize_textareas) {
1517 this.do_resize(this.view.options.resize_textareas);
1518 this.resized = true;
1521 update_dom: function() {
1522 this._super.apply(this, arguments);
1523 this.$element.find('textarea').prop('disabled', this.readonly);
1525 set_value_from_ui: function() {
1526 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1529 validate: function() {
1530 this.invalid = false;
1532 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1533 this.invalid = this.required && value === '';
1535 this.invalid = true;
1539 this.$element.find('textarea').focus();
1541 do_resize: function(max_height) {
1542 max_height = parseInt(max_height, 10);
1543 var $input = this.$element.find('textarea'),
1544 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1546 $div.text($input.val());
1547 _.each('font-family,font-size,white-space'.split(','), function(style) {
1548 $div.css(style, $input.css(style));
1550 $div.appendTo($('body'));
1551 new_height = $div.height();
1552 if (new_height < 90) {
1555 if (!isNaN(max_height) && new_height > max_height) {
1556 new_height = max_height;
1559 $input.height(new_height);
1562 this.resized = false;
1566 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1567 template: 'FieldBoolean',
1570 this._super.apply(this, arguments);
1571 this.$element.find('input').click(self.on_ui_change);
1573 set_value: function(value) {
1574 this._super.apply(this, arguments);
1575 this.$element.find('input')[0].checked = value;
1577 set_value_from_ui: function() {
1578 this.value = this.$element.find('input').is(':checked');
1581 update_dom: function() {
1582 this._super.apply(this, arguments);
1583 this.$element.find('input').prop('disabled', this.readonly);
1586 this.$element.find('input').focus();
1590 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1591 template: 'FieldProgressBar',
1593 this._super.apply(this, arguments);
1594 this.$element.find('div').progressbar({
1596 disabled: this.readonly
1599 set_value: function(value) {
1600 this._super.apply(this, arguments);
1601 var show_value = Number(value);
1602 if (isNaN(show_value)) {
1605 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1609 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1610 // to replace view editor
1613 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1614 template: 'FieldSelection',
1615 init: function(view, node) {
1617 this._super(view, node);
1618 this.values = _.clone(this.field.selection);
1619 _.each(this.values, function(v, i) {
1620 if (v[0] === false && v[1] === '') {
1621 self.values.splice(i, 1);
1624 this.values.unshift([false, '']);
1627 // Flag indicating whether we're in an event chain containing a change
1628 // event on the select, in order to know what to do on keyup[RETURN]:
1629 // * If the user presses [RETURN] as part of changing the value of a
1630 // selection, we should just let the value change and not let the
1631 // event broadcast further (e.g. to validating the current state of
1632 // the form in editable list view, which would lead to saving the
1633 // current row or switching to the next one)
1634 // * If the user presses [RETURN] with a select closed (side-effect:
1635 // also if the user opened the select and pressed [RETURN] without
1636 // changing the selected value), takes the action as validating the
1638 var ischanging = false;
1639 this._super.apply(this, arguments);
1640 this.$element.find('select')
1641 .change(this.on_ui_change)
1642 .change(function () { ischanging = true; })
1643 .click(function () { ischanging = false; })
1644 .keyup(function (e) {
1645 if (e.which !== 13 || !ischanging) { return; }
1646 e.stopPropagation();
1650 set_value: function(value) {
1651 value = value === null ? false : value;
1652 value = value instanceof Array ? value[0] : value;
1655 for (var i = 0, ii = this.values.length; i < ii; i++) {
1656 if (this.values[i][0] === value) index = i;
1658 this.$element.find('select')[0].selectedIndex = index;
1660 set_value_from_ui: function() {
1661 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1664 update_dom: function() {
1665 this._super.apply(this, arguments);
1666 this.$element.find('select').prop('disabled', this.readonly);
1668 validate: function() {
1669 var value = this.values[this.$element.find('select')[0].selectedIndex];
1670 this.invalid = !(value && !(this.required && value[0] === false));
1673 this.$element.find('select').focus();
1677 // jquery autocomplete tweak to allow html
1679 var proto = $.ui.autocomplete.prototype,
1680 initSource = proto._initSource;
1682 function filter( array, term ) {
1683 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1684 return $.grep( array, function(value) {
1685 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1690 _initSource: function() {
1691 if ( this.options.html && $.isArray(this.options.source) ) {
1692 this.source = function( request, response ) {
1693 response( filter( this.options.source, request.term ) );
1696 initSource.call( this );
1700 _renderItem: function( ul, item) {
1701 return $( "<li></li>" )
1702 .data( "item.autocomplete", item )
1703 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1709 openerp.web.form.dialog = function(content, options) {
1710 options = _.extend({
1717 options.autoOpen = true;
1718 var dialog = new openerp.web.Dialog(null, options);
1719 dialog.$element = $(content).dialog(dialog.dialog_options);
1720 return dialog.$element;
1723 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1724 template: 'FieldMany2One',
1725 init: function(view, node) {
1726 this._super(view, node);
1729 this.cm_id = _.uniqueId('m2o_cm_');
1730 this.last_search = [];
1731 this.tmp_value = undefined;
1736 this.$input = this.$element.find("input");
1737 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1738 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1741 var init_context_menu_def = $.Deferred().then(function(e) {
1742 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1743 rdataset.call("get", ['action', 'client_action_relate',
1744 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1745 .then(function(result) {
1746 self.related_entries = result;
1748 var $cmenu = $("#" + self.cm_id);
1749 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1751 bindings[self.cm_id + "_search"] = function() {
1752 self._search_create_popup("search");
1754 bindings[self.cm_id + "_create"] = function() {
1755 self._search_create_popup("form");
1757 bindings[self.cm_id + "_open"] = function() {
1761 var pop = new openerp.web.form.FormOpenPopup(self.view);
1763 self.field.relation,
1765 self.build_context(),
1767 title: _t("Open: ") + (self.string || self.name)
1770 pop.on_write_completed.add_last(function() {
1771 self.set_value(self.value[0]);
1774 _.each(_.range(self.related_entries.length), function(i) {
1775 bindings[self.cm_id + "_related_" + i] = function() {
1776 self.open_related(self.related_entries[i]);
1779 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1780 bindings: bindings, itemStyle: {"color": ""},
1781 onContextMenu: function() {
1783 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1785 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1787 if (!self.readonly) {
1788 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1790 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1793 }, menuStyle: {width: "200px"}
1795 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1798 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1799 this.$menu_btn.bind('contextmenu', ctx_callback);
1800 this.$menu_btn.click(ctx_callback);
1802 // some behavior for input
1803 this.$input.keyup(function() {
1804 if (self.$input.val() === "") {
1805 self._change_int_value(null);
1806 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1807 self._change_int_value(undefined);
1810 this.$drop_down.click(function() {
1813 if (self.$input.autocomplete("widget").is(":visible")) {
1814 self.$input.autocomplete("close");
1817 self.$input.autocomplete("search", "");
1819 self.$input.autocomplete("search");
1821 self.$input.focus();
1824 var anyoneLoosesFocus = function() {
1825 if (!self.$input.is(":focus") &&
1826 !self.$input.autocomplete("widget").is(":visible") &&
1828 if (self.value === undefined && self.last_search.length > 0) {
1829 self._change_int_ext_value(self.last_search[0]);
1831 self._change_int_ext_value(null);
1835 this.$input.focusout(anyoneLoosesFocus);
1837 var isSelecting = false;
1839 this.$input.autocomplete({
1840 source: function(req, resp) { self.get_search_result(req, resp); },
1841 select: function(event, ui) {
1845 self._change_int_value([item.id, item.name]);
1846 } else if (item.action) {
1847 self._change_int_value(undefined);
1852 focus: function(e, ui) {
1856 close: anyoneLoosesFocus,
1860 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1861 this.$input.keyup(function(e) {
1862 if (e.which === 13) {
1864 e.stopPropagation();
1866 isSelecting = false;
1869 // autocomplete component content handling
1870 get_search_result: function(request, response) {
1871 var search_val = request.term;
1874 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1876 dataset.name_search(search_val, self.build_domain(), 'ilike',
1877 this.limit + 1, function(data) {
1878 self.last_search = data;
1879 // possible selections for the m2o
1880 var values = _.map(data, function(x) {
1881 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1884 // search more... if more results that max
1885 if (values.length > self.limit) {
1886 values = values.slice(0, self.limit);
1887 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
1888 dataset.name_search(search_val, self.build_domain(), 'ilike'
1889 , false, function(data) {
1890 self._change_int_value(null);
1891 self._search_create_popup("search", data);
1896 var raw_result = _(data.result).map(function(x) {return x[1];});
1897 if (search_val.length > 0 &&
1898 !_.include(raw_result, search_val) &&
1899 (!self.value || search_val !== self.value[1])) {
1900 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
1901 $('<span />').text(search_val).html()), action: function() {
1902 self._quick_create(search_val);
1906 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
1907 self._change_int_value(null);
1908 self._search_create_popup("form", undefined, {"default_name": search_val});
1914 _quick_create: function(name) {
1916 var slow_create = function() {
1917 self._change_int_value(null);
1918 self._search_create_popup("form", undefined, {"default_name": name});
1920 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
1921 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1922 dataset.name_create(name, function(data) {
1923 self._change_int_ext_value(data);
1924 }).fail(function(error, event) {
1925 event.preventDefault();
1931 // all search/create popup handling
1932 _search_create_popup: function(view, ids, context) {
1934 var pop = new openerp.web.form.SelectCreatePopup(this);
1936 self.field.relation,
1938 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
1939 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1941 disable_multiple_selection: true
1943 self.build_domain(),
1944 new openerp.web.CompoundContext(self.build_context(), context || {})
1946 pop.on_select_elements.add(function(element_ids) {
1947 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1948 dataset.name_get([element_ids[0]], function(data) {
1949 self._change_int_ext_value(data[0]);
1953 _change_int_ext_value: function(value) {
1954 this._change_int_value(value);
1955 this.$input.val(this.value ? this.value[1] : "");
1957 _change_int_value: function(value) {
1959 var back_orig_value = this.original_value;
1960 if (this.value === null || this.value) {
1961 this.original_value = this.value;
1963 if (back_orig_value === undefined) { // first use after a set_value()
1966 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1967 !== (this.value ? this.value[0] : null))) {
1968 this.on_ui_change();
1971 set_value: function(value) {
1972 value = value || null;
1973 this.invalid = false;
1975 this.tmp_value = value;
1977 self.on_value_changed();
1978 var real_set_value = function(rval) {
1979 self.tmp_value = undefined;
1981 self.original_value = undefined;
1982 self._change_int_ext_value(rval);
1984 if (value && !(value instanceof Array)) {
1985 // name_get in a m2o does not use the context of the field
1986 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
1987 dataset.name_get([value], function(data) {
1988 real_set_value(data[0]);
1989 }).fail(function() {self.tmp_value = undefined;});
1991 $.async_when().then(function() {real_set_value(value);});
1994 get_value: function() {
1995 if (this.tmp_value !== undefined) {
1996 if (this.tmp_value instanceof Array) {
1997 return this.tmp_value[0];
1999 return this.tmp_value ? this.tmp_value : false;
2001 if (this.value === undefined)
2002 return this.original_value ? this.original_value[0] : false;
2003 return this.value ? this.value[0] : false;
2005 validate: function() {
2006 this.invalid = false;
2007 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2009 this.invalid = this.required;
2012 open_related: function(related) {
2016 var additional_context = {
2017 active_id: self.value[0],
2018 active_ids: [self.value[0]],
2019 active_model: self.field.relation
2021 self.rpc("/web/action/load", {
2022 action_id: related[2].id,
2023 context: additional_context
2024 }, function(result) {
2025 result.result.context = _.extend(result.result.context || {}, additional_context);
2026 self.do_action(result.result);
2029 focus: function () {
2030 this.$input.focus();
2032 update_dom: function() {
2033 this._super.apply(this, arguments);
2034 this.$input.prop('disabled', this.readonly);
2039 # Values: (0, 0, { fields }) create
2040 # (1, ID, { fields }) update
2041 # (2, ID) remove (delete)
2042 # (3, ID) unlink one (target id or target of relation)
2044 # (5) unlink all (only valid for one2many)
2049 'create': function (values) {
2050 return [commands.CREATE, false, values];
2052 // (1, id, {values})
2054 'update': function (id, values) {
2055 return [commands.UPDATE, id, values];
2059 'delete': function (id) {
2060 return [commands.DELETE, id, false];
2062 // (3, id[, _]) removes relation, but not linked record itself
2064 'forget': function (id) {
2065 return [commands.FORGET, id, false];
2069 'link_to': function (id) {
2070 return [commands.LINK_TO, id, false];
2074 'delete_all': function () {
2075 return [5, false, false];
2077 // (6, _, ids) replaces all linked records with provided ids
2079 'replace_with': function (ids) {
2080 return [6, false, ids];
2083 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2084 template: 'FieldOne2Many',
2085 multi_selection: false,
2086 init: function(view, node) {
2087 this._super(view, node);
2088 this.is_loaded = $.Deferred();
2089 this.initial_is_loaded = this.is_loaded;
2090 this.is_setted = $.Deferred();
2091 this.form_last_update = $.Deferred();
2092 this.init_form_last_update = this.form_last_update;
2093 this.disable_utility_classes = true;
2096 this._super.apply(this, arguments);
2100 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2101 this.dataset.o2m = this;
2102 this.dataset.parent_view = this.view;
2103 this.dataset.child_name = this.name;
2104 //this.dataset.child_name =
2105 this.dataset.on_change.add_last(function() {
2106 self.trigger_on_change();
2109 this.is_setted.then(function() {
2113 trigger_on_change: function() {
2114 var tmp = this.doing_on_change;
2115 this.doing_on_change = true;
2116 this.on_ui_change();
2117 this.doing_on_change = tmp;
2119 is_readonly: function() {
2120 return this.readonly || this.force_readonly;
2122 load_views: function() {
2125 var modes = this.node.attrs.mode;
2126 modes = !!modes ? modes.split(",") : ["tree"];
2128 _.each(modes, function(mode) {
2131 view_type: mode == "tree" ? "list" : mode,
2132 options: { sidebar : false }
2134 if (self.field.views && self.field.views[mode]) {
2135 view.embedded_view = self.field.views[mode];
2137 if(view.view_type === "list") {
2138 view.options.selectable = self.multi_selection;
2139 if (self.is_readonly()) {
2140 view.options.addable = null;
2141 view.options.deletable = null;
2142 view.options.isClarkGable = false;
2144 } else if (view.view_type === "form") {
2145 if (self.is_readonly()) {
2146 view.view_type = 'page';
2148 view.options.not_interactible_on_create = true;
2154 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2155 this.viewmanager.template = 'One2Many.viewmanager';
2156 this.viewmanager.registry = openerp.web.views.clone({
2157 list: 'openerp.web.form.One2ManyListView',
2158 form: 'openerp.web.form.One2ManyFormView',
2159 page: 'openerp.web.PageView'
2161 var once = $.Deferred().then(function() {
2162 self.init_form_last_update.resolve();
2164 var def = $.Deferred().then(function() {
2165 self.initial_is_loaded.resolve();
2167 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2168 if (view_type == "list") {
2169 controller.o2m = self;
2170 if (self.is_readonly())
2171 controller.set_editable(false);
2172 } else if (view_type == "form" || view_type == 'page') {
2173 if (view_type == 'page' || self.is_readonly()) {
2174 $(".oe_form_buttons", controller.$element).children().remove();
2176 controller.on_record_loaded.add_last(function() {
2179 controller.on_pager_action.add_first(function() {
2180 self.save_any_view();
2182 } else if (view_type == "graph") {
2183 self.reload_current_view()
2187 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2188 $.when(self.save_any_view()).then(function() {
2189 if(n_mode === "list")
2190 $.async_when().then(function() {self.reload_current_view();});
2193 this.is_setted.then(function() {
2194 $.async_when().then(function () {
2195 self.viewmanager.appendTo(self.$element);
2200 reload_current_view: function() {
2202 return self.is_loaded = self.is_loaded.pipe(function() {
2203 var active_view = self.viewmanager.active_view;
2204 var view = self.viewmanager.views[active_view].controller;
2205 if(active_view === "list") {
2206 return view.reload_content();
2207 } else if (active_view === "form" || active_view === 'page') {
2208 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2209 self.dataset.index = 0;
2211 var act = function() {
2212 return view.do_show();
2214 self.form_last_update = self.form_last_update.pipe(act, act);
2215 return self.form_last_update;
2216 } else if (active_view === "graph") {
2217 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2221 set_value: function(value) {
2222 value = value || [];
2224 this.dataset.reset_ids([]);
2225 if(value.length >= 1 && value[0] instanceof Array) {
2227 _.each(value, function(command) {
2228 var obj = {values: command[2]};
2229 switch (command[0]) {
2230 case commands.CREATE:
2231 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2233 self.dataset.to_create.push(obj);
2234 self.dataset.cache.push(_.clone(obj));
2237 case commands.UPDATE:
2238 obj['id'] = command[1];
2239 self.dataset.to_write.push(obj);
2240 self.dataset.cache.push(_.clone(obj));
2243 case commands.DELETE:
2244 self.dataset.to_delete.push({id: command[1]});
2246 case commands.LINK_TO:
2247 ids.push(command[1]);
2249 case commands.DELETE_ALL:
2250 self.dataset.delete_all = true;
2255 this.dataset.set_ids(ids);
2256 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2258 this.dataset.delete_all = true;
2259 _.each(value, function(command) {
2260 var obj = {values: command};
2261 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2263 self.dataset.to_create.push(obj);
2264 self.dataset.cache.push(_.clone(obj));
2268 this.dataset.set_ids(ids);
2271 this.dataset.reset_ids(value);
2273 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2274 this.dataset.index = 0;
2276 self.is_setted.resolve();
2277 return self.reload_current_view();
2279 get_value: function() {
2283 this.save_any_view();
2284 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2285 val = val.concat(_.map(this.dataset.ids, function(id) {
2286 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2288 return commands.create(alter_order.values);
2290 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2292 return commands.update(alter_order.id, alter_order.values);
2294 return commands.link_to(id);
2296 return val.concat(_.map(
2297 this.dataset.to_delete, function(x) {
2298 return commands['delete'](x.id);}));
2300 save_any_view: function() {
2301 if (this.doing_on_change)
2303 return this.session.synchronized_mode(_.bind(function() {
2304 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2305 this.viewmanager.views[this.viewmanager.active_view] &&
2306 this.viewmanager.views[this.viewmanager.active_view].controller) {
2307 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2308 if (this.viewmanager.active_view === "form") {
2309 var res = $.when(view.do_save());
2310 if (!res.isResolved() && !res.isRejected()) {
2311 console.warn("Asynchronous get_value() is not supported in form view.");
2314 } else if (this.viewmanager.active_view === "list") {
2315 var res = $.when(view.ensure_saved());
2316 if (!res.isResolved() && !res.isRejected()) {
2317 console.warn("Asynchronous get_value() is not supported in list view.");
2325 is_valid: function() {
2327 return this._super();
2329 validate: function() {
2330 this.invalid = false;
2331 if (!this.viewmanager.views[this.viewmanager.active_view])
2333 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2334 if (this.viewmanager.active_view === "form") {
2335 for (var f in view.fields) {
2337 if (!f.is_valid()) {
2338 this.invalid = true;
2344 is_dirty: function() {
2345 this.save_any_view();
2346 return this._super();
2348 update_dom: function() {
2349 this._super.apply(this, arguments);
2351 if (this.previous_readonly !== this.readonly) {
2352 this.previous_readonly = this.readonly;
2353 if (this.viewmanager) {
2354 this.is_loaded = this.is_loaded.pipe(function() {
2355 self.viewmanager.stop();
2356 return $.when(self.load_views()).then(function() {
2357 self.reload_current_view();
2365 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2366 get_context: function() {
2367 this.context = this.o2m.build_context([this.o2m.name]);
2368 return this.context;
2372 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2373 _template: 'One2Many.listview',
2374 do_add_record: function () {
2375 if (this.options.editable) {
2376 this._super.apply(this, arguments);
2379 var pop = new openerp.web.form.SelectCreatePopup(this);
2380 pop.on_default_get.add(self.dataset.on_default_get);
2382 self.o2m.field.relation,
2384 title: _t("Create: ") + self.name,
2385 initial_view: "form",
2386 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2387 create_function: function(data, callback, error_callback) {
2388 return self.o2m.dataset.create(data).then(function(r) {
2389 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2390 self.o2m.dataset.on_change();
2391 }).then(callback, error_callback);
2393 read_function: function() {
2394 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2396 parent_view: self.o2m.view,
2397 child_name: self.o2m.name,
2398 form_view_options: {'not_interactible_on_create':true}
2400 self.o2m.build_domain(),
2401 self.o2m.build_context()
2403 pop.on_select_elements.add_last(function() {
2404 self.o2m.reload_current_view();
2408 do_activate_record: function(index, id) {
2410 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2411 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2412 title: _t("Open: ") + self.name,
2414 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2415 parent_view: self.o2m.view,
2416 child_name: self.o2m.name,
2417 read_function: function() {
2418 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2420 form_view_options: {'not_interactible_on_create':true},
2421 readonly: self.o2m.is_readonly()
2423 pop.on_write.add(function(id, data) {
2424 self.o2m.dataset.write(id, data, {}, function(r) {
2425 self.o2m.reload_current_view();
2429 do_button_action: function (name, id, callback) {
2431 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2432 return this._super(name, id, _.bind(def.resolve, def));
2436 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2437 form_template: 'One2Many.formview',
2438 on_loaded: function(data) {
2440 this.$form_header.find('button.oe_form_button_create').click(this.on_button_new);
2444 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2445 template: 'FieldMany2Many',
2446 multi_selection: false,
2447 init: function(view, node) {
2448 this._super(view, node);
2449 this.list_id = _.uniqueId("many2many");
2450 this.is_loaded = $.Deferred();
2451 this.initial_is_loaded = this.is_loaded;
2452 this.is_setted = $.Deferred();
2455 this._super.apply(this, arguments);
2459 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2460 this.dataset.m2m = this;
2461 this.dataset.on_unlink.add_last(function(ids) {
2462 self.on_ui_change();
2465 this.is_setted.then(function() {
2469 set_value: function(value) {
2470 value = value || [];
2471 if (value.length >= 1 && value[0] instanceof Array) {
2472 value = value[0][2];
2475 this.dataset.set_ids(value);
2477 self.reload_content();
2478 this.is_setted.resolve();
2480 get_value: function() {
2481 return [commands.replace_with(this.dataset.ids)];
2483 validate: function() {
2484 this.invalid = false;
2486 is_readonly: function() {
2487 return this.readonly || this.force_readonly;
2489 load_view: function() {
2491 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2492 'addable': self.is_readonly() ? null : _t("Add"),
2493 'deletable': self.is_readonly() ? false : true,
2494 'selectable': self.multi_selection,
2495 'isClarkGable': self.is_readonly() ? false : true
2497 var embedded = (this.field.views || {}).tree;
2499 this.list_view.set_embedded_view(embedded);
2501 this.list_view.m2m_field = this;
2502 var loaded = $.Deferred();
2503 this.list_view.on_loaded.add_last(function() {
2504 self.initial_is_loaded.resolve();
2507 $.async_when().then(function () {
2508 self.list_view.appendTo($("#" + self.list_id));
2512 reload_content: function() {
2514 this.is_loaded = this.is_loaded.pipe(function() {
2515 return self.list_view.reload_content();
2518 update_dom: function() {
2519 this._super.apply(this, arguments);
2521 if (this.previous_readonly !== this.readonly) {
2522 this.previous_readonly = this.readonly;
2523 if (this.list_view) {
2524 this.is_loaded = this.is_loaded.pipe(function() {
2525 self.list_view.stop();
2526 return $.when(self.load_view()).then(function() {
2527 self.reload_content();
2535 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2536 get_context: function() {
2537 this.context = this.m2m.build_context();
2538 return this.context;
2544 * @extends openerp.web.ListView
2546 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2547 do_add_record: function () {
2548 var pop = new openerp.web.form.SelectCreatePopup(this);
2552 title: _t("Add: ") + this.name
2554 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2555 this.m2m_field.build_context()
2558 pop.on_select_elements.add(function(element_ids) {
2559 _.each(element_ids, function(element_id) {
2560 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2561 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2562 self.m2m_field.on_ui_change();
2563 self.reload_content();
2568 do_activate_record: function(index, id) {
2570 var pop = new openerp.web.form.FormOpenPopup(this);
2571 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2572 title: _t("Open: ") + this.name,
2573 readonly: this.widget_parent.is_readonly()
2575 pop.on_write_completed.add_last(function() {
2576 self.reload_content();
2583 * @extends openerp.web.OldWidget
2585 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2586 identifier_prefix: "selectcreatepopup",
2587 template: "SelectCreatePopup",
2591 * - initial_view: form or search (default search)
2592 * - disable_multiple_selection
2593 * - alternative_form_view
2594 * - create_function (defaults to a naive saving behavior)
2597 * - form_view_options
2598 * - list_view_options
2601 select_element: function(model, options, domain, context) {
2604 this.domain = domain || [];
2605 this.context = context || {};
2606 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2607 return self.create_row.apply(self, arguments);
2608 }, read_function: null});
2609 this.initial_ids = this.options.initial_ids;
2610 this.created_elements = [];
2611 this.render_element();
2612 openerp.web.form.dialog(this.$element, {
2616 title: options.title || ""
2623 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2625 this.dataset.create_function = function() {
2626 return self.options.create_function.apply(null, arguments).then(function(r) {
2627 self.created_elements.push(r.result);
2630 this.dataset.write_function = function() {
2631 return self.write_row.apply(self, arguments);
2633 this.dataset.read_function = this.options.read_function;
2634 this.dataset.parent_view = this.options.parent_view;
2635 this.dataset.child_name = this.options.child_name;
2636 this.dataset.on_default_get.add(this.on_default_get);
2637 if (this.options.initial_view == "search") {
2638 self.rpc('/web/session/eval_domain_and_context', {
2640 contexts: [this.context]
2641 }, function (results) {
2642 var search_defaults = {};
2643 _.each(results.context, function (value, key) {
2644 var match = /^search_default_(.*)$/.exec(key);
2646 search_defaults[match[1]] = value;
2649 self.setup_search_view(search_defaults);
2655 setup_search_view: function(search_defaults) {
2657 if (this.searchview) {
2658 this.searchview.stop();
2660 this.searchview = new openerp.web.SearchView(this,
2661 this.dataset, false, search_defaults);
2662 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2663 if (self.initial_ids) {
2664 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2665 contexts, groupbys);
2666 self.initial_ids = undefined;
2668 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2671 this.searchview.on_loaded.add_last(function () {
2672 self.view_list = new openerp.web.form.SelectCreateListView(self,
2673 self.dataset, false,
2674 _.extend({'deletable': false,
2675 'selectable': !self.options.disable_multiple_selection
2676 }, self.options.list_view_options || {}));
2677 self.view_list.popup = self;
2678 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2679 self.view_list.do_show();
2680 }).pipe(function() {
2681 self.searchview.do_search();
2683 self.view_list.on_loaded.add_last(function() {
2684 var $buttons = self.view_list.$element.find(".oe-actions");
2685 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2686 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2687 $cbutton.click(function() {
2690 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2691 if(self.options.disable_multiple_selection) {
2694 $sbutton.click(function() {
2695 self.on_select_elements(self.selected_ids);
2700 this.searchview.appendTo($("#" + this.element_id + "_search"));
2702 do_search: function(domains, contexts, groupbys) {
2704 this.rpc('/web/session/eval_domain_and_context', {
2705 domains: domains || [],
2706 contexts: contexts || [],
2707 group_by_seq: groupbys || []
2708 }, function (results) {
2709 self.view_list.do_search(results.domain, results.context, results.group_by);
2712 create_row: function() {
2714 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2715 wdataset.parent_view = this.options.parent_view;
2716 wdataset.child_name = this.options.child_name;
2717 return wdataset.create.apply(wdataset, arguments);
2719 write_row: function() {
2721 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2722 wdataset.parent_view = this.options.parent_view;
2723 wdataset.child_name = this.options.child_name;
2724 return wdataset.write.apply(wdataset, arguments);
2726 on_select_elements: function(element_ids) {
2728 on_click_element: function(ids) {
2729 this.selected_ids = ids || [];
2730 if(this.selected_ids.length > 0) {
2731 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2733 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2736 new_object: function() {
2738 if (this.searchview) {
2739 this.searchview.hide();
2741 if (this.view_list) {
2742 this.view_list.$element.hide();
2744 this.dataset.index = null;
2745 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2746 if (this.options.alternative_form_view) {
2747 this.view_form.set_embedded_view(this.options.alternative_form_view);
2749 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2750 this.view_form.on_loaded.add_last(function() {
2751 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2752 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2753 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2754 $nbutton.click(function() {
2755 $.when(self.view_form.do_save()).then(function() {
2756 self.view_form.reload_lock.then(function() {
2757 self.view_form.on_button_new();
2761 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2762 $nbutton.click(function() {
2763 $.when(self.view_form.do_save()).then(function() {
2764 self.view_form.reload_lock.then(function() {
2769 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2770 $cbutton.click(function() {
2774 this.view_form.do_show();
2776 check_exit: function() {
2777 if (this.created_elements.length > 0) {
2778 this.on_select_elements(this.created_elements);
2782 on_default_get: function(res) {}
2785 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2786 do_add_record: function () {
2787 this.popup.new_object();
2789 select_record: function(index) {
2790 this.popup.on_select_elements([this.dataset.ids[index]]);
2793 do_select: function(ids, records) {
2794 this._super(ids, records);
2795 this.popup.on_click_element(ids);
2801 * @extends openerp.web.OldWidget
2803 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2804 identifier_prefix: "formopenpopup",
2805 template: "FormOpenPopup",
2808 * - alternative_form_view
2809 * - auto_write (default true)
2813 * - form_view_options
2816 show_element: function(model, row_id, context, options) {
2818 this.row_id = row_id;
2819 this.context = context || {};
2820 this.options = _.defaults(options || {}, {"auto_write": true});
2821 this.render_element();
2822 this.$element.dialog({
2823 title: options.title || '',
2832 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2833 this.dataset.fop = this;
2834 this.dataset.ids = [this.row_id];
2835 this.dataset.index = 0;
2836 this.dataset.parent_view = this.options.parent_view;
2837 this.dataset.child_name = this.options.child_name;
2838 this.setup_form_view();
2840 on_write: function(id, data) {
2841 if (!this.options.auto_write)
2844 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2845 wdataset.parent_view = this.options.parent_view;
2846 wdataset.child_name = this.options.child_name;
2847 wdataset.write(id, data, {}, function(r) {
2848 self.on_write_completed();
2851 on_write_completed: function() {},
2852 setup_form_view: function() {
2854 var FormClass = this.options.readonly
2855 ? openerp.web.views.get_object('page')
2856 : openerp.web.views.get_object('form');
2857 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2858 if (this.options.alternative_form_view) {
2859 this.view_form.set_embedded_view(this.options.alternative_form_view);
2861 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2862 this.view_form.on_loaded.add_last(function() {
2863 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2864 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2865 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2866 $nbutton.click(function() {
2867 self.view_form.do_save().then(function() {
2871 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2872 $cbutton.click(function() {
2875 if (self.options.readonly) {
2877 $cbutton.text(_t("Close"));
2879 self.view_form.do_show();
2881 this.dataset.on_write.add(this.on_write);
2885 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2886 read_ids: function() {
2887 if (this.fop.options.read_function) {
2888 return this.fop.options.read_function.apply(null, arguments);
2890 return this._super.apply(this, arguments);
2895 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2896 template: 'FieldReference',
2897 init: function(view, node) {
2898 this._super(view, node);
2899 this.fields_view = {
2902 selection: view.fields_view.fields[this.name].selection
2909 this.get_fields_values = view.get_fields_values;
2910 this.do_onchange = this.on_form_changed = this.on_nop;
2911 this.dataset = this.view.dataset;
2912 this.widgets_counter = 0;
2913 this.view_id = 'reference_' + _.uniqueId();
2916 this.fields_order = [];
2917 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2921 this.reference_ready = true;
2922 this.selection.on_value_changed.add_last(this.on_selection_changed);
2923 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2928 on_nop: function() {
2930 on_selection_changed: function() {
2931 if (this.reference_ready) {
2932 var sel = this.selection.get_value();
2933 this.m2o.field.relation = sel;
2934 this.m2o.set_value(null);
2935 this.m2o.$element.toggle(sel !== false);
2940 this.selection.start();
2943 is_valid: function() {
2944 return this.required === false || typeof(this.get_value()) === 'string';
2946 is_dirty: function() {
2947 return this.selection.is_dirty() || this.m2o.is_dirty();
2949 set_value: function(value) {
2951 this.reference_ready = false;
2952 var vals = [], sel_val, m2o_val;
2953 if (typeof(value) === 'string') {
2954 vals = value.split(',');
2956 sel_val = vals[0] || false;
2957 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2958 this.selection.set_value(sel_val);
2959 this.m2o.field.relation = sel_val;
2960 this.m2o.set_value(m2o_val);
2961 this.m2o.$element.toggle(sel_val !== false);
2962 this.reference_ready = true;
2964 get_value: function() {
2965 var model = this.selection.get_value(),
2966 id = this.m2o.get_value();
2967 if (typeof(model) === 'string' && typeof(id) === 'number') {
2968 return model + ',' + id;
2975 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2976 init: function(view, node) {
2977 this._super(view, node);
2978 this.iframe = this.element_id + '_iframe';
2979 this.binary_value = false;
2982 this._super.apply(this, arguments);
2983 this.$element.find('input.oe-binary-file').change(this.on_file_change);
2984 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2985 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2987 human_filesize : function(size) {
2988 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2990 while (size >= 1024) {
2994 return size.toFixed(2) + ' ' + units[i];
2996 on_file_change: function(e) {
2997 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2998 // http://www.html5rocks.com/tutorials/file/dndfiles/
2999 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3000 window[this.iframe] = this.on_file_uploaded;
3001 if ($(e.target).val() != '') {
3002 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3003 this.$element.find('form.oe-binary-form').submit();
3004 this.$element.find('.oe-binary-progress').show();
3005 this.$element.find('.oe-binary').hide();
3008 on_file_uploaded: function(size, name, content_type, file_base64) {
3009 delete(window[this.iframe]);
3010 if (size === false) {
3011 this.do_warn("File Upload", "There was a problem while uploading your file");
3012 // TODO: use openerp web crashmanager
3013 console.warn("Error while uploading file : ", name);
3015 this.on_file_uploaded_and_valid.apply(this, arguments);
3016 this.on_ui_change();
3018 this.$element.find('.oe-binary-progress').hide();
3019 this.$element.find('.oe-binary').show();
3021 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3023 on_save_as: function() {
3024 var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
3025 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
3026 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
3029 on_clear: function() {
3030 if (this.value !== false) {
3032 this.binary_value = false;
3033 this.on_ui_change();
3039 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3040 template: 'FieldBinaryFile',
3041 update_dom: function() {
3042 this._super.apply(this, arguments);
3043 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3044 this.$element.find('input[type=text]').prop('disabled', this.readonly);
3046 set_value: function(value) {
3047 this._super.apply(this, arguments);
3049 if (this.node.attrs.filename) {
3050 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3052 show_value = (value != null && value !== false) ? value : '';
3054 this.$element.find('input').eq(0).val(show_value);
3056 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3057 this.value = file_base64;
3058 this.binary_value = true;
3059 var show_value = name + " (" + this.human_filesize(size) + ")";
3060 this.$element.find('input').eq(0).val(show_value);
3061 this.set_filename(name);
3063 set_filename: function(value) {
3064 var filename = this.node.attrs.filename;
3065 if (this.view.fields[filename]) {
3066 this.view.fields[filename].set_value(value);
3067 this.view.fields[filename].on_ui_change();
3070 on_clear: function() {
3071 this._super.apply(this, arguments);
3072 this.$element.find('input').eq(0).val('');
3073 this.set_filename('');
3077 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3078 template: 'FieldBinaryImage',
3080 this._super.apply(this, arguments);
3081 this.$image = this.$element.find('img.oe-binary-image');
3083 update_dom: function() {
3084 this._super.apply(this, arguments);
3085 this.$element.find('.oe-binary').toggle(!this.readonly);
3087 set_value: function(value) {
3088 this._super.apply(this, arguments);
3089 this.set_image_maxwidth();
3090 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3091 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3092 this.$image.attr('src', url);
3094 set_image_maxwidth: function() {
3095 this.$image.css('max-width', this.$element.width());
3097 on_file_change: function() {
3098 this.set_image_maxwidth();
3099 this._super.apply(this, arguments);
3101 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3102 this.value = file_base64;
3103 this.binary_value = true;
3104 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3106 on_clear: function() {
3107 this._super.apply(this, arguments);
3108 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3112 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3113 template: "EmptyComponent",
3116 this.selected_value = null;
3120 set_value: function(value) {
3122 this.selected_value = value;
3126 render_list: function() {
3128 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3129 function(x) { return _.str.trim(x); });
3130 shown = _.select(shown, function(x) { return x.length > 0; });
3132 if (shown.length == 0) {
3133 this.to_show = this.field.selection;
3135 this.to_show = _.select(this.field.selection, function(x) {
3136 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3140 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3141 this.$element.html(content);
3143 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3144 var color = colors[this.selected_value];
3146 var elem = this.$element.find("li.oe-arrow-list-selected span");
3147 elem.css("border-color", color);
3148 if (this.check_white(color))
3149 elem.css("color", "white");
3150 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3151 elem.css("border-left-color", "rgba(0,0,0,0)");
3152 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3153 elem.css("border-color", "rgba(0,0,0,0)");
3154 elem.css("border-left-color", color);
3157 check_white: function(color) {
3158 var div = $("<div></div>");
3159 div.css("display", "none");
3160 div.css("color", color);
3161 div.appendTo($("body"));
3162 var ncolor = div.css("color");
3164 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3168 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3169 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3177 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3178 render: function () {
3179 var $root = $('<div class="oe_form_html_view">');
3180 this.render_children(this, $root);
3181 return $root.html();
3183 render_children: function (object, $into) {
3185 fields = this.view.fields_view.fields;
3186 _(object.children).each(function (child) {
3187 if (typeof child === 'string') {
3189 } else if (child.tag === 'field') {
3191 new (self.view.registry.get_object('frame'))(
3192 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3195 var $child = $(document.createElement(child.tag))
3198 self.render_children(child, $child);
3206 * Registry of form widgets, called by :js:`openerp.web.FormView`
3208 openerp.web.form.widgets = new openerp.web.Registry({
3209 'frame' : 'openerp.web.form.WidgetFrame',
3210 'group' : 'openerp.web.form.WidgetGroup',
3211 'notebook' : 'openerp.web.form.WidgetNotebook',
3212 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3213 'separator' : 'openerp.web.form.WidgetSeparator',
3214 'label' : 'openerp.web.form.WidgetLabel',
3215 'button' : 'openerp.web.form.WidgetButton',
3216 'char' : 'openerp.web.form.FieldChar',
3217 'email' : 'openerp.web.form.FieldEmail',
3218 'url' : 'openerp.web.form.FieldUrl',
3219 'text' : 'openerp.web.form.FieldText',
3220 'text_wiki' : 'openerp.web.form.FieldText',
3221 'date' : 'openerp.web.form.FieldDate',
3222 'datetime' : 'openerp.web.form.FieldDatetime',
3223 'selection' : 'openerp.web.form.FieldSelection',
3224 'many2one' : 'openerp.web.form.FieldMany2One',
3225 'many2many' : 'openerp.web.form.FieldMany2Many',
3226 'one2many' : 'openerp.web.form.FieldOne2Many',
3227 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3228 'reference' : 'openerp.web.form.FieldReference',
3229 'boolean' : 'openerp.web.form.FieldBoolean',
3230 'float' : 'openerp.web.form.FieldFloat',
3231 'integer': 'openerp.web.form.FieldFloat',
3232 'float_time': 'openerp.web.form.FieldFloat',
3233 'progressbar': 'openerp.web.form.FieldProgressBar',
3234 'image': 'openerp.web.form.FieldBinaryImage',
3235 'binary': 'openerp.web.form.FieldBinaryFile',
3236 'statusbar': 'openerp.web.form.FieldStatus',
3237 'html': 'openerp.web.form.WidgetHtml'
3243 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: