1 openerp.web.form = function (openerp) {
3 var _t = openerp.web._t;
4 var QWeb = openerp.web.qweb;
6 openerp.web.views.add('form', 'openerp.web.FormView');
7 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
9 * Indicates that this view is not searchable, and thus that no search
10 * view should be displayed (if there is one active).
14 form_template: "FormView",
15 identifier_prefix: 'formview-',
17 * @constructs openerp.web.FormView
18 * @extends openerp.web.View
20 * @param {openerp.web.Session} session the current openerp session
21 * @param {openerp.web.DataSet} dataset the dataset this view will work with
22 * @param {String} view_id the identifier of the OpenERP view object
24 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
26 init: function(parent, dataset, view_id, options) {
28 this.set_default_options(options);
29 this.dataset = dataset;
30 this.model = dataset.model;
31 this.view_id = view_id || false;
32 this.fields_view = {};
34 this.widgets_counter = 0;
37 this.show_invalid = true;
38 this.default_focus_field = null;
39 this.default_focus_button = null;
40 this.registry = this.readonly ? openerp.web.form.readonly : openerp.web.form.widgets;
41 this.has_been_loaded = $.Deferred();
42 this.$form_header = null;
43 this.translatable_fields = [];
44 _.defaults(this.options, {"always_show_new_button": true,
45 "not_interactible_on_create": false});
46 this.mutating_lock = $.Deferred();
47 this.initial_mutating_lock = this.mutating_lock;
48 this.on_change_lock = $.Deferred().resolve();
49 this.reload_lock = $.Deferred().resolve();
53 return this.init_view();
55 init_view: function() {
56 if (this.embedded_view) {
57 var def = $.Deferred().then(this.on_loaded);
59 setTimeout(function() {def.resolve(self.embedded_view);}, 0);
62 var context = new openerp.web.CompoundContext(this.dataset.get_context());
63 return this.rpc("/web/view/load", {
65 "view_id": this.view_id,
67 toolbar: this.options.sidebar,
74 this.sidebar.attachments.stop();
77 _.each(this.widgets, function(w) {
82 reposition: function ($e) {
86 on_loaded: function(data) {
89 this.fields_view = data;
90 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
92 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
94 this.$element.html(this.rendered);
95 _.each(this.widgets, function(w) {
98 this.$form_header = this.$element.find('.oe_form_header:first');
99 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
100 var action = $(this).data('pager-action');
101 self.on_pager_action(action);
104 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
105 this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
106 this.$form_header.find('button.oe_form_button_duplicate').click(this.on_button_duplicate);
107 this.$form_header.find('button.oe_form_button_delete').click(this.on_button_delete);
108 this.$form_header.find('button.oe_form_button_toggle').click(this.on_toggle_readonly);
110 if (this.options.sidebar && this.options.sidebar_id) {
111 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
112 this.sidebar.start();
113 this.sidebar.do_unfold();
114 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
115 this.sidebar.add_toolbar(this.fields_view.toolbar);
116 this.set_common_sidebar_sections(this.sidebar);
118 this.has_been_loaded.resolve();
120 on_toggle_readonly: function() {
122 self.translatable_fields = [];
125 self.$form_header.find('button').unbind('click');
126 self.readonly = !self.readonly;
127 self.registry = self.readonly ? openerp.web.form.readonly : openerp.web.form.widgets;
128 self.on_loaded(self.fields_view);
129 return self.reload();
131 do_set_readonly: function() {
132 return this.readonly ? $.Deferred().resolve() : this.on_toggle_readonly();
134 do_set_editable: function() {
135 return !this.readonly ? $.Deferred().resolve() : this.on_toggle_readonly();
137 do_show: function () {
139 if (this.dataset.index === null) {
140 // null index means we should start a new record
141 promise = this.on_button_new();
143 promise = this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_record_loaded);
145 this.$element.show();
147 this.sidebar.$element.show();
151 do_hide: function () {
152 this.$element.hide();
154 this.sidebar.$element.hide();
157 on_record_loaded: function(record) {
159 deferred_stack = $.Deferred.queue();
161 throw("Form: No record received");
164 this.$form_header.find('.oe_form_on_create').show();
165 this.$form_header.find('.oe_form_on_update').hide();
166 if (!this.options["always_show_new_button"]) {
167 this.$form_header.find('button.oe_form_button_new').hide();
170 this.$form_header.find('.oe_form_on_create').hide();
171 this.$form_header.find('.oe_form_on_update').show();
172 this.$form_header.find('button.oe_form_button_new').show();
174 this.$form_header.find('.oe_form_on_readonly').toggle(this.readonly);
175 this.$form_header.find('.oe_form_on_editable').toggle(!this.readonly);
176 this.datarecord = record;
178 _(this.fields).each(function (field, f) {
180 var result = field.set_value(self.datarecord[f] || false);
181 if (result && _.isFunction(result.promise)) {
182 deferred_stack.push(result);
184 $.when(result).then(function() {
188 deferred_stack.push('force resolution if no fields');
189 return deferred_stack.then(function() {
191 // New record: Second pass in order to trigger the onchanges
192 self.show_invalid = false;
193 for (var f in record) {
194 var field = self.fields[f];
197 self.do_onchange(field);
201 self.on_form_changed();
202 self.initial_mutating_lock.resolve();
203 self.show_invalid = true;
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();
213 on_form_changed: function() {
214 for (var w in this.widgets) {
216 w.process_modifiers();
220 on_pager_action: function(action) {
221 if (this.can_be_discarded()) {
224 this.dataset.index = 0;
227 this.dataset.previous();
233 this.dataset.index = this.dataset.ids.length - 1;
239 do_update_pager: function(hide_index) {
240 var $pager = this.$form_header.find('div.oe_form_pager');
241 var index = hide_index ? '-' : this.dataset.index + 1;
242 $pager.find('span.oe_pager_index').html(index);
243 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
245 parse_on_change: function (on_change, widget) {
247 var onchange = _.str.trim(on_change);
248 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
253 var method = call[1];
254 if (!_.str.trim(call[2])) {
255 return {method: method, args: [], context_index: null}
258 var argument_replacement = {
259 'False': function () {return false;},
260 'True': function () {return true;},
261 'None': function () {return null;},
262 'context': function (i) {
264 var ctx = widget.build_context ? widget.build_context() : {};
268 var parent_fields = null, context_index = null;
269 var args = _.map(call[2].split(','), function (a, i) {
270 var field = _.str.trim(a);
272 // literal constant or context
273 if (field in argument_replacement) {
274 return argument_replacement[field](i);
277 if (self.fields[field]) {
278 var value = self.fields[field].get_on_change_value();
279 return value == null ? false : value;
282 var splitted = field.split('.');
283 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
284 if (parent_fields === null) {
285 parent_fields = self.dataset.parent_view.get_fields_values();
287 var p_val = parent_fields[_.str.trim(splitted[1])];
288 if (p_val !== undefined) {
289 return p_val == null ? false : p_val;
293 var first_char = field[0], last_char = field[field.length-1];
294 if ((first_char === '"' && last_char === '"')
295 || (first_char === "'" && last_char === "'")) {
296 return field.slice(1, -1);
299 throw new Error("Could not get field with name '" + field +
300 "' for onchange '" + onchange + "'");
306 context_index: context_index
309 do_onchange: function(widget, processed) {
311 var act = function() {
313 processed = processed || [];
314 var on_change = widget.node.attrs.on_change;
316 var change_spec = self.parse_on_change(on_change, widget);
319 url: '/web/dataset/call',
322 return self.rpc(ajax, {
323 model: self.dataset.model,
324 method: change_spec.method,
325 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
326 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
327 }).pipe(function(response) {
328 return self.on_processed_onchange(response, processed);
331 console.warn("Wrong on_change format", on_change);
336 return $.Deferred().reject();
339 this.on_change_lock = this.on_change_lock.pipe(act, act);
340 return this.on_change_lock;
342 on_processed_onchange: function(response, processed) {
344 var result = response;
346 for (var f in result.value) {
347 var field = this.fields[f];
348 // If field is not defined in the view, just ignore it
350 var value = result.value[f];
351 processed.push(field.name);
352 if (field.get_value() != value) {
353 field.set_value(value);
355 if (_.indexOf(processed, field.name) < 0) {
356 this.do_onchange(field, processed);
361 this.on_form_changed();
363 if (!_.isEmpty(result.warning)) {
364 $(QWeb.render("DialogWarning", result.warning)).dialog({
368 $(this).dialog("close");
376 return $.Deferred().resolve();
379 return $.Deferred().reject();
382 on_button_save: function() {
383 return this.do_save().then(this.do_set_readonly);
385 on_button_new: function() {
387 var def = $.Deferred();
388 $.when(this.has_been_loaded).then(function() {
389 if (self.can_be_discarded()) {
390 var keys = _.keys(self.fields_view.fields);
391 $.when(self.do_set_editable()).then(function() {
393 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
397 self.on_record_loaded({}).then(function() {
404 return def.promise();
406 on_button_duplicate: function() {
408 var def = $.Deferred();
409 $.when(this.has_been_loaded).then(function() {
410 if (self.can_be_discarded()) {
411 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
412 return self.on_created({ result : new_id });
413 }).then(self.do_set_editable).then(function() {
418 return def.promise();
420 on_button_delete: function() {
422 var def = $.Deferred();
423 $.when(this.has_been_loaded).then(function() {
424 if (self.can_be_discarded() && self.datarecord.id) {
425 if (confirm(_t("Do you really want to delete this record?"))) {
426 self.dataset.unlink([self.datarecord.id]).then(function() {
427 self.on_pager_action('next');
431 setTimeout(function () {
437 return def.promise();
439 can_be_discarded: function() {
440 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
443 * Triggers saving the form's record. Chooses between creating a new
444 * record or saving an existing one depending on whether the record
445 * already has an id property.
447 * @param {Function} success callback on save success
448 * @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)
450 do_save: function(success, prepend_on_create) {
452 var action = function() {
454 if (!self.initial_mutating_lock.isResolved() && !self.initial_mutating_lock.isRejected())
456 var form_invalid = false,
458 first_invalid_field = null;
459 for (var f in self.fields) {
464 if (!first_invalid_field) {
465 first_invalid_field = f;
467 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
468 // Special case 'id' field, do not save this field
469 // on 'create' : save all non readonly fields
470 // on 'edit' : save non readonly modified fields
471 values[f.name] = f.get_value();
475 first_invalid_field.focus();
477 return $.Deferred().reject();
479 if (!self.datarecord.id) {
480 openerp.log("FormView(", self, ") : About to create", values);
481 return self.dataset.create(values).pipe(function(r) {
482 return self.on_created(r, undefined, prepend_on_create);
484 } else if (_.isEmpty(values)) {
485 openerp.log("FormView(", self, ") : Nothing to save");
490 openerp.log("FormView(", self, ") : About to save", values);
491 return self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
492 return self.on_saved(r);
498 return $.Deferred().reject();
501 this.mutating_lock = this.mutating_lock.pipe(action, action);
502 return this.mutating_lock;
504 on_invalid: function() {
506 _.each(this.fields, function(f) {
508 msg += "<li>" + f.string + "</li>";
512 this.do_warn("The following fields are invalid :", msg);
514 on_saved: function(r, success) {
516 // should not happen in the server, but may happen for internal purpose
517 return $.Deferred().reject();
519 return $.when(this.reload()).pipe(function () {
520 return $.when(r).then(success); }, null);
524 * Updates the form' dataset to contain the new record:
526 * * Adds the newly created record to the current dataset (at the end by
528 * * Selects that record (sets the dataset's index to point to the new
530 * * Updates the pager and sidebar displays
533 * @param {Function} success callback to execute after having updated the dataset
534 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
536 on_created: function(r, success, prepend_on_create) {
538 // should not happen in the server, but may happen for internal purpose
539 return $.Deferred().reject();
541 this.datarecord.id = r.result;
542 if (!prepend_on_create) {
543 this.dataset.ids.push(this.datarecord.id);
544 this.dataset.index = this.dataset.ids.length - 1;
546 this.dataset.ids.unshift(this.datarecord.id);
547 this.dataset.index = 0;
549 this.do_update_pager();
551 this.sidebar.attachments.do_update();
553 openerp.log("The record has been created with id #" + this.datarecord.id);
555 return $.when(_.extend(r, {created: true})).then(success);
558 on_action: function (action) {
559 console.debug('Executing action', action);
563 var act = function() {
564 if (self.dataset.index == null || self.dataset.index < 0) {
565 return $.when(self.on_button_new());
567 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
570 this.reload_lock = this.reload_lock.pipe(act, act);
571 return this.reload_lock;
573 get_fields_values: function() {
575 _.each(this.fields, function(value, key) {
576 var val = value.get_value();
581 get_selected_ids: function() {
582 var id = this.dataset.ids[this.dataset.index];
583 return id ? [id] : [];
585 recursive_save: function() {
587 return $.when(this.do_save()).pipe(function(res) {
588 if (self.dataset.parent_view)
589 return self.dataset.parent_view.recursive_save();
592 is_dirty: function() {
593 return _.any(this.fields, function (value) {
594 return value.is_dirty();
597 is_interactible_record: function() {
598 var id = this.datarecord.id;
600 if (this.options.not_interactible_on_create)
602 } else if (typeof(id) === "string") {
603 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
608 sidebar_context: function () {
609 return this.do_save().pipe($.proxy(this, 'get_fields_values'));
612 openerp.web.FormDialog = openerp.web.Dialog.extend({
613 init: function(parent, options, view_id, dataset) {
614 this._super(parent, options);
615 this.dataset = dataset;
616 this.view_id = view_id;
621 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
625 this.form.appendTo(this.$element);
626 this.form.on_created.add_last(this.on_form_dialog_saved);
627 this.form.on_saved.add_last(this.on_form_dialog_saved);
630 select_id: function(id) {
631 if (this.form.dataset.select_id(id)) {
632 return this.form.do_show();
634 this.do_warn("Could not find id in dataset");
635 return $.Deferred().reject();
638 on_form_dialog_saved: function(r) {
644 openerp.web.form = {};
646 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
647 init: function(parent, form_view) {
648 var $section = parent.add_section(_t('Attachments'), 'attachments');
649 this.$div = $('<div class="oe-sidebar-attachments"></div>');
650 $section.append(this.$div);
652 this._super(parent, $section.attr('id'));
653 this.view = form_view;
655 do_update: function() {
656 if (!this.view.datarecord.id) {
657 this.on_attachments_loaded([]);
659 (new openerp.web.DataSetSearch(
660 this, 'ir.attachment', this.view.dataset.get_context(),
662 ['res_model', '=', this.view.dataset.model],
663 ['res_id', '=', this.view.datarecord.id],
664 ['type', 'in', ['binary', 'url']]
665 ])).read_slice(['name', 'url', 'type'], {}, this.on_attachments_loaded);
668 on_attachments_loaded: function(attachments) {
669 this.attachments = attachments;
670 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
671 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
672 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
674 on_attachment_changed: function(e) {
675 window[this.element_id + '_iframe'] = this.do_update;
676 var $e = $(e.target);
677 if ($e.val() != '') {
678 this.$element.find('form.oe-binary-form').submit();
679 $e.parent().find('input[type=file]').attr('disabled', 'true');
680 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
683 on_attachment_delete: function(e) {
684 var self = this, $e = $(e.currentTarget);
685 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
686 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
687 this.rpc('/web/dataset/unlink', {
688 model: 'ir.attachment',
689 ids: [parseInt($e.attr('data-id'))]
691 $e.parent().remove();
692 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
698 openerp.web.form.compute_domain = function(expr, fields) {
700 for (var i = expr.length - 1; i >= 0; i--) {
702 if (ex.length == 1) {
703 var top = stack.pop();
706 stack.push(stack.pop() || top);
709 stack.push(stack.pop() && top);
715 throw new Error('Unknown domain operator ' + ex);
719 var field = fields[ex[0]];
721 throw new Error("Domain references unknown field : " + ex[0]);
723 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
727 switch (op.toLowerCase()) {
730 stack.push(field_value == val);
734 stack.push(field_value != val);
737 stack.push(field_value < val);
740 stack.push(field_value > val);
743 stack.push(field_value <= val);
746 stack.push(field_value >= val);
749 stack.push(_(val).contains(field_value));
752 stack.push(!_(val).contains(field_value));
755 console.warn("Unsupported operator in modifiers :", op);
758 return _.all(stack, _.identity);
761 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
763 identifier_prefix: 'formview-widget-',
765 * @constructs openerp.web.form.Widget
766 * @extends openerp.web.Widget
771 init: function(view, node) {
774 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
775 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
776 this.type = this.type || node.tag;
777 this.element_name = this.element_name || this.type;
778 this.element_class = [
779 'formview', this.view.view_id, this.element_name,
780 this.view.widgets_counter++].join("_");
784 this.view.widgets[this.element_class] = this;
785 this.children = node.children;
786 this.colspan = parseInt(node.attrs.colspan || 1, 10);
787 this.decrease_max_width = 0;
789 this.string = this.string || node.attrs.string;
790 this.help = this.help || node.attrs.help;
791 this.invisible = this.modifiers['invisible'] === true;
792 this.classname = 'oe_form_' + this.type;
794 this.align = parseFloat(this.node.attrs.align);
795 if (isNaN(this.align) || this.align === 1) {
796 this.align = 'right';
797 } else if (this.align === 0) {
800 this.align = 'center';
804 this.width = this.node.attrs.width;
807 this.$element = this.view.$element.find(
808 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
810 process_modifiers: function() {
811 var compute_domain = openerp.web.form.compute_domain;
812 for (var a in this.modifiers) {
813 this[a] = compute_domain(this.modifiers[a], this.view.fields);
816 update_dom: function() {
817 this.$element.toggle(!this.invisible);
820 var template = this.template;
821 return QWeb.render(template, { "widget": this });
823 do_attach_tooltip: function(widget, trigger, options) {
824 widget = widget || this;
825 trigger = trigger || this.$element;
828 maxWidth: openerp.connection.debug ? '300px' : '200px',
829 content: function() {
830 var template = widget.template + '.tooltip';
831 if (!QWeb.has_template(template)) {
832 template = 'WidgetLabel.tooltip';
834 return QWeb.render(template, {
835 debug: openerp.connection.debug,
840 trigger.tipTip(options);
842 _build_view_fields_values: function() {
843 var a_dataset = this.view.dataset;
844 var fields_values = this.view.get_fields_values();
845 var active_id = a_dataset.ids[a_dataset.index];
846 _.extend(fields_values, {
847 active_id: active_id || false,
848 active_ids: active_id ? [active_id] : [],
849 active_model: a_dataset.model,
850 parent: a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {}
852 return fields_values;
854 _build_eval_context: function() {
855 var a_dataset = this.view.dataset;
856 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values());
859 * Builds a new context usable for operations related to fields by merging
860 * the fields'context with the action's context.
862 build_context: function() {
863 var f_context = (this.field || {}).context || {};
864 if (!!f_context.__ref) {
865 var fields_values = this._build_eval_context();
866 f_context = new openerp.web.CompoundDomain(f_context).set_eval_context(fields_values);
868 // maybe the default_get should only be used when we do a default_get?
869 var v_contexts = _.compact([this.node.attrs.default_get || null,
870 this.node.attrs.context || null]);
871 var v_context = new openerp.web.CompoundContext();
872 _.each(v_contexts, function(x) {v_context.add(x);});
873 if (_.detect(v_contexts, function(x) {return !!x.__ref;})) {
874 var fields_values = this._build_eval_context();
875 v_context.set_eval_context(fields_values);
877 // if there is a context on the node, overrides the model's context
878 var ctx = v_contexts.length > 0 ? v_context : f_context;
881 build_domain: function() {
882 var f_domain = this.field.domain || [];
883 var n_domain = this.node.attrs.domain || null;
884 // if there is a domain on the node, overrides the model's domain
885 var final_domain = n_domain !== null ? n_domain : f_domain;
886 if (!(final_domain instanceof Array)) {
887 var fields_values = this._build_eval_context();
888 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
894 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
895 template: 'WidgetFrame',
896 init: function(view, node) {
897 this._super(view, node);
898 this.columns = parseInt(node.attrs.col || 4, 10);
903 for (var i = 0; i < node.children.length; i++) {
904 var n = node.children[i];
905 if (n.tag == "newline") {
911 this.set_row_cells_with(this.table[this.table.length - 1]);
914 if (this.table.length) {
915 this.set_row_cells_with(this.table[this.table.length - 1]);
918 this.table.push(row);
923 set_row_cells_with: function(row) {
926 row_length = row.length;
927 for (var i = 0; i < row.length; i++) {
928 if (row[i].always_invisible) {
931 bypass += row[i].width === undefined ? 0 : 1;
932 max_width -= row[i].decrease_max_width;
935 var size_unit = Math.round(max_width / (this.columns - bypass)),
937 for (var i = 0; i < row.length; i++) {
939 if (w.always_invisible) {
942 colspan_sum += w.colspan;
943 if (w.width === undefined) {
944 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
946 w.width = width + '%';
950 handle_node: function(node) {
952 if (node.tag == 'field') {
953 type = this.view.fields_view.fields[node.attrs.name] || {};
954 if (node.attrs.widget == 'statusbar') {
955 // This way we can retain backward compatibility between addons and old clients
956 node.attrs.nolabel = '1';
959 var widget = new (this.view.registry.get_any(
960 [node.attrs.widget, type.type, node.tag])) (this.view, node);
961 if (node.tag == 'field') {
962 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
963 this.view.default_focus_field = widget;
965 if (node.attrs.nolabel != '1') {
966 var label = new (this.view.registry.get_object('label')) (this.view, node);
967 label["for"] = widget;
968 this.add_widget(label, widget.colspan + 1);
971 this.add_widget(widget);
973 add_widget: function(widget, colspan) {
974 var current_row = this.table[this.table.length - 1];
975 if (!widget.always_invisible) {
976 colspan = colspan || widget.colspan;
977 if (current_row.length && (this.x + colspan) > this.columns) {
978 current_row = this.add_row();
980 this.x += widget.colspan;
982 current_row.push(widget);
987 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
988 template: 'WidgetGroup',
991 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
992 template: 'WidgetNotebook',
993 init: function(view, node) {
994 this._super(view, node);
996 for (var i = 0; i < node.children.length; i++) {
997 var n = node.children[i];
998 if (n.tag == "page") {
999 var page = new (this.view.registry.get_object('notebookpage'))(
1000 this.view, n, this, this.pages.length);
1001 this.pages.push(page);
1007 this._super.apply(this, arguments);
1008 this.$element.find('> ul > li').each(function (index, tab_li) {
1009 var page = self.pages[index],
1010 id = _.uniqueId(self.element_name + '-');
1011 page.element_id = id;
1012 $(tab_li).find('a').attr('href', '#' + id);
1014 this.$element.find('> div').each(function (index, page) {
1015 page.id = self.pages[index].element_id;
1017 this.$element.tabs();
1018 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1019 if (openerp.connection.debug) {
1020 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1021 defaultPosition: 'top'
1025 do_select_first_visible_tab: function() {
1026 for (var i = 0; i < this.pages.length; i++) {
1027 var page = this.pages[i];
1028 if (page.invisible === false) {
1029 this.$element.tabs('select', page.index);
1036 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1037 template: 'WidgetNotebookPage',
1038 init: function(view, node, notebook, index) {
1039 this.notebook = notebook;
1041 this.element_name = 'page_' + index;
1042 this._super(view, node);
1045 this._super.apply(this, arguments);
1046 this.$element_tab = this.notebook.$element.find(
1047 '> ul > li:eq(' + this.index + ')');
1049 update_dom: function() {
1050 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1051 this.notebook.do_select_first_visible_tab();
1053 this.$element_tab.toggle(!this.invisible);
1054 this.$element.toggle(!this.invisible);
1058 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1059 template: 'WidgetSeparator',
1060 init: function(view, node) {
1061 this._super(view, node);
1062 this.orientation = node.attrs.orientation || 'horizontal';
1063 if (this.orientation === 'vertical') {
1066 this.classname += '_' + this.orientation;
1070 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1071 template: 'WidgetButton',
1072 init: function(view, node) {
1073 this._super(view, node);
1074 this.force_disabled = false;
1076 // We don't have button key bindings in the webclient
1077 this.string = this.string.replace(/_/g, '');
1079 if (node.attrs.default_focus == '1') {
1080 // TODO fme: provide enter key binding to widgets
1081 this.view.default_focus_button = this;
1085 this._super.apply(this, arguments);
1086 this.$element.find("button").click(this.on_click);
1087 if (this.help || openerp.connection.debug) {
1088 this.do_attach_tooltip();
1091 on_click: function() {
1093 this.force_disabled = true;
1094 this.check_disable();
1095 this.execute_action().always(function() {
1096 self.force_disabled = false;
1097 self.check_disable();
1100 execute_action: function() {
1102 var exec_action = function() {
1103 if (self.node.attrs.confirm) {
1104 var def = $.Deferred();
1105 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1110 self.on_confirmed().then(function() {
1113 $(this).dialog("close");
1115 Cancel: function() {
1117 $(this).dialog("close");
1121 return def.promise();
1123 return self.on_confirmed();
1126 if (!this.node.attrs.special) {
1127 return this.view.recursive_save().pipe(exec_action);
1129 return exec_action();
1132 on_confirmed: function() {
1135 var context = this.node.attrs.context;
1136 if (context && context.__ref) {
1137 context = new openerp.web.CompoundContext(context);
1138 context.set_eval_context(this._build_eval_context());
1141 return this.view.do_execute_action(
1142 _.extend({}, this.node.attrs, {context: context}),
1143 this.view.dataset, this.view.datarecord.id, function () {
1147 update_dom: function() {
1149 this.check_disable();
1151 check_disable: function() {
1152 if (this.readonly || this.force_disabled || !this.view.is_interactible_record()) {
1153 this.$element.find("button").attr("disabled", "disabled");
1154 this.$element.find("button").css("color", "grey");
1156 this.$element.find("button").removeAttr("disabled");
1157 this.$element.find("button").css("color", "");
1162 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1163 template: 'WidgetLabel',
1164 init: function(view, node) {
1165 this.element_name = 'label_' + node.attrs.name;
1167 this._super(view, node);
1169 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1170 this.template = "WidgetParagraph";
1171 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1175 this.decrease_max_width = 1;
1179 render: function () {
1180 if (this['for'] && this.type !== 'label') {
1181 return QWeb.render(this.template, {widget: this['for']});
1183 // Actual label widgets should not have a false and have type label
1184 return QWeb.render(this.template, {widget: this});
1189 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1190 this.do_attach_tooltip(self['for']);
1192 this.$element.find("label").dblclick(function() {
1193 var widget = self['for'] || self;
1194 openerp.log(widget.element_class , widget);
1200 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1202 * @constructs openerp.web.form.Field
1203 * @extends openerp.web.form.Widget
1208 init: function(view, node) {
1209 this.name = node.attrs.name;
1210 this.value = undefined;
1211 view.fields[this.name] = this;
1212 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1213 this.element_name = "field_" + this.name + "_" + this.type;
1215 this._super(view, node);
1217 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1220 this.field = view.fields_view.fields[node.attrs.name] || {};
1221 this.string = node.attrs.string || this.field.string;
1222 this.help = node.attrs.help || this.field.help;
1223 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1224 this.readonly = this.modifiers['readonly'] === true;
1225 this.required = this.modifiers['required'] === true;
1226 this.invalid = this.dirty = false;
1228 this.classname = 'oe_form_field_' + this.type;
1231 this._super.apply(this, arguments);
1232 if (this.field.translate) {
1233 this.view.translatable_fields.push(this);
1234 this.$element.find('.oe_field_translate').click(this.on_translate);
1236 if (this.nolabel && openerp.connection.debug) {
1237 this.do_attach_tooltip(this, this.$element, {
1238 defaultPosition: 'top'
1242 set_value: function(value) {
1244 this.invalid = false;
1246 this.on_value_changed();
1248 set_value_from_ui: function() {
1249 this.on_value_changed();
1251 on_value_changed: function() {
1253 on_translate: function() {
1254 this.view.open_translate_dialog(this);
1256 get_value: function() {
1259 is_valid: function() {
1260 return !this.invalid;
1262 is_dirty: function() {
1263 return this.dirty && !this.readonly;
1265 get_on_change_value: function() {
1266 return this.get_value();
1268 update_dom: function() {
1269 this._super.apply(this, arguments);
1270 if (this.field.translate) {
1271 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1273 if (!this.disable_utility_classes) {
1274 this.$element.toggleClass('disabled', this.readonly);
1275 this.$element.toggleClass('required', this.required);
1276 if (this.view.show_invalid) {
1277 this.$element.toggleClass('invalid', !this.is_valid());
1281 on_ui_change: function() {
1284 if (this.is_valid()) {
1285 this.set_value_from_ui();
1286 this.view.do_onchange(this);
1287 this.view.on_form_changed();
1292 validate: function() {
1293 this.invalid = false;
1302 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1303 template: 'FieldChar',
1304 init: function (view, node) {
1305 this._super(view, node);
1306 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1309 this._super.apply(this, arguments);
1310 this.$element.find('input').change(this.on_ui_change);
1312 set_value: function(value) {
1313 this._super.apply(this, arguments);
1314 var show_value = openerp.web.format_value(value, this, '');
1315 this.$element.find('input').val(show_value);
1318 update_dom: function() {
1319 this._super.apply(this, arguments);
1320 this.$element.find('input').attr('disabled', this.readonly);
1322 set_value_from_ui: function() {
1323 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1326 validate: function() {
1327 this.invalid = false;
1329 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1330 this.invalid = this.required && value === '';
1332 this.invalid = true;
1336 this.$element.find('input').focus();
1340 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1341 template: 'FieldEmail',
1343 this._super.apply(this, arguments);
1344 this.$element.find('button').click(this.on_button_clicked);
1346 on_button_clicked: function() {
1347 if (!this.value || !this.is_valid()) {
1348 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1350 location.href = 'mailto:' + this.value;
1355 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1356 template: 'FieldUrl',
1358 this._super.apply(this, arguments);
1359 this.$element.find('button').click(this.on_button_clicked);
1361 on_button_clicked: function() {
1363 this.do_warn("Resource error", "This resource is empty");
1365 window.open(this.value);
1370 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1371 init: function (view, node) {
1372 this._super(view, node);
1373 if (node.attrs.digits) {
1374 this.parse_digits(node.attrs.digits);
1376 this.digits = view.fields_view.fields[node.attrs.name].digits;
1379 parse_digits: function (digits_attr) {
1380 // could use a Python parser instead.
1381 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1382 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1384 set_value: function(value) {
1385 if (value === false || value === undefined) {
1386 // As in GTK client, floats default to 0
1389 this._super.apply(this, [value]);
1393 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1394 template: "web.datetimepicker",
1395 jqueryui_object: 'datetimepicker',
1396 type_of_date: "datetime",
1397 init: function(parent) {
1398 this._super(parent);
1399 this.name = parent.name;
1403 this.$input = this.$element.find('input.oe_datepicker_master');
1404 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1405 this.$input.change(this.on_change);
1407 onSelect: this.on_picker_select,
1411 showButtonPanel: true
1413 this.$element.find('img.oe_datepicker_trigger').click(function() {
1414 if (!self.readonly) {
1415 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1416 self.$input_picker.show();
1417 self.picker('show');
1418 self.$input_picker.hide();
1421 this.set_readonly(false);
1424 picker: function() {
1425 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1427 on_picker_select: function(text, instance) {
1428 var date = this.picker('getDate');
1429 this.$input.val(date ? this.format_client(date) : '').change();
1431 set_value: function(value) {
1433 this.$input.val(value ? this.format_client(value) : '');
1435 get_value: function() {
1438 set_value_from_ui: function() {
1439 var value = this.$input.val() || false;
1440 this.value = this.parse_client(value);
1442 set_readonly: function(readonly) {
1443 this.readonly = readonly;
1444 this.$input.attr('disabled', this.readonly);
1445 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1447 is_valid: function(required) {
1448 var value = this.$input.val();
1453 this.parse_client(value);
1461 this.$input.focus();
1463 parse_client: function(v) {
1464 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1466 format_client: function(v) {
1467 return openerp.web.format_value(v, {"widget": this.type_of_date});
1469 on_change: function() {
1470 if (this.is_valid()) {
1471 this.set_value_from_ui();
1476 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1477 jqueryui_object: 'datepicker',
1478 type_of_date: "date"
1481 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1482 template: "EmptyComponent",
1483 build_widget: function() {
1484 return new openerp.web.DateTimeWidget(this);
1488 this._super.apply(this, arguments);
1489 this.datewidget = this.build_widget();
1490 this.datewidget.on_change.add_last(this.on_ui_change);
1491 this.datewidget.appendTo(this.$element);
1493 set_value: function(value) {
1495 this.datewidget.set_value(value);
1497 get_value: function() {
1498 return this.datewidget.get_value();
1500 update_dom: function() {
1501 this._super.apply(this, arguments);
1502 this.datewidget.set_readonly(this.readonly);
1504 validate: function() {
1505 this.invalid = !this.datewidget.is_valid(this.required);
1508 this.datewidget.focus();
1512 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1513 build_widget: function() {
1514 return new openerp.web.DateWidget(this);
1518 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1519 template: 'FieldText',
1521 this._super.apply(this, arguments);
1522 this.$element.find('textarea').change(this.on_ui_change);
1524 set_value: function(value) {
1525 this._super.apply(this, arguments);
1526 var show_value = openerp.web.format_value(value, this, '');
1527 this.$element.find('textarea').val(show_value);
1529 update_dom: function() {
1530 this._super.apply(this, arguments);
1531 this.$element.find('textarea').attr('disabled', this.readonly);
1533 set_value_from_ui: function() {
1534 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1537 validate: function() {
1538 this.invalid = false;
1540 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1541 this.invalid = this.required && value === '';
1543 this.invalid = true;
1547 this.$element.find('textarea').focus();
1551 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1552 template: 'FieldBoolean',
1555 this._super.apply(this, arguments);
1556 this.$element.find('input').click(self.on_ui_change);
1558 set_value: function(value) {
1559 this._super.apply(this, arguments);
1560 this.$element.find('input')[0].checked = value;
1562 set_value_from_ui: function() {
1563 this.value = this.$element.find('input').is(':checked');
1566 update_dom: function() {
1567 this._super.apply(this, arguments);
1568 this.$element.find('input').attr('disabled', this.readonly);
1571 this.$element.find('input').focus();
1575 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1576 template: 'FieldProgressBar',
1578 this._super.apply(this, arguments);
1579 this.$element.find('div').progressbar({
1581 disabled: this.readonly
1584 set_value: function(value) {
1585 this._super.apply(this, arguments);
1586 var show_value = Number(value);
1587 if (isNaN(show_value)) {
1590 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1594 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1595 // to replace view editor
1598 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1599 template: 'FieldSelection',
1600 init: function(view, node) {
1602 this._super(view, node);
1603 this.values = this.field.selection;
1604 _.each(this.values, function(v, i) {
1605 if (v[0] === false && v[1] === '') {
1606 self.values.splice(i, 1);
1609 this.values.unshift([false, '']);
1612 // Flag indicating whether we're in an event chain containing a change
1613 // event on the select, in order to know what to do on keyup[RETURN]:
1614 // * If the user presses [RETURN] as part of changing the value of a
1615 // selection, we should just let the value change and not let the
1616 // event broadcast further (e.g. to validating the current state of
1617 // the form in editable list view, which would lead to saving the
1618 // current row or switching to the next one)
1619 // * If the user presses [RETURN] with a select closed (side-effect:
1620 // also if the user opened the select and pressed [RETURN] without
1621 // changing the selected value), takes the action as validating the
1623 var ischanging = false;
1624 this._super.apply(this, arguments);
1625 this.$element.find('select')
1626 .change(this.on_ui_change)
1627 .change(function () { ischanging = true; })
1628 .click(function () { ischanging = false; })
1629 .keyup(function (e) {
1630 if (e.which !== 13 || !ischanging) { return; }
1631 e.stopPropagation();
1635 set_value: function(value) {
1636 value = value === null ? false : value;
1637 value = value instanceof Array ? value[0] : value;
1640 for (var i = 0, ii = this.values.length; i < ii; i++) {
1641 if (this.values[i][0] === value) index = i;
1643 this.$element.find('select')[0].selectedIndex = index;
1645 set_value_from_ui: function() {
1646 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1649 update_dom: function() {
1650 this._super.apply(this, arguments);
1651 this.$element.find('select').attr('disabled', this.readonly);
1653 validate: function() {
1654 var value = this.values[this.$element.find('select')[0].selectedIndex];
1655 this.invalid = !(value && !(this.required && value[0] === false));
1658 this.$element.find('select').focus();
1662 // jquery autocomplete tweak to allow html
1664 var proto = $.ui.autocomplete.prototype,
1665 initSource = proto._initSource;
1667 function filter( array, term ) {
1668 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1669 return $.grep( array, function(value) {
1670 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1675 _initSource: function() {
1676 if ( this.options.html && $.isArray(this.options.source) ) {
1677 this.source = function( request, response ) {
1678 response( filter( this.options.source, request.term ) );
1681 initSource.call( this );
1685 _renderItem: function( ul, item) {
1686 return $( "<li></li>" )
1687 .data( "item.autocomplete", item )
1688 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1694 openerp.web.form.dialog = function(content, options) {
1695 options = _.extend({
1702 options.autoOpen = true;
1703 var dialog = new openerp.web.Dialog(null, options);
1704 dialog.$dialog = $(content).dialog(dialog.dialog_options);
1705 return dialog.$dialog;
1708 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1709 template: 'FieldMany2One',
1710 init: function(view, node) {
1711 this._super(view, node);
1714 this.cm_id = _.uniqueId('m2o_cm_');
1715 this.last_search = [];
1716 this.tmp_value = undefined;
1721 this.$input = this.$element.find("input");
1722 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1723 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1726 var init_context_menu_def = $.Deferred().then(function(e) {
1727 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1728 rdataset.call("get", ['action', 'client_action_relate',
1729 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1730 .then(function(result) {
1731 self.related_entries = result;
1733 var $cmenu = $("#" + self.cm_id);
1734 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1736 bindings[self.cm_id + "_search"] = function() {
1737 self._search_create_popup("search");
1739 bindings[self.cm_id + "_create"] = function() {
1740 self._search_create_popup("form");
1742 bindings[self.cm_id + "_open"] = function() {
1746 var pop = new openerp.web.form.FormOpenPopup(self.view);
1747 pop.show_element(self.field.relation, self.value[0],self.build_context(), {});
1748 pop.on_write_completed.add_last(function() {
1749 self.set_value(self.value[0]);
1752 _.each(_.range(self.related_entries.length), function(i) {
1753 bindings[self.cm_id + "_related_" + i] = function() {
1754 self.open_related(self.related_entries[i]);
1757 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1758 bindings: bindings, itemStyle: {"color": ""},
1759 onContextMenu: function() {
1761 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1763 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1765 if (!self.readonly) {
1766 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1768 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1771 }, menuStyle: {width: "200px"}
1773 setTimeout(function() {self.$menu_btn.trigger(e);}, 0);
1776 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1777 this.$menu_btn.bind('contextmenu', ctx_callback);
1778 this.$menu_btn.click(ctx_callback);
1780 // some behavior for input
1781 this.$input.keyup(function() {
1782 if (self.$input.val() === "") {
1783 self._change_int_value(null);
1784 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1785 self._change_int_value(undefined);
1788 this.$drop_down.click(function() {
1791 if (self.$input.autocomplete("widget").is(":visible")) {
1792 self.$input.autocomplete("close");
1795 self.$input.autocomplete("search", "");
1797 self.$input.autocomplete("search");
1799 self.$input.focus();
1802 var anyoneLoosesFocus = function() {
1803 if (!self.$input.is(":focus") &&
1804 !self.$input.autocomplete("widget").is(":visible") &&
1806 if (self.value === undefined && self.last_search.length > 0) {
1807 self._change_int_ext_value(self.last_search[0]);
1809 self._change_int_ext_value(null);
1813 this.$input.focusout(anyoneLoosesFocus);
1815 var isSelecting = false;
1817 this.$input.autocomplete({
1818 source: function(req, resp) { self.get_search_result(req, resp); },
1819 select: function(event, ui) {
1823 self._change_int_value([item.id, item.name]);
1824 } else if (item.action) {
1825 self._change_int_value(undefined);
1830 focus: function(e, ui) {
1834 close: anyoneLoosesFocus,
1838 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1839 this.$input.keyup(function(e) {
1840 if (e.which === 13) {
1842 e.stopPropagation();
1844 isSelecting = false;
1847 // autocomplete component content handling
1848 get_search_result: function(request, response) {
1849 var search_val = request.term;
1852 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1854 dataset.name_search(search_val, self.build_domain(), 'ilike',
1855 this.limit + 1, function(data) {
1856 self.last_search = data;
1857 // possible selections for the m2o
1858 var values = _.map(data, function(x) {
1859 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1862 // search more... if more results that max
1863 if (values.length > self.limit) {
1864 values = values.slice(0, self.limit);
1865 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
1866 dataset.name_search(search_val, self.build_domain(), 'ilike'
1867 , false, function(data) {
1868 self._change_int_value(null);
1869 self._search_create_popup("search", data);
1874 var raw_result = _(data.result).map(function(x) {return x[1];});
1875 if (search_val.length > 0 &&
1876 !_.include(raw_result, search_val) &&
1877 (!self.value || search_val !== self.value[1])) {
1878 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
1879 $('<span />').text(search_val).html()), action: function() {
1880 self._quick_create(search_val);
1884 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
1885 self._change_int_value(null);
1886 self._search_create_popup("form", undefined, {"default_name": search_val});
1892 _quick_create: function(name) {
1894 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1895 dataset.name_create(name, function(data) {
1896 self._change_int_ext_value(data);
1897 }).fail(function(error, event) {
1898 event.preventDefault();
1899 self._change_int_value(null);
1900 self._search_create_popup("form", undefined, {"default_name": name});
1903 // all search/create popup handling
1904 _search_create_popup: function(view, ids, context) {
1906 var pop = new openerp.web.form.SelectCreatePopup(this);
1907 pop.select_element(self.field.relation,{
1908 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1910 disable_multiple_selection: true
1911 }, self.build_domain(),
1912 new openerp.web.CompoundContext(self.build_context(), context || {}));
1913 pop.on_select_elements.add(function(element_ids) {
1914 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1915 dataset.name_get([element_ids[0]], function(data) {
1916 self._change_int_ext_value(data[0]);
1920 _change_int_ext_value: function(value) {
1921 this._change_int_value(value);
1922 this.$input.val(this.value ? this.value[1] : "");
1924 _change_int_value: function(value) {
1926 var back_orig_value = this.original_value;
1927 if (this.value === null || this.value) {
1928 this.original_value = this.value;
1930 if (back_orig_value === undefined) { // first use after a set_value()
1933 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1934 !== (this.value ? this.value[0] : null))) {
1935 this.on_ui_change();
1938 set_value: function(value) {
1939 value = value || null;
1940 this.invalid = false;
1942 this.tmp_value = value;
1944 self.on_value_changed();
1945 var real_set_value = function(rval) {
1946 self.tmp_value = undefined;
1948 self.original_value = undefined;
1949 self._change_int_ext_value(rval);
1951 if (value && !(value instanceof Array)) {
1952 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1953 dataset.name_get([value], function(data) {
1954 real_set_value(data[0]);
1955 }).fail(function() {self.tmp_value = undefined;});
1957 setTimeout(function() {real_set_value(value);}, 0);
1960 get_value: function() {
1961 if (this.tmp_value !== undefined) {
1962 if (this.tmp_value instanceof Array) {
1963 return this.tmp_value[0];
1965 return this.tmp_value ? this.tmp_value : false;
1967 if (this.value === undefined)
1968 return this.original_value ? this.original_value[0] : false;
1969 return this.value ? this.value[0] : false;
1971 validate: function() {
1972 this.invalid = false;
1973 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1975 this.invalid = this.required;
1978 open_related: function(related) {
1982 var additional_context = {
1983 active_id: self.value[0],
1984 active_ids: [self.value[0]],
1985 active_model: self.field.relation
1987 self.rpc("/web/action/load", {
1988 action_id: related[2].id,
1989 context: additional_context
1990 }, function(result) {
1991 result.result.context = _.extend(result.result.context || {}, additional_context);
1992 self.do_action(result.result);
1995 focus: function () {
1996 this.$input.focus();
1998 update_dom: function() {
1999 this._super.apply(this, arguments);
2000 this.$input.attr('disabled', this.readonly);
2005 # Values: (0, 0, { fields }) create
2006 # (1, ID, { fields }) update
2007 # (2, ID) remove (delete)
2008 # (3, ID) unlink one (target id or target of relation)
2010 # (5) unlink all (only valid for one2many)
2015 'create': function (values) {
2016 return [commands.CREATE, false, values];
2018 // (1, id, {values})
2020 'update': function (id, values) {
2021 return [commands.UPDATE, id, values];
2025 'delete': function (id) {
2026 return [commands.DELETE, id, false];
2028 // (3, id[, _]) removes relation, but not linked record itself
2030 'forget': function (id) {
2031 return [commands.FORGET, id, false];
2035 'link_to': function (id) {
2036 return [commands.LINK_TO, id, false];
2040 'delete_all': function () {
2041 return [5, false, false];
2043 // (6, _, ids) replaces all linked records with provided ids
2045 'replace_with': function (ids) {
2046 return [6, false, ids];
2049 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2050 template: 'FieldOne2Many',
2051 multi_selection: false,
2052 init: function(view, node) {
2053 this._super(view, node);
2054 this.is_loaded = $.Deferred();
2055 this.initial_is_loaded = this.is_loaded;
2056 this.is_setted = $.Deferred();
2057 this.form_last_update = $.Deferred();
2058 this.init_form_last_update = this.form_last_update;
2059 this.disable_utility_classes = true;
2062 this._super.apply(this, arguments);
2066 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2067 this.dataset.o2m = this;
2068 this.dataset.parent_view = this.view;
2069 this.dataset.on_change.add_last(function() {
2070 self.on_ui_change();
2073 this.is_setted.then(function() {
2077 is_readonly: function() {
2078 return this.readonly || this.force_readonly;
2080 load_views: function() {
2083 var modes = this.node.attrs.mode;
2084 modes = !!modes ? modes.split(",") : ["tree"];
2086 _.each(modes, function(mode) {
2089 view_type: mode == "tree" ? "list" : mode,
2090 options: { sidebar : false }
2092 if (self.field.views && self.field.views[mode]) {
2093 view.embedded_view = self.field.views[mode];
2095 if(view.view_type === "list") {
2096 view.options.selectable = self.multi_selection;
2097 if (self.is_readonly()) {
2098 view.options.addable = null;
2099 view.options.deletable = null;
2101 } else if (view.view_type === "form") {
2102 view.options.not_interactible_on_create = true;
2108 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views);
2109 this.viewmanager.registry = openerp.web.views.clone({
2110 list: 'openerp.web.form.One2ManyListView',
2111 form: 'openerp.web.FormView'
2113 var once = $.Deferred().then(function() {
2114 self.init_form_last_update.resolve();
2116 var def = $.Deferred().then(function() {
2117 self.initial_is_loaded.resolve();
2119 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2120 if (view_type == "list") {
2121 controller.o2m = self;
2122 if (self.is_readonly())
2123 controller.set_editable(false);
2124 } else if (view_type == "form") {
2125 if (self.is_readonly()) {
2126 controller.on_toggle_readonly();
2127 $(controller.$element.find(".oe_form_buttons")[0]).children().remove();
2129 controller.on_record_loaded.add_last(function() {
2132 controller.on_pager_action.add_first(function() {
2133 self.save_any_view();
2135 controller.$element.find(".oe_form_button_save").hide();
2136 } else if (view_type == "graph") {
2137 self.reload_current_view()
2141 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2142 $.when(self.save_any_view()).then(function() {
2143 if(n_mode === "list")
2144 setTimeout(function() {self.reload_current_view();}, 0);
2147 this.is_setted.then(function() {
2148 setTimeout(function () {
2149 self.viewmanager.appendTo(self.$element);
2154 reload_current_view: function() {
2156 return self.is_loaded = self.is_loaded.pipe(function() {
2157 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
2158 if(self.viewmanager.active_view === "list") {
2159 return view.reload_content();
2160 } else if (self.viewmanager.active_view === "form") {
2161 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2162 self.dataset.index = 0;
2164 var act = function() {
2165 return view.do_show();
2167 self.form_last_update = self.form_last_update.pipe(act, act);
2168 return self.form_last_update;
2169 } else if (self.viewmanager.active_view === "graph") {
2170 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2174 set_value: function(value) {
2175 value = value || [];
2177 this.dataset.reset_ids([]);
2178 if(value.length >= 1 && value[0] instanceof Array) {
2180 _.each(value, function(command) {
2181 var obj = {values: command[2]};
2182 switch (command[0]) {
2183 case commands.CREATE:
2184 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2186 self.dataset.to_create.push(obj);
2187 self.dataset.cache.push(_.clone(obj));
2190 case commands.UPDATE:
2191 obj['id'] = command[1];
2192 self.dataset.to_write.push(obj);
2193 self.dataset.cache.push(_.clone(obj));
2196 case commands.DELETE:
2197 self.dataset.to_delete.push({id: command[1]});
2199 case commands.LINK_TO:
2200 ids.push(command[1]);
2202 case commands.DELETE_ALL:
2203 self.dataset.delete_all = true;
2208 this.dataset.set_ids(ids);
2209 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2211 this.dataset.delete_all = true;
2212 _.each(value, function(command) {
2213 var obj = {values: command};
2214 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2216 self.dataset.to_create.push(obj);
2217 self.dataset.cache.push(_.clone(obj));
2221 this.dataset.set_ids(ids);
2224 this.dataset.reset_ids(value);
2226 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2227 this.dataset.index = 0;
2229 self.is_setted.resolve();
2230 return self.reload_current_view();
2232 get_value: function() {
2236 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2237 val = val.concat(_.map(this.dataset.ids, function(id) {
2238 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2240 return commands.create(alter_order.values);
2242 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2244 return commands.update(alter_order.id, alter_order.values);
2246 return commands.link_to(id);
2248 return val.concat(_.map(
2249 this.dataset.to_delete, function(x) {
2250 return commands['delete'](x.id);}));
2252 save_any_view: function() {
2253 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2254 this.viewmanager.views[this.viewmanager.active_view] &&
2255 this.viewmanager.views[this.viewmanager.active_view].controller) {
2256 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2257 if (this.viewmanager.active_view === "form") {
2258 var res = $.when(view.do_save());
2259 // it seems line there are some cases when this happens
2260 /*if (!res.isResolved() && !res.isRejected()) {
2261 console.warn("Asynchronous get_value() is not supported in form view.");
2264 } else if (this.viewmanager.active_view === "list") {
2265 var res = $.when(view.ensure_saved());
2266 // it seems line there are some cases when this happens
2267 /*if (!res.isResolved() && !res.isRejected()) {
2268 console.warn("Asynchronous get_value() is not supported in list view.");
2275 is_valid: function() {
2277 return this._super();
2279 validate: function() {
2280 this.invalid = false;
2281 if (!this.viewmanager.views[this.viewmanager.active_view])
2283 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2284 if (this.viewmanager.active_view === "form") {
2285 for (var f in view.fields) {
2287 if (!f.is_valid()) {
2288 this.invalid = true;
2294 is_dirty: function() {
2295 this.save_any_view();
2296 return this._super();
2298 update_dom: function() {
2299 this._super.apply(this, arguments);
2301 if (this.previous_readonly !== this.readonly) {
2302 this.previous_readonly = this.readonly;
2303 if (this.viewmanager) {
2304 this.is_loaded = this.is_loaded.pipe(function() {
2305 self.viewmanager.stop();
2306 return $.when(self.load_views()).then(function() {
2307 self.reload_current_view();
2315 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2316 get_context: function() {
2317 this.context = this.o2m.build_context();
2318 return this.context;
2322 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2323 do_add_record: function () {
2324 if (this.options.editable) {
2325 this._super.apply(this, arguments);
2328 var pop = new openerp.web.form.SelectCreatePopup(this);
2329 pop.on_default_get.add(self.dataset.on_default_get);
2330 pop.select_element(self.o2m.field.relation,{
2331 initial_view: "form",
2332 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2333 create_function: function(data, callback, error_callback) {
2334 return self.o2m.dataset.create(data).then(function(r) {
2335 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2336 self.o2m.dataset.on_change();
2337 }).then(callback, error_callback);
2339 read_function: function() {
2340 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2342 parent_view: self.o2m.view,
2343 form_view_options: {'not_interactible_on_create':true}
2344 }, self.o2m.build_domain(), self.o2m.build_context());
2345 pop.on_select_elements.add_last(function() {
2346 self.o2m.reload_current_view();
2350 do_activate_record: function(index, id) {
2352 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2353 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(),{
2355 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2356 parent_view: self.o2m.view,
2357 read_function: function() {
2358 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2360 form_view_options: {'not_interactible_on_create':true},
2361 readonly: self.o2m.is_readonly()
2363 pop.on_write.add(function(id, data) {
2364 self.o2m.dataset.write(id, data, {}, function(r) {
2365 self.o2m.reload_current_view();
2371 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2372 template: 'FieldMany2Many',
2373 multi_selection: false,
2374 init: function(view, node) {
2375 this._super(view, node);
2376 this.list_id = _.uniqueId("many2many");
2377 this.is_loaded = $.Deferred();
2378 this.initial_is_loaded = this.is_loaded;
2379 this.is_setted = $.Deferred();
2382 this._super.apply(this, arguments);
2386 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2387 this.dataset.m2m = this;
2388 this.dataset.on_unlink.add_last(function(ids) {
2389 self.on_ui_change();
2392 this.is_setted.then(function() {
2396 set_value: function(value) {
2397 value = value || [];
2398 if (value.length >= 1 && value[0] instanceof Array) {
2399 value = value[0][2];
2402 this.dataset.set_ids(value);
2404 self.reload_content();
2405 this.is_setted.resolve();
2407 get_value: function() {
2408 return [commands.replace_with(this.dataset.ids)];
2410 validate: function() {
2411 this.invalid = false;
2413 is_readonly: function() {
2414 return this.readonly || this.force_readonly;
2416 load_view: function() {
2418 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2419 'addable': self.is_readonly() ? null : 'Add',
2420 'deletable': self.is_readonly() ? false : true,
2421 'selectable': self.multi_selection
2423 var embedded = (this.field.views || {}).tree;
2425 this.list_view.set_embedded_view(embedded);
2427 this.list_view.m2m_field = this;
2428 var loaded = $.Deferred();
2429 this.list_view.on_loaded.add_last(function() {
2430 self.initial_is_loaded.resolve();
2433 setTimeout(function () {
2434 self.list_view.appendTo($("#" + self.list_id));
2438 reload_content: function() {
2440 this.is_loaded = this.is_loaded.pipe(function() {
2441 return self.list_view.reload_content();
2444 update_dom: function() {
2445 this._super.apply(this, arguments);
2447 if (this.previous_readonly !== this.readonly) {
2448 this.previous_readonly = this.readonly;
2449 if (this.list_view) {
2450 this.is_loaded = this.is_loaded.pipe(function() {
2451 self.list_view.stop();
2452 return $.when(self.load_view()).then(function() {
2453 self.reload_content();
2461 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2462 get_context: function() {
2463 this.context = this.m2m.build_context();
2464 return this.context;
2470 * @extends openerp.web.ListView
2472 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2473 do_add_record: function () {
2474 var pop = new openerp.web.form.SelectCreatePopup(this);
2475 pop.select_element(this.model, {},
2476 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2477 this.m2m_field.build_context());
2479 pop.on_select_elements.add(function(element_ids) {
2480 _.each(element_ids, function(element_id) {
2481 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2482 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2483 self.m2m_field.on_ui_change();
2484 self.reload_content();
2489 do_activate_record: function(index, id) {
2491 var pop = new openerp.web.form.FormOpenPopup(this);
2492 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {});
2493 pop.on_write_completed.add_last(function() {
2494 self.reload_content();
2501 * @extends openerp.web.OldWidget
2503 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2504 identifier_prefix: "selectcreatepopup",
2505 template: "SelectCreatePopup",
2509 * - initial_view: form or search (default search)
2510 * - disable_multiple_selection
2511 * - alternative_form_view
2512 * - create_function (defaults to a naive saving behavior)
2514 * - form_view_options
2515 * - list_view_options
2518 select_element: function(model, options, domain, context) {
2521 this.domain = domain || [];
2522 this.context = context || {};
2523 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2524 return self.create_row.apply(self, arguments);
2525 }, read_function: null});
2526 this.initial_ids = this.options.initial_ids;
2527 this.created_elements = [];
2528 this.render_element();
2529 openerp.web.form.dialog(this.$element, {close:function() {
2537 search_defaults = {};
2538 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2540 this.dataset.create_function = function() {
2541 return self.options.create_function.apply(null, arguments).then(function(r) {
2542 self.created_elements.push(r.result);
2545 this.dataset.write_function = function() {
2546 return self.write_row.apply(self, arguments);
2548 this.dataset.read_function = this.options.read_function;
2549 this.dataset.parent_view = this.options.parent_view;
2550 this.dataset.on_default_get.add(this.on_default_get);
2551 if (this.options.initial_view == "search") {
2552 self.rpc('/web/session/eval_domain_and_context', {
2554 contexts: [this.context],
2555 }, function (results) {
2556 _.each(results.context, function (value, key) {
2557 var match = /^search_default_(.*)$/.exec(key);
2559 search_defaults[match[1]] = value;
2562 self.setup_search_view(search_defaults);
2568 setup_search_view: function(search_defaults) {
2570 if (this.searchview) {
2571 this.searchview.stop();
2573 this.searchview = new openerp.web.SearchView(this,
2574 this.dataset, false, search_defaults);
2575 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2576 if (self.initial_ids) {
2577 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2578 contexts, groupbys);
2579 self.initial_ids = undefined;
2581 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2584 this.searchview.on_loaded.add_last(function () {
2585 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
2586 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
2587 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2588 $cbutton.click(function() {
2591 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2592 if(self.options.disable_multiple_selection) {
2595 $sbutton.click(function() {
2596 self.on_select_elements(self.selected_ids);
2599 self.view_list = new openerp.web.form.SelectCreateListView(self,
2600 self.dataset, false,
2601 _.extend({'deletable': false,
2602 'selectable': !self.options.disable_multiple_selection
2603 }, self.options.list_view_options || {}));
2604 self.view_list.popup = self;
2605 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2606 self.view_list.do_show();
2607 }).pipe(function() {
2608 self.searchview.do_search();
2611 this.searchview.appendTo($("#" + this.element_id + "_search"));
2613 do_search: function(domains, contexts, groupbys) {
2615 this.rpc('/web/session/eval_domain_and_context', {
2616 domains: domains || [],
2617 contexts: contexts || [],
2618 group_by_seq: groupbys || []
2619 }, function (results) {
2620 self.view_list.do_search(results.domain, results.context, results.group_by);
2623 create_row: function() {
2625 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2626 wdataset.parent_view = this.options.parent_view;
2627 return wdataset.create.apply(wdataset, arguments);
2629 write_row: function() {
2631 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2632 wdataset.parent_view = this.options.parent_view;
2633 return wdataset.write.apply(wdataset, arguments);
2635 on_select_elements: function(element_ids) {
2637 on_click_element: function(ids) {
2638 this.selected_ids = ids || [];
2639 if(this.selected_ids.length > 0) {
2640 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2642 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2645 new_object: function() {
2647 if (this.searchview) {
2648 this.searchview.hide();
2650 if (this.view_list) {
2651 this.view_list.$element.hide();
2653 this.dataset.index = null;
2654 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2655 if (this.options.alternative_form_view) {
2656 this.view_form.set_embedded_view(this.options.alternative_form_view);
2658 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2659 this.view_form.on_loaded.add_last(function() {
2660 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2661 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2662 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2663 $nbutton.click(function() {
2664 $.when(self.view_form.do_save()).then(function() {
2665 self.view_form.reload_lock.then(function() {
2666 self.view_form.on_button_new();
2670 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2671 $nbutton.click(function() {
2672 $.when(self.view_form.do_save()).then(function() {
2673 self.view_form.reload_lock.then(function() {
2678 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2679 $cbutton.click(function() {
2683 this.view_form.do_show();
2685 check_exit: function() {
2686 if (this.created_elements.length > 0) {
2687 this.on_select_elements(this.created_elements);
2691 on_default_get: function(res) {}
2694 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2695 do_add_record: function () {
2696 this.popup.new_object();
2698 select_record: function(index) {
2699 this.popup.on_select_elements([this.dataset.ids[index]]);
2702 do_select: function(ids, records) {
2703 this._super(ids, records);
2704 this.popup.on_click_element(ids);
2710 * @extends openerp.web.OldWidget
2712 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2713 identifier_prefix: "formopenpopup",
2714 template: "FormOpenPopup",
2717 * - alternative_form_view
2718 * - auto_write (default true)
2721 * - form_view_options
2724 show_element: function(model, row_id, context, options) {
2726 this.row_id = row_id;
2727 this.context = context || {};
2728 this.options = _.defaults(options || {}, {"auto_write": true});
2729 this.render_element();
2730 this.$element.dialog({title: '',
2738 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2739 this.dataset.fop = this;
2740 this.dataset.ids = [this.row_id];
2741 this.dataset.index = 0;
2742 this.dataset.parent_view = this.options.parent_view;
2743 this.setup_form_view();
2745 on_write: function(id, data) {
2746 if (!this.options.auto_write)
2749 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2750 wdataset.parent_view = this.options.parent_view;
2751 wdataset.write(id, data, {}, function(r) {
2752 self.on_write_completed();
2755 on_write_completed: function() {},
2756 setup_form_view: function() {
2758 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2759 if (this.options.alternative_form_view) {
2760 this.view_form.set_embedded_view(this.options.alternative_form_view);
2762 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2763 var once = $.Deferred().then(function() {
2764 if (self.options.readonly) {
2765 self.view_form.on_toggle_readonly();
2768 this.view_form.on_loaded.add_last(function() {
2770 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2771 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2772 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2773 $nbutton.click(function() {
2774 self.view_form.do_save().then(function() {
2778 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2779 $cbutton.click(function() {
2782 if (self.options.readonly) {
2784 $cbutton.text(_t("Close"));
2786 self.view_form.do_show();
2788 this.dataset.on_write.add(this.on_write);
2792 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2793 read_ids: function() {
2794 if (this.fop.options.read_function) {
2795 return this.fop.options.read_function.apply(null, arguments);
2797 return this._super.apply(this, arguments);
2802 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2803 template: 'FieldReference',
2804 init: function(view, node) {
2805 this._super(view, node);
2806 this.fields_view = {
2809 selection: view.fields_view.fields[this.name].selection
2816 this.get_fields_values = view.get_fields_values;
2817 this.do_onchange = this.on_form_changed = this.on_nop;
2818 this.dataset = this.view.dataset;
2819 this.widgets_counter = 0;
2820 this.view_id = 'reference_' + _.uniqueId();
2823 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2827 this.selection.on_value_changed.add_last(this.on_selection_changed);
2828 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2833 on_nop: function() {
2835 on_selection_changed: function() {
2836 var sel = this.selection.get_value();
2837 this.m2o.field.relation = sel;
2838 this.m2o.set_value(null);
2839 this.m2o.$element.toggle(sel !== false);
2843 this.selection.start();
2846 is_valid: function() {
2847 return this.required === false || typeof(this.get_value()) === 'string';
2849 is_dirty: function() {
2850 return this.selection.is_dirty() || this.m2o.is_dirty();
2852 set_value: function(value) {
2854 if (typeof(value) === 'string') {
2855 var vals = value.split(',');
2856 this.selection.set_value(vals[0]);
2857 this.m2o.set_value(parseInt(vals[1], 10));
2860 get_value: function() {
2861 var model = this.selection.get_value(),
2862 id = this.m2o.get_value();
2863 if (typeof(model) === 'string' && typeof(id) === 'number') {
2864 return model + ',' + id;
2871 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2872 init: function(view, node) {
2873 this._super(view, node);
2874 this.iframe = this.element_id + '_iframe';
2875 this.binary_value = false;
2878 this._super.apply(this, arguments);
2879 this.$element.find('input.oe-binary-file').change(this.on_file_change);
2880 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2881 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2883 human_filesize : function(size) {
2884 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2886 while (size >= 1024) {
2890 return size.toFixed(2) + ' ' + units[i];
2892 on_file_change: function(e) {
2893 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2894 // http://www.html5rocks.com/tutorials/file/dndfiles/
2895 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2896 window[this.iframe] = this.on_file_uploaded;
2897 if ($(e.target).val() != '') {
2898 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2899 this.$element.find('form.oe-binary-form').submit();
2900 this.$element.find('.oe-binary-progress').show();
2901 this.$element.find('.oe-binary').hide();
2904 on_file_uploaded: function(size, name, content_type, file_base64) {
2905 delete(window[this.iframe]);
2906 if (size === false) {
2907 this.do_warn("File Upload", "There was a problem while uploading your file");
2908 // TODO: use openerp web crashmanager
2909 console.warn("Error while uploading file : ", name);
2911 this.on_file_uploaded_and_valid.apply(this, arguments);
2912 this.on_ui_change();
2914 this.$element.find('.oe-binary-progress').hide();
2915 this.$element.find('.oe-binary').show();
2917 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2919 on_save_as: function() {
2920 var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
2921 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
2922 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
2925 on_clear: function() {
2926 if (this.value !== false) {
2928 this.binary_value = false;
2929 this.on_ui_change();
2935 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
2936 template: 'FieldBinaryFile',
2937 update_dom: function() {
2938 this._super.apply(this, arguments);
2939 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
2940 this.$element.find('input[type=text]').attr('disabled', this.readonly);
2942 set_value: function(value) {
2943 this._super.apply(this, arguments);
2944 var show_value = (value != null && value !== false) ? value : '';
2945 this.$element.find('input').eq(0).val(show_value);
2947 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2948 this.value = file_base64;
2949 this.binary_value = true;
2950 var show_value = this.human_filesize(size);
2951 this.$element.find('input').eq(0).val(show_value);
2952 this.set_filename(name);
2954 set_filename: function(value) {
2955 var filename = this.node.attrs.filename;
2956 if (this.view.fields[filename]) {
2957 this.view.fields[filename].set_value(value);
2958 this.view.fields[filename].on_ui_change();
2961 on_clear: function() {
2962 this._super.apply(this, arguments);
2963 this.$element.find('input').eq(0).val('');
2964 this.set_filename('');
2968 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
2969 template: 'FieldBinaryImage',
2971 this._super.apply(this, arguments);
2972 this.$image = this.$element.find('img.oe-binary-image');
2974 update_dom: function() {
2975 this._super.apply(this, arguments);
2976 this.$element.find('.oe-binary').toggle(!this.readonly);
2978 set_value: function(value) {
2979 this._super.apply(this, arguments);
2980 this.set_image_maxwidth();
2981 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
2982 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
2983 this.$image.attr('src', url);
2985 set_image_maxwidth: function() {
2986 this.$image.css('max-width', this.$element.width());
2988 on_file_change: function() {
2989 this.set_image_maxwidth();
2990 this._super.apply(this, arguments);
2992 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2993 this.value = file_base64;
2994 this.binary_value = true;
2995 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2997 on_clear: function() {
2998 this._super.apply(this, arguments);
2999 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3003 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3004 template: "EmptyComponent",
3007 this.selected_value = null;
3011 set_value: function(value) {
3013 this.selected_value = value;
3017 render_list: function() {
3019 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3020 function(x) { return _.str.trim(x); });
3021 shown = _.select(shown, function(x) { return x.length > 0; });
3023 if (shown.length == 0) {
3024 this.to_show = this.field.selection;
3026 this.to_show = _.select(this.field.selection, function(x) {
3027 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3031 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3032 this.$element.html(content);
3034 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3035 var color = colors[this.selected_value];
3037 var elem = this.$element.find("li.oe-arrow-list-selected span");
3038 elem.css("border-color", color);
3039 if (this.check_white(color))
3040 elem.css("color", "white");
3041 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3042 elem.css("border-left-color", "rgba(0,0,0,0)");
3043 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3044 elem.css("border-color", "rgba(0,0,0,0)");
3045 elem.css("border-left-color", color);
3048 check_white: function(color) {
3049 var div = $("<div></div>");
3050 div.css("display", "none");
3051 div.css("color", color);
3052 div.appendTo($("body"));
3053 var ncolor = div.css("color");
3055 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3059 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3060 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3068 openerp.web.form.FieldReadonly = openerp.web.form.Field.extend({
3071 openerp.web.form.FieldCharReadonly = openerp.web.form.FieldReadonly.extend({
3072 template: 'FieldChar.readonly',
3073 init: function(view, node) {
3074 this._super(view, node);
3075 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
3077 set_value: function (value) {
3078 this._super.apply(this, arguments);
3079 var show_value = openerp.web.format_value(value, this, '');
3080 if (this.password) {
3081 show_value = new Array(show_value.length + 1).join('*');
3083 this.$element.find('div').text(show_value);
3087 openerp.web.form.FieldURIReadonly = openerp.web.form.FieldCharReadonly.extend({
3088 template: 'FieldURI.readonly',
3090 set_value: function (value) {
3091 var displayed = this._super.apply(this, arguments);
3092 this.$element.find('a')
3093 .attr('href', this.scheme + ':' + displayed)
3097 openerp.web.form.FieldEmailReadonly = openerp.web.form.FieldURIReadonly.extend({
3100 openerp.web.form.FieldUrlReadonly = openerp.web.form.FieldURIReadonly.extend({
3101 set_value: function (value) {
3102 var s = /(\w+):(.+)/.exec(value);
3103 if (!s || !(s[1] === 'http' || s[1] === 'https')) { return; }
3108 openerp.web.form.FieldBooleanReadonly = openerp.web.form.FieldCharReadonly.extend({
3109 set_value: function (value) {
3110 this._super(value ? '\u2611' : '\u2610');
3113 openerp.web.form.FieldSelectionReadonly = openerp.web.form.FieldReadonly.extend({
3114 template: 'FieldChar.readonly',
3115 init: function(view, node) {
3116 // lifted straight from r/w version
3118 this._super(view, node);
3119 this.values = this.field.selection;
3120 _.each(this.values, function(v, i) {
3121 if (v[0] === false && v[1] === '') {
3122 self.values.splice(i, 1);
3125 this.values.unshift([false, '']);
3127 set_value: function (value) {
3128 value = value === null ? false : value;
3129 value = value instanceof Array ? value[0] : value;
3130 var option = _(this.values)
3131 .detect(function (record) { return record[0] === value; });
3133 this.$element.find('div').text(option ? option[1] : this.values[0][1]);
3136 openerp.web.form.FieldMany2OneReadonly = openerp.web.form.FieldURIReadonly.extend({
3137 set_value: function (value) {
3138 value = value || null;
3139 this.invalid = false;
3143 self.on_value_changed();
3144 var real_set_value = function(rval) {
3146 self.$element.find('a')
3148 .text(rval ? rval[1] : '')
3149 .click(function () {
3151 type: 'ir.actions.act_window',
3152 res_model: self.field.relation,
3153 res_id: self.value[0],
3154 context: self.build_context(),
3155 views: [[false, 'form']],
3161 if (value && !(value instanceof Array)) {
3162 new openerp.web.DataSetStatic(
3163 this, this.field.relation, self.build_context())
3164 .name_get([value], function(data) {
3165 real_set_value(data[0]);
3168 setTimeout(function() {real_set_value(value);}, 0);
3171 get_value: function() {
3174 } else if (this.value instanceof Array) {
3175 return this.value[0];
3183 * Registry of form widgets, called by :js:`openerp.web.FormView`
3185 openerp.web.form.widgets = new openerp.web.Registry({
3186 'frame' : 'openerp.web.form.WidgetFrame',
3187 'group' : 'openerp.web.form.WidgetGroup',
3188 'notebook' : 'openerp.web.form.WidgetNotebook',
3189 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3190 'separator' : 'openerp.web.form.WidgetSeparator',
3191 'label' : 'openerp.web.form.WidgetLabel',
3192 'button' : 'openerp.web.form.WidgetButton',
3193 'char' : 'openerp.web.form.FieldChar',
3194 'email' : 'openerp.web.form.FieldEmail',
3195 'url' : 'openerp.web.form.FieldUrl',
3196 'text' : 'openerp.web.form.FieldText',
3197 'text_wiki' : 'openerp.web.form.FieldText',
3198 'date' : 'openerp.web.form.FieldDate',
3199 'datetime' : 'openerp.web.form.FieldDatetime',
3200 'selection' : 'openerp.web.form.FieldSelection',
3201 'many2one' : 'openerp.web.form.FieldMany2One',
3202 'many2many' : 'openerp.web.form.FieldMany2Many',
3203 'one2many' : 'openerp.web.form.FieldOne2Many',
3204 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3205 'reference' : 'openerp.web.form.FieldReference',
3206 'boolean' : 'openerp.web.form.FieldBoolean',
3207 'float' : 'openerp.web.form.FieldFloat',
3208 'integer': 'openerp.web.form.FieldFloat',
3209 'float_time': 'openerp.web.form.FieldFloat',
3210 'progressbar': 'openerp.web.form.FieldProgressBar',
3211 'image': 'openerp.web.form.FieldBinaryImage',
3212 'binary': 'openerp.web.form.FieldBinaryFile',
3213 'statusbar': 'openerp.web.form.FieldStatus'
3216 openerp.web.form.FieldMany2ManyReadonly = openerp.web.form.FieldMany2Many.extend({
3217 force_readonly: true
3219 openerp.web.form.FieldOne2ManyReadonly = openerp.web.form.FieldOne2Many.extend({
3220 force_readonly: true
3222 openerp.web.form.readonly = openerp.web.form.widgets.clone({
3223 'char': 'openerp.web.form.FieldCharReadonly',
3224 'email': 'openerp.web.form.FieldEmailReadonly',
3225 'url': 'openerp.web.form.FieldUrlReadonly',
3226 'text': 'openerp.web.form.FieldCharReadonly',
3227 'text_wiki' : 'openerp.web.form.FieldCharReadonly',
3228 'date': 'openerp.web.form.FieldCharReadonly',
3229 'datetime': 'openerp.web.form.FieldCharReadonly',
3230 'selection' : 'openerp.web.form.FieldSelectionReadonly',
3231 'many2one': 'openerp.web.form.FieldMany2OneReadonly',
3232 'many2many' : 'openerp.web.form.FieldMany2ManyReadonly',
3233 'one2many' : 'openerp.web.form.FieldOne2ManyReadonly',
3234 'one2many_list' : 'openerp.web.form.FieldOne2ManyReadonly',
3235 'boolean': 'openerp.web.form.FieldBooleanReadonly',
3236 'float': 'openerp.web.form.FieldCharReadonly',
3237 'integer': 'openerp.web.form.FieldCharReadonly',
3238 'float_time': 'openerp.web.form.FieldCharReadonly'
3243 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: