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;
36 this.fields_order = [];
38 this.show_invalid = true;
39 this.default_focus_field = null;
40 this.default_focus_button = null;
41 this.registry = openerp.web.form.widgets;
42 this.has_been_loaded = $.Deferred();
43 this.$form_header = null;
44 this.translatable_fields = [];
45 _.defaults(this.options, {
46 "not_interactible_on_create": false
48 this.mutating_lock = $.Deferred();
49 this.initial_mutating_lock = this.mutating_lock;
50 this.on_change_lock = $.Deferred().resolve();
51 this.reload_lock = $.Deferred().resolve();
55 return this.init_view();
57 init_view: function() {
58 if (this.embedded_view) {
59 var def = $.Deferred().then(this.on_loaded);
61 setTimeout(function() {def.resolve(self.embedded_view);}, 0);
64 var context = new openerp.web.CompoundContext(this.dataset.get_context());
65 return this.rpc("/web/view/load", {
67 "view_id": this.view_id,
69 toolbar: this.options.sidebar,
76 this.sidebar.attachments.stop();
79 _.each(this.widgets, function(w) {
84 reposition: function ($e) {
88 on_loaded: function(data) {
91 this.fields_order = [];
92 this.fields_view = data;
93 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
95 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
97 this.$element.html(this.rendered);
98 _.each(this.widgets, function(w) {
101 this.$form_header = this.$element.find('.oe_form_header:first');
102 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
103 var action = $(this).data('pager-action');
104 self.on_pager_action(action);
107 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
108 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
110 if (!this.sidebar && 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 do_show: function () {
122 if (this.dataset.index === null) {
123 // null index means we should start a new record
124 promise = this.on_button_new();
126 promise = this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_record_loaded);
128 this.$element.show();
130 this.sidebar.$element.show();
134 do_hide: function () {
135 this.$element.hide();
137 this.sidebar.$element.hide();
140 on_record_loaded: function(record) {
142 deferred_stack = $.Deferred.queue();
144 throw("Form: No record received");
146 this.datarecord = record;
148 _(this.fields).each(function (field, f) {
150 var result = field.set_value(self.datarecord[f] || false);
151 if (result && _.isFunction(result.promise)) {
152 deferred_stack.push(result);
154 $.when(result).then(function() {
158 deferred_stack.push('force resolution if no fields');
159 return deferred_stack.then(function() {
161 self.show_invalid = false;
162 // New record: Second pass in order to trigger the onchanges
163 // respecting the fields order defined in the view
164 _.each(self.fields_order, function(field_name) {
165 if (record[field_name] !== undefined) {
166 var field = self.fields[field_name];
168 self.do_onchange(field);
172 self.on_form_changed();
173 self.initial_mutating_lock.resolve();
174 self.show_invalid = true;
175 self.do_update_pager(record.id == null);
177 self.sidebar.attachments.do_update();
179 if (self.default_focus_field && !self.embedded_view) {
180 self.default_focus_field.focus();
184 on_form_changed: function() {
185 for (var w in this.widgets) {
187 w.process_modifiers();
191 on_pager_action: function(action) {
192 if (this.can_be_discarded()) {
195 this.dataset.index = 0;
198 this.dataset.previous();
204 this.dataset.index = this.dataset.ids.length - 1;
210 do_update_pager: function(hide_index) {
211 var $pager = this.$form_header.find('div.oe_form_pager');
212 var index = hide_index ? '-' : this.dataset.index + 1;
213 $pager.find('span.oe_pager_index').html(index);
214 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
216 parse_on_change: function (on_change, widget) {
218 var onchange = _.str.trim(on_change);
219 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
224 var method = call[1];
225 if (!_.str.trim(call[2])) {
226 return {method: method, args: [], context_index: null}
229 var argument_replacement = {
230 'False': function () {return false;},
231 'True': function () {return true;},
232 'None': function () {return null;},
233 'context': function (i) {
235 var ctx = widget.build_context ? widget.build_context() : {};
239 var parent_fields = null, context_index = null;
240 var args = _.map(call[2].split(','), function (a, i) {
241 var field = _.str.trim(a);
243 // literal constant or context
244 if (field in argument_replacement) {
245 return argument_replacement[field](i);
248 if (/^-?\d+(\.\d+)?$/.test(field)) {
249 return Number(field);
252 if (self.fields[field]) {
253 var value = self.fields[field].get_on_change_value();
254 return value == null ? false : value;
257 var splitted = field.split('.');
258 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
259 if (parent_fields === null) {
260 parent_fields = self.dataset.parent_view.get_fields_values();
262 var p_val = parent_fields[_.str.trim(splitted[1])];
263 if (p_val !== undefined) {
264 return p_val == null ? false : p_val;
268 var first_char = field[0], last_char = field[field.length-1];
269 if ((first_char === '"' && last_char === '"')
270 || (first_char === "'" && last_char === "'")) {
271 return field.slice(1, -1);
274 throw new Error("Could not get field with name '" + field +
275 "' for onchange '" + onchange + "'");
281 context_index: context_index
284 do_onchange: function(widget, processed) {
286 var act = function() {
288 processed = processed || [];
289 var on_change = widget.node.attrs.on_change;
291 var change_spec = self.parse_on_change(on_change, widget);
294 url: '/web/dataset/call',
297 return self.rpc(ajax, {
298 model: self.dataset.model,
299 method: change_spec.method,
300 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
301 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
302 }).pipe(function(response) {
303 return self.on_processed_onchange(response, processed);
306 console.warn("Wrong on_change format", on_change);
311 return $.Deferred().reject();
314 this.on_change_lock = this.on_change_lock.pipe(act, act);
315 return this.on_change_lock;
317 on_processed_onchange: function(response, processed) {
319 var result = response;
321 for (var f in result.value) {
322 var field = this.fields[f];
323 // If field is not defined in the view, just ignore it
325 var value = result.value[f];
326 processed.push(field.name);
327 if (field.get_value() != value) {
328 field.set_value(value);
330 if (_.indexOf(processed, field.name) < 0) {
331 this.do_onchange(field, processed);
336 this.on_form_changed();
338 if (!_.isEmpty(result.warning)) {
339 $(QWeb.render("DialogWarning", result.warning)).dialog({
343 $(this).dialog("close");
351 return $.Deferred().resolve();
354 return $.Deferred().reject();
357 on_button_save: function() {
359 return this.do_save().then(function(result) {
360 self.do_prev_view(result.created);
363 on_button_cancel: function() {
364 return this.do_prev_view();
366 on_button_new: function() {
368 var def = $.Deferred();
369 $.when(this.has_been_loaded).then(function() {
370 if (self.can_be_discarded()) {
371 var keys = _.keys(self.fields_view.fields);
373 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
377 self.on_record_loaded({}).then(function() {
383 return def.promise();
385 can_be_discarded: function() {
386 return true; // FIXME: Disabled until the page view and button refactoring is done
387 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
390 * Triggers saving the form's record. Chooses between creating a new
391 * record or saving an existing one depending on whether the record
392 * already has an id property.
394 * @param {Function} success callback on save success
395 * @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)
397 do_save: function(success, prepend_on_create) {
399 var action = function() {
401 if (!self.initial_mutating_lock.isResolved() && !self.initial_mutating_lock.isRejected())
403 var form_invalid = false,
405 first_invalid_field = null;
406 for (var f in self.fields) {
411 if (!first_invalid_field) {
412 first_invalid_field = f;
414 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
415 // Special case 'id' field, do not save this field
416 // on 'create' : save all non readonly fields
417 // on 'edit' : save non readonly modified fields
418 values[f.name] = f.get_value();
422 first_invalid_field.focus();
424 return $.Deferred().reject();
427 if (!self.datarecord.id) {
428 openerp.log("FormView(", self, ") : About to create", values);
429 save_deferral = self.dataset.create(values).pipe(function(r) {
430 return self.on_created(r, undefined, prepend_on_create);
432 } else if (_.isEmpty(values)) {
433 openerp.log("FormView(", self, ") : Nothing to save");
434 save_deferral = $.Deferred().resolve({}).promise();
436 openerp.log("FormView(", self, ") : About to save", values);
437 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
438 return self.on_saved(r);
441 return save_deferral.then(success);
445 return $.Deferred().reject();
448 this.mutating_lock = this.mutating_lock.pipe(action, action);
449 return this.mutating_lock;
451 on_invalid: function() {
453 _.each(this.fields, function(f) {
455 msg += "<li>" + f.string + "</li>";
459 this.do_warn("The following fields are invalid :", msg);
461 on_saved: function(r, success) {
463 // should not happen in the server, but may happen for internal purpose
464 return $.Deferred().reject();
466 return $.when(this.reload()).pipe(function () {
467 return $.when(r).then(success); }, null);
471 * Updates the form' dataset to contain the new record:
473 * * Adds the newly created record to the current dataset (at the end by
475 * * Selects that record (sets the dataset's index to point to the new
477 * * Updates the pager and sidebar displays
480 * @param {Function} success callback to execute after having updated the dataset
481 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
483 on_created: function(r, success, prepend_on_create) {
485 // should not happen in the server, but may happen for internal purpose
486 return $.Deferred().reject();
488 this.datarecord.id = r.result;
489 if (!prepend_on_create) {
490 this.dataset.ids.push(this.datarecord.id);
491 this.dataset.index = this.dataset.ids.length - 1;
493 this.dataset.ids.unshift(this.datarecord.id);
494 this.dataset.index = 0;
496 this.do_update_pager();
498 this.sidebar.attachments.do_update();
500 openerp.log("The record has been created with id #" + this.datarecord.id);
502 return $.when(_.extend(r, {created: true})).then(success);
505 on_action: function (action) {
506 console.debug('Executing action', action);
510 var act = function() {
511 if (self.dataset.index == null || self.dataset.index < 0) {
512 return $.when(self.on_button_new());
514 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
517 this.reload_lock = this.reload_lock.pipe(act, act);
518 return this.reload_lock;
520 get_fields_values: function() {
522 _.each(this.fields, function(value, key) {
523 var val = value.get_value();
528 get_selected_ids: function() {
529 var id = this.dataset.ids[this.dataset.index];
530 return id ? [id] : [];
532 recursive_save: function() {
534 return $.when(this.do_save()).pipe(function(res) {
535 if (self.dataset.parent_view)
536 return self.dataset.parent_view.recursive_save();
539 is_dirty: function() {
540 return _.any(this.fields, function (value) {
541 return value.is_dirty();
544 is_interactible_record: function() {
545 var id = this.datarecord.id;
547 if (this.options.not_interactible_on_create)
549 } else if (typeof(id) === "string") {
550 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
555 sidebar_context: function () {
556 return this.do_save().pipe($.proxy(this, 'get_fields_values'));
559 openerp.web.FormDialog = openerp.web.Dialog.extend({
560 init: function(parent, options, view_id, dataset) {
561 this._super(parent, options);
562 this.dataset = dataset;
563 this.view_id = view_id;
568 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
572 this.form.appendTo(this.$element);
573 this.form.on_created.add_last(this.on_form_dialog_saved);
574 this.form.on_saved.add_last(this.on_form_dialog_saved);
577 select_id: function(id) {
578 if (this.form.dataset.select_id(id)) {
579 return this.form.do_show();
581 this.do_warn("Could not find id in dataset");
582 return $.Deferred().reject();
585 on_form_dialog_saved: function(r) {
591 openerp.web.form = {};
593 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
594 init: function(parent, form_view) {
595 var $section = parent.add_section(_t('Attachments'), 'attachments');
596 this.$div = $('<div class="oe-sidebar-attachments"></div>');
597 $section.append(this.$div);
599 this._super(parent, $section.attr('id'));
600 this.view = form_view;
602 do_update: function() {
603 if (!this.view.datarecord.id) {
604 this.on_attachments_loaded([]);
606 (new openerp.web.DataSetSearch(
607 this, 'ir.attachment', this.view.dataset.get_context(),
609 ['res_model', '=', this.view.dataset.model],
610 ['res_id', '=', this.view.datarecord.id],
611 ['type', 'in', ['binary', 'url']]
612 ])).read_slice(['name', 'url', 'type'], {}, this.on_attachments_loaded);
615 on_attachments_loaded: function(attachments) {
616 this.attachments = attachments;
617 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
618 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
619 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
621 on_attachment_changed: function(e) {
622 window[this.element_id + '_iframe'] = this.do_update;
623 var $e = $(e.target);
624 if ($e.val() != '') {
625 this.$element.find('form.oe-binary-form').submit();
626 $e.parent().find('input[type=file]').attr('disabled', 'true');
627 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
630 on_attachment_delete: function(e) {
631 var self = this, $e = $(e.currentTarget);
632 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
633 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
634 this.rpc('/web/dataset/unlink', {
635 model: 'ir.attachment',
636 ids: [parseInt($e.attr('data-id'))]
638 $e.parent().remove();
639 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
645 openerp.web.form.compute_domain = function(expr, fields) {
647 for (var i = expr.length - 1; i >= 0; i--) {
649 if (ex.length == 1) {
650 var top = stack.pop();
653 stack.push(stack.pop() || top);
656 stack.push(stack.pop() && top);
662 throw new Error('Unknown domain operator ' + ex);
666 var field = fields[ex[0]];
668 throw new Error("Domain references unknown field : " + ex[0]);
670 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
674 switch (op.toLowerCase()) {
677 stack.push(field_value == val);
681 stack.push(field_value != val);
684 stack.push(field_value < val);
687 stack.push(field_value > val);
690 stack.push(field_value <= val);
693 stack.push(field_value >= val);
696 stack.push(_(val).contains(field_value));
699 stack.push(!_(val).contains(field_value));
702 console.warn("Unsupported operator in modifiers :", op);
705 return _.all(stack, _.identity);
708 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
710 identifier_prefix: 'formview-widget-',
712 * @constructs openerp.web.form.Widget
713 * @extends openerp.web.Widget
718 init: function(view, node) {
721 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
722 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
723 this.type = this.type || node.tag;
724 this.element_name = this.element_name || this.type;
725 this.element_class = [
726 'formview', this.view.view_id, this.element_name,
727 this.view.widgets_counter++].join("_");
731 this.view.widgets[this.element_class] = this;
732 this.children = node.children;
733 this.colspan = parseInt(node.attrs.colspan || 1, 10);
734 this.decrease_max_width = 0;
736 this.string = this.string || node.attrs.string;
737 this.help = this.help || node.attrs.help;
738 this.invisible = this.modifiers['invisible'] === true;
739 this.classname = 'oe_form_' + this.type;
741 this.align = parseFloat(this.node.attrs.align);
742 if (isNaN(this.align) || this.align === 1) {
743 this.align = 'right';
744 } else if (this.align === 0) {
747 this.align = 'center';
751 this.width = this.node.attrs.width;
754 this.$element = this.view.$element.find(
755 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
757 process_modifiers: function() {
758 var compute_domain = openerp.web.form.compute_domain;
759 for (var a in this.modifiers) {
760 this[a] = compute_domain(this.modifiers[a], this.view.fields);
763 update_dom: function() {
764 this.$element.toggle(!this.invisible);
767 var template = this.template;
768 return QWeb.render(template, { "widget": this });
770 do_attach_tooltip: function(widget, trigger, options) {
771 widget = widget || this;
772 trigger = trigger || this.$element;
775 maxWidth: openerp.connection.debug ? '300px' : '200px',
776 content: function() {
777 var template = widget.template + '.tooltip';
778 if (!QWeb.has_template(template)) {
779 template = 'WidgetLabel.tooltip';
781 return QWeb.render(template, {
782 debug: openerp.connection.debug,
787 trigger.tipTip(options);
789 _build_view_fields_values: function() {
790 var a_dataset = this.view.dataset;
791 var fields_values = this.view.get_fields_values();
792 var active_id = a_dataset.ids[a_dataset.index];
793 _.extend(fields_values, {
794 active_id: active_id || false,
795 active_ids: active_id ? [active_id] : [],
796 active_model: a_dataset.model,
797 parent: a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {}
799 return fields_values;
801 _build_eval_context: function() {
802 var a_dataset = this.view.dataset;
803 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values());
806 * Builds a new context usable for operations related to fields by merging
807 * the fields'context with the action's context.
809 build_context: function() {
810 var f_context = (this.field || {}).context || {};
811 if (!!f_context.__ref) {
812 var fields_values = this._build_eval_context();
813 f_context = new openerp.web.CompoundDomain(f_context).set_eval_context(fields_values);
815 // maybe the default_get should only be used when we do a default_get?
816 var v_contexts = _.compact([this.node.attrs.default_get || null,
817 this.node.attrs.context || null]);
818 var v_context = new openerp.web.CompoundContext();
819 _.each(v_contexts, function(x) {v_context.add(x);});
820 if (_.detect(v_contexts, function(x) {return !!x.__ref;})) {
821 var fields_values = this._build_eval_context();
822 v_context.set_eval_context(fields_values);
824 // if there is a context on the node, overrides the model's context
825 var ctx = v_contexts.length > 0 ? v_context : f_context;
828 build_domain: function() {
829 var f_domain = this.field.domain || [];
830 var n_domain = this.node.attrs.domain || null;
831 // if there is a domain on the node, overrides the model's domain
832 var final_domain = n_domain !== null ? n_domain : f_domain;
833 if (!(final_domain instanceof Array)) {
834 var fields_values = this._build_eval_context();
835 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
841 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
842 template: 'WidgetFrame',
843 init: function(view, node) {
844 this._super(view, node);
845 this.columns = parseInt(node.attrs.col || 4, 10);
850 for (var i = 0; i < node.children.length; i++) {
851 var n = node.children[i];
852 if (n.tag == "newline") {
858 this.set_row_cells_with(this.table[this.table.length - 1]);
861 if (this.table.length) {
862 this.set_row_cells_with(this.table[this.table.length - 1]);
865 this.table.push(row);
870 set_row_cells_with: function(row) {
873 row_length = row.length;
874 for (var i = 0; i < row.length; i++) {
875 if (row[i].always_invisible) {
878 bypass += row[i].width === undefined ? 0 : 1;
879 max_width -= row[i].decrease_max_width;
882 var size_unit = Math.round(max_width / (this.columns - bypass)),
884 for (var i = 0; i < row.length; i++) {
886 if (w.always_invisible) {
889 colspan_sum += w.colspan;
890 if (w.width === undefined) {
891 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
893 w.width = width + '%';
897 handle_node: function(node) {
899 if (node.tag == 'field') {
900 type = this.view.fields_view.fields[node.attrs.name] || {};
901 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
902 // This way we can retain backward compatibility between addons and old clients
903 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
904 node.attrs.nolabel = '1';
907 var widget = new (this.view.registry.get_any(
908 [node.attrs.widget, type.type, node.tag])) (this.view, node);
909 if (node.tag == 'field') {
910 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
911 this.view.default_focus_field = widget;
913 if (node.attrs.nolabel != '1') {
914 var label = new (this.view.registry.get_object('label')) (this.view, node);
915 label["for"] = widget;
916 this.add_widget(label, widget.colspan + 1);
919 this.add_widget(widget);
921 add_widget: function(widget, colspan) {
922 var current_row = this.table[this.table.length - 1];
923 if (!widget.always_invisible) {
924 colspan = colspan || widget.colspan;
925 if (current_row.length && (this.x + colspan) > this.columns) {
926 current_row = this.add_row();
928 this.x += widget.colspan;
930 current_row.push(widget);
935 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
936 template: 'WidgetGroup'
939 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
940 template: 'WidgetNotebook',
941 init: function(view, node) {
942 this._super(view, node);
944 for (var i = 0; i < node.children.length; i++) {
945 var n = node.children[i];
946 if (n.tag == "page") {
947 var page = new (this.view.registry.get_object('notebookpage'))(
948 this.view, n, this, this.pages.length);
949 this.pages.push(page);
955 this._super.apply(this, arguments);
956 this.$element.find('> ul > li').each(function (index, tab_li) {
957 var page = self.pages[index],
958 id = _.uniqueId(self.element_name + '-');
959 page.element_id = id;
960 $(tab_li).find('a').attr('href', '#' + id);
962 this.$element.find('> div').each(function (index, page) {
963 page.id = self.pages[index].element_id;
965 this.$element.tabs();
966 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
967 if (openerp.connection.debug) {
968 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
969 defaultPosition: 'top'
973 do_select_first_visible_tab: function() {
974 for (var i = 0; i < this.pages.length; i++) {
975 var page = this.pages[i];
976 if (page.invisible === false) {
977 this.$element.tabs('select', page.index);
984 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
985 template: 'WidgetNotebookPage',
986 init: function(view, node, notebook, index) {
987 this.notebook = notebook;
989 this.element_name = 'page_' + index;
990 this._super(view, node);
993 this._super.apply(this, arguments);
994 this.$element_tab = this.notebook.$element.find(
995 '> ul > li:eq(' + this.index + ')');
997 update_dom: function() {
998 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
999 this.notebook.do_select_first_visible_tab();
1001 this.$element_tab.toggle(!this.invisible);
1002 this.$element.toggle(!this.invisible);
1006 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1007 template: 'WidgetSeparator',
1008 init: function(view, node) {
1009 this._super(view, node);
1010 this.orientation = node.attrs.orientation || 'horizontal';
1011 if (this.orientation === 'vertical') {
1014 this.classname += '_' + this.orientation;
1018 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1019 template: 'WidgetButton',
1020 init: function(view, node) {
1021 this._super(view, node);
1022 this.force_disabled = false;
1024 // We don't have button key bindings in the webclient
1025 this.string = this.string.replace(/_/g, '');
1027 if (node.attrs.default_focus == '1') {
1028 // TODO fme: provide enter key binding to widgets
1029 this.view.default_focus_button = this;
1033 this._super.apply(this, arguments);
1034 this.$element.find("button").click(this.on_click);
1035 if (this.help || openerp.connection.debug) {
1036 this.do_attach_tooltip();
1039 on_click: function() {
1041 this.force_disabled = true;
1042 this.check_disable();
1043 this.execute_action().always(function() {
1044 self.force_disabled = false;
1045 self.check_disable();
1049 execute_action: function() {
1051 var exec_action = function() {
1052 if (self.node.attrs.confirm) {
1053 var def = $.Deferred();
1054 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1059 self.on_confirmed().then(function() {
1062 $(this).dialog("close");
1064 Cancel: function() {
1066 $(this).dialog("close");
1070 return def.promise();
1072 return self.on_confirmed();
1075 if (!this.node.attrs.special) {
1076 return this.view.recursive_save().pipe(exec_action);
1078 return exec_action();
1081 on_confirmed: function() {
1084 var context = this.node.attrs.context;
1085 if (context && context.__ref) {
1086 context = new openerp.web.CompoundContext(context);
1087 context.set_eval_context(this._build_eval_context());
1090 return this.view.do_execute_action(
1091 _.extend({}, this.node.attrs, {context: context}),
1092 this.view.dataset, this.view.datarecord.id, function () {
1096 update_dom: function() {
1098 this.check_disable();
1100 check_disable: function() {
1101 if (this.readonly || this.force_disabled || !this.view.is_interactible_record()) {
1102 this.$element.find("button").attr("disabled", "disabled");
1103 this.$element.find("button").css("color", "grey");
1105 this.$element.find("button").removeAttr("disabled");
1106 this.$element.find("button").css("color", "");
1111 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1112 template: 'WidgetLabel',
1113 init: function(view, node) {
1114 this.element_name = 'label_' + node.attrs.name;
1116 this._super(view, node);
1118 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1119 this.template = "WidgetParagraph";
1120 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1121 // Widgets default to right-aligned, but paragraph defaults to
1123 if (isNaN(parseFloat(this.node.attrs.align))) {
1124 this.align = 'left';
1129 this.decrease_max_width = 1;
1133 render: function () {
1134 if (this['for'] && this.type !== 'label') {
1135 return QWeb.render(this.template, {widget: this['for']});
1137 // Actual label widgets should not have a false and have type label
1138 return QWeb.render(this.template, {widget: this});
1143 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1144 this.do_attach_tooltip(self['for']);
1146 this.$element.find("label").dblclick(function() {
1147 var widget = self['for'] || self;
1148 openerp.log(widget.element_class , widget);
1154 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1156 * @constructs openerp.web.form.Field
1157 * @extends openerp.web.form.Widget
1162 init: function(view, node) {
1163 this.name = node.attrs.name;
1164 this.value = undefined;
1165 view.fields[this.name] = this;
1166 view.fields_order.push(this.name);
1167 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1168 this.element_name = "field_" + this.name + "_" + this.type;
1170 this._super(view, node);
1172 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1175 this.field = view.fields_view.fields[node.attrs.name] || {};
1176 this.string = node.attrs.string || this.field.string;
1177 this.help = node.attrs.help || this.field.help;
1178 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1179 this.readonly = this.modifiers['readonly'] === true;
1180 this.required = this.modifiers['required'] === true;
1181 this.invalid = this.dirty = false;
1183 this.classname = 'oe_form_field_' + this.type;
1186 this._super.apply(this, arguments);
1187 if (this.field.translate) {
1188 this.view.translatable_fields.push(this);
1189 this.$element.find('.oe_field_translate').click(this.on_translate);
1191 if (this.nolabel && openerp.connection.debug) {
1192 this.do_attach_tooltip(this, this.$element, {
1193 defaultPosition: 'top'
1197 set_value: function(value) {
1199 this.invalid = false;
1201 this.on_value_changed();
1203 set_value_from_ui: function() {
1204 this.on_value_changed();
1206 on_value_changed: function() {
1208 on_translate: function() {
1209 this.view.open_translate_dialog(this);
1211 get_value: function() {
1214 is_valid: function() {
1215 return !this.invalid;
1217 is_dirty: function() {
1218 return this.dirty && !this.readonly;
1220 get_on_change_value: function() {
1221 return this.get_value();
1223 update_dom: function() {
1224 this._super.apply(this, arguments);
1225 if (this.field.translate) {
1226 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1228 if (!this.disable_utility_classes) {
1229 this.$element.toggleClass('disabled', this.readonly);
1230 this.$element.toggleClass('required', this.required);
1231 if (this.view.show_invalid) {
1232 this.$element.toggleClass('invalid', !this.is_valid());
1236 on_ui_change: function() {
1239 if (this.is_valid()) {
1240 this.set_value_from_ui();
1241 this.view.do_onchange(this);
1242 this.view.on_form_changed();
1247 validate: function() {
1248 this.invalid = false;
1257 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1258 template: 'FieldChar',
1259 init: function (view, node) {
1260 this._super(view, node);
1261 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1264 this._super.apply(this, arguments);
1265 this.$element.find('input').change(this.on_ui_change);
1267 set_value: function(value) {
1268 this._super.apply(this, arguments);
1269 var show_value = openerp.web.format_value(value, this, '');
1270 this.$element.find('input').val(show_value);
1273 update_dom: function() {
1274 this._super.apply(this, arguments);
1275 this.$element.find('input').attr('disabled', this.readonly);
1277 set_value_from_ui: function() {
1278 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1281 validate: function() {
1282 this.invalid = false;
1284 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1285 this.invalid = this.required && value === '';
1287 this.invalid = true;
1291 this.$element.find('input').focus();
1295 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1296 template: 'FieldEmail',
1298 this._super.apply(this, arguments);
1299 this.$element.find('button').click(this.on_button_clicked);
1301 on_button_clicked: function() {
1302 if (!this.value || !this.is_valid()) {
1303 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1305 location.href = 'mailto:' + this.value;
1310 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1311 template: 'FieldUrl',
1313 this._super.apply(this, arguments);
1314 this.$element.find('button').click(this.on_button_clicked);
1316 on_button_clicked: function() {
1318 this.do_warn("Resource error", "This resource is empty");
1320 window.open(this.value);
1325 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1326 init: function (view, node) {
1327 this._super(view, node);
1328 if (node.attrs.digits) {
1329 this.parse_digits(node.attrs.digits);
1331 this.digits = view.fields_view.fields[node.attrs.name].digits;
1334 parse_digits: function (digits_attr) {
1335 // could use a Python parser instead.
1336 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1337 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1339 set_value: function(value) {
1340 if (value === false || value === undefined) {
1341 // As in GTK client, floats default to 0
1344 this._super.apply(this, [value]);
1348 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1349 template: "web.datetimepicker",
1350 jqueryui_object: 'datetimepicker',
1351 type_of_date: "datetime",
1352 init: function(parent) {
1353 this._super(parent);
1354 this.name = parent.name;
1358 this.$input = this.$element.find('input.oe_datepicker_master');
1359 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1360 this.$input.change(this.on_change);
1362 onSelect: this.on_picker_select,
1366 showButtonPanel: true
1368 this.$element.find('img.oe_datepicker_trigger').click(function() {
1369 if (!self.readonly) {
1370 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1371 self.$input_picker.show();
1372 self.picker('show');
1373 self.$input_picker.hide();
1376 this.set_readonly(false);
1379 picker: function() {
1380 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1382 on_picker_select: function(text, instance) {
1383 var date = this.picker('getDate');
1384 this.$input.val(date ? this.format_client(date) : '').change();
1386 set_value: function(value) {
1388 this.$input.val(value ? this.format_client(value) : '');
1390 get_value: function() {
1393 set_value_from_ui: function() {
1394 var value = this.$input.val() || false;
1395 this.value = this.parse_client(value);
1397 set_readonly: function(readonly) {
1398 this.readonly = readonly;
1399 this.$input.attr('disabled', this.readonly);
1400 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1402 is_valid: function(required) {
1403 var value = this.$input.val();
1408 this.parse_client(value);
1416 this.$input.focus();
1418 parse_client: function(v) {
1419 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1421 format_client: function(v) {
1422 return openerp.web.format_value(v, {"widget": this.type_of_date});
1424 on_change: function() {
1425 if (this.is_valid()) {
1426 this.set_value_from_ui();
1431 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1432 jqueryui_object: 'datepicker',
1433 type_of_date: "date"
1436 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1437 template: "EmptyComponent",
1438 build_widget: function() {
1439 return new openerp.web.DateTimeWidget(this);
1443 this._super.apply(this, arguments);
1444 this.datewidget = this.build_widget();
1445 this.datewidget.on_change.add_last(this.on_ui_change);
1446 this.datewidget.appendTo(this.$element);
1448 set_value: function(value) {
1450 this.datewidget.set_value(value);
1452 get_value: function() {
1453 return this.datewidget.get_value();
1455 update_dom: function() {
1456 this._super.apply(this, arguments);
1457 this.datewidget.set_readonly(this.readonly);
1459 validate: function() {
1460 this.invalid = !this.datewidget.is_valid(this.required);
1463 this.datewidget.focus();
1467 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1468 build_widget: function() {
1469 return new openerp.web.DateWidget(this);
1473 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1474 template: 'FieldText',
1476 this._super.apply(this, arguments);
1477 this.$element.find('textarea').change(this.on_ui_change);
1479 set_value: function(value) {
1480 this._super.apply(this, arguments);
1481 var show_value = openerp.web.format_value(value, this, '');
1482 this.$element.find('textarea').val(show_value);
1484 update_dom: function() {
1485 this._super.apply(this, arguments);
1486 this.$element.find('textarea').attr('disabled', this.readonly);
1488 set_value_from_ui: function() {
1489 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1492 validate: function() {
1493 this.invalid = false;
1495 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1496 this.invalid = this.required && value === '';
1498 this.invalid = true;
1502 this.$element.find('textarea').focus();
1506 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1507 template: 'FieldBoolean',
1510 this._super.apply(this, arguments);
1511 this.$element.find('input').click(self.on_ui_change);
1513 set_value: function(value) {
1514 this._super.apply(this, arguments);
1515 this.$element.find('input')[0].checked = value;
1517 set_value_from_ui: function() {
1518 this.value = this.$element.find('input').is(':checked');
1521 update_dom: function() {
1522 this._super.apply(this, arguments);
1523 this.$element.find('input').attr('disabled', this.readonly);
1526 this.$element.find('input').focus();
1530 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1531 template: 'FieldProgressBar',
1533 this._super.apply(this, arguments);
1534 this.$element.find('div').progressbar({
1536 disabled: this.readonly
1539 set_value: function(value) {
1540 this._super.apply(this, arguments);
1541 var show_value = Number(value);
1542 if (isNaN(show_value)) {
1545 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1549 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1550 // to replace view editor
1553 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1554 template: 'FieldSelection',
1555 init: function(view, node) {
1557 this._super(view, node);
1558 this.values = _.clone(this.field.selection);
1559 _.each(this.values, function(v, i) {
1560 if (v[0] === false && v[1] === '') {
1561 self.values.splice(i, 1);
1564 this.values.unshift([false, '']);
1567 // Flag indicating whether we're in an event chain containing a change
1568 // event on the select, in order to know what to do on keyup[RETURN]:
1569 // * If the user presses [RETURN] as part of changing the value of a
1570 // selection, we should just let the value change and not let the
1571 // event broadcast further (e.g. to validating the current state of
1572 // the form in editable list view, which would lead to saving the
1573 // current row or switching to the next one)
1574 // * If the user presses [RETURN] with a select closed (side-effect:
1575 // also if the user opened the select and pressed [RETURN] without
1576 // changing the selected value), takes the action as validating the
1578 var ischanging = false;
1579 this._super.apply(this, arguments);
1580 this.$element.find('select')
1581 .change(this.on_ui_change)
1582 .change(function () { ischanging = true; })
1583 .click(function () { ischanging = false; })
1584 .keyup(function (e) {
1585 if (e.which !== 13 || !ischanging) { return; }
1586 e.stopPropagation();
1590 set_value: function(value) {
1591 value = value === null ? false : value;
1592 value = value instanceof Array ? value[0] : value;
1595 for (var i = 0, ii = this.values.length; i < ii; i++) {
1596 if (this.values[i][0] === value) index = i;
1598 this.$element.find('select')[0].selectedIndex = index;
1600 set_value_from_ui: function() {
1601 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1604 update_dom: function() {
1605 this._super.apply(this, arguments);
1606 this.$element.find('select').attr('disabled', this.readonly);
1608 validate: function() {
1609 var value = this.values[this.$element.find('select')[0].selectedIndex];
1610 this.invalid = !(value && !(this.required && value[0] === false));
1613 this.$element.find('select').focus();
1617 // jquery autocomplete tweak to allow html
1619 var proto = $.ui.autocomplete.prototype,
1620 initSource = proto._initSource;
1622 function filter( array, term ) {
1623 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1624 return $.grep( array, function(value) {
1625 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1630 _initSource: function() {
1631 if ( this.options.html && $.isArray(this.options.source) ) {
1632 this.source = function( request, response ) {
1633 response( filter( this.options.source, request.term ) );
1636 initSource.call( this );
1640 _renderItem: function( ul, item) {
1641 return $( "<li></li>" )
1642 .data( "item.autocomplete", item )
1643 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1649 openerp.web.form.dialog = function(content, options) {
1650 options = _.extend({
1657 options.autoOpen = true;
1658 var dialog = new openerp.web.Dialog(null, options);
1659 dialog.$dialog = $(content).dialog(dialog.dialog_options);
1660 return dialog.$dialog;
1663 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1664 template: 'FieldMany2One',
1665 init: function(view, node) {
1666 this._super(view, node);
1669 this.cm_id = _.uniqueId('m2o_cm_');
1670 this.last_search = [];
1671 this.tmp_value = undefined;
1676 this.$input = this.$element.find("input");
1677 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1678 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1681 var init_context_menu_def = $.Deferred().then(function(e) {
1682 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1683 rdataset.call("get", ['action', 'client_action_relate',
1684 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1685 .then(function(result) {
1686 self.related_entries = result;
1688 var $cmenu = $("#" + self.cm_id);
1689 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1691 bindings[self.cm_id + "_search"] = function() {
1692 self._search_create_popup("search");
1694 bindings[self.cm_id + "_create"] = function() {
1695 self._search_create_popup("form");
1697 bindings[self.cm_id + "_open"] = function() {
1701 var pop = new openerp.web.form.FormOpenPopup(self.view);
1702 pop.show_element(self.field.relation, self.value[0],self.build_context(), {});
1703 pop.on_write_completed.add_last(function() {
1704 self.set_value(self.value[0]);
1707 _.each(_.range(self.related_entries.length), function(i) {
1708 bindings[self.cm_id + "_related_" + i] = function() {
1709 self.open_related(self.related_entries[i]);
1712 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1713 bindings: bindings, itemStyle: {"color": ""},
1714 onContextMenu: function() {
1716 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1718 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1720 if (!self.readonly) {
1721 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1723 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1726 }, menuStyle: {width: "200px"}
1728 setTimeout(function() {self.$menu_btn.trigger(e);}, 0);
1731 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1732 this.$menu_btn.bind('contextmenu', ctx_callback);
1733 this.$menu_btn.click(ctx_callback);
1735 // some behavior for input
1736 this.$input.keyup(function() {
1737 if (self.$input.val() === "") {
1738 self._change_int_value(null);
1739 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1740 self._change_int_value(undefined);
1743 this.$drop_down.click(function() {
1746 if (self.$input.autocomplete("widget").is(":visible")) {
1747 self.$input.autocomplete("close");
1750 self.$input.autocomplete("search", "");
1752 self.$input.autocomplete("search");
1754 self.$input.focus();
1757 var anyoneLoosesFocus = function() {
1758 if (!self.$input.is(":focus") &&
1759 !self.$input.autocomplete("widget").is(":visible") &&
1761 if (self.value === undefined && self.last_search.length > 0) {
1762 self._change_int_ext_value(self.last_search[0]);
1764 self._change_int_ext_value(null);
1768 this.$input.focusout(anyoneLoosesFocus);
1770 var isSelecting = false;
1772 this.$input.autocomplete({
1773 source: function(req, resp) { self.get_search_result(req, resp); },
1774 select: function(event, ui) {
1778 self._change_int_value([item.id, item.name]);
1779 } else if (item.action) {
1780 self._change_int_value(undefined);
1785 focus: function(e, ui) {
1789 close: anyoneLoosesFocus,
1793 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1794 this.$input.keyup(function(e) {
1795 if (e.which === 13) {
1797 e.stopPropagation();
1799 isSelecting = false;
1802 // autocomplete component content handling
1803 get_search_result: function(request, response) {
1804 var search_val = request.term;
1807 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1809 dataset.name_search(search_val, self.build_domain(), 'ilike',
1810 this.limit + 1, function(data) {
1811 self.last_search = data;
1812 // possible selections for the m2o
1813 var values = _.map(data, function(x) {
1814 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1817 // search more... if more results that max
1818 if (values.length > self.limit) {
1819 values = values.slice(0, self.limit);
1820 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
1821 dataset.name_search(search_val, self.build_domain(), 'ilike'
1822 , false, function(data) {
1823 self._change_int_value(null);
1824 self._search_create_popup("search", data);
1829 var raw_result = _(data.result).map(function(x) {return x[1];});
1830 if (search_val.length > 0 &&
1831 !_.include(raw_result, search_val) &&
1832 (!self.value || search_val !== self.value[1])) {
1833 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
1834 $('<span />').text(search_val).html()), action: function() {
1835 self._quick_create(search_val);
1839 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
1840 self._change_int_value(null);
1841 self._search_create_popup("form", undefined, {"default_name": search_val});
1847 _quick_create: function(name) {
1849 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1850 dataset.name_create(name, function(data) {
1851 self._change_int_ext_value(data);
1852 }).fail(function(error, event) {
1853 event.preventDefault();
1854 self._change_int_value(null);
1855 self._search_create_popup("form", undefined, {"default_name": name});
1858 // all search/create popup handling
1859 _search_create_popup: function(view, ids, context) {
1861 var pop = new openerp.web.form.SelectCreatePopup(this);
1862 pop.select_element(self.field.relation,{
1863 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1865 disable_multiple_selection: true
1866 }, self.build_domain(),
1867 new openerp.web.CompoundContext(self.build_context(), context || {}));
1868 pop.on_select_elements.add(function(element_ids) {
1869 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1870 dataset.name_get([element_ids[0]], function(data) {
1871 self._change_int_ext_value(data[0]);
1875 _change_int_ext_value: function(value) {
1876 this._change_int_value(value);
1877 this.$input.val(this.value ? this.value[1] : "");
1879 _change_int_value: function(value) {
1881 var back_orig_value = this.original_value;
1882 if (this.value === null || this.value) {
1883 this.original_value = this.value;
1885 if (back_orig_value === undefined) { // first use after a set_value()
1888 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1889 !== (this.value ? this.value[0] : null))) {
1890 this.on_ui_change();
1893 set_value: function(value) {
1894 value = value || null;
1895 this.invalid = false;
1897 this.tmp_value = value;
1899 self.on_value_changed();
1900 var real_set_value = function(rval) {
1901 self.tmp_value = undefined;
1903 self.original_value = undefined;
1904 self._change_int_ext_value(rval);
1906 if (value && !(value instanceof Array)) {
1907 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1908 dataset.name_get([value], function(data) {
1909 real_set_value(data[0]);
1910 }).fail(function() {self.tmp_value = undefined;});
1912 setTimeout(function() {real_set_value(value);}, 0);
1915 get_value: function() {
1916 if (this.tmp_value !== undefined) {
1917 if (this.tmp_value instanceof Array) {
1918 return this.tmp_value[0];
1920 return this.tmp_value ? this.tmp_value : false;
1922 if (this.value === undefined)
1923 return this.original_value ? this.original_value[0] : false;
1924 return this.value ? this.value[0] : false;
1926 validate: function() {
1927 this.invalid = false;
1928 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1930 this.invalid = this.required;
1933 open_related: function(related) {
1937 var additional_context = {
1938 active_id: self.value[0],
1939 active_ids: [self.value[0]],
1940 active_model: self.field.relation
1942 self.rpc("/web/action/load", {
1943 action_id: related[2].id,
1944 context: additional_context
1945 }, function(result) {
1946 result.result.context = _.extend(result.result.context || {}, additional_context);
1947 self.do_action(result.result);
1950 focus: function () {
1951 this.$input.focus();
1953 update_dom: function() {
1954 this._super.apply(this, arguments);
1955 this.$input.attr('disabled', this.readonly);
1960 # Values: (0, 0, { fields }) create
1961 # (1, ID, { fields }) update
1962 # (2, ID) remove (delete)
1963 # (3, ID) unlink one (target id or target of relation)
1965 # (5) unlink all (only valid for one2many)
1970 'create': function (values) {
1971 return [commands.CREATE, false, values];
1973 // (1, id, {values})
1975 'update': function (id, values) {
1976 return [commands.UPDATE, id, values];
1980 'delete': function (id) {
1981 return [commands.DELETE, id, false];
1983 // (3, id[, _]) removes relation, but not linked record itself
1985 'forget': function (id) {
1986 return [commands.FORGET, id, false];
1990 'link_to': function (id) {
1991 return [commands.LINK_TO, id, false];
1995 'delete_all': function () {
1996 return [5, false, false];
1998 // (6, _, ids) replaces all linked records with provided ids
2000 'replace_with': function (ids) {
2001 return [6, false, ids];
2004 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2005 template: 'FieldOne2Many',
2006 multi_selection: false,
2007 init: function(view, node) {
2008 this._super(view, node);
2009 this.is_loaded = $.Deferred();
2010 this.initial_is_loaded = this.is_loaded;
2011 this.is_setted = $.Deferred();
2012 this.form_last_update = $.Deferred();
2013 this.init_form_last_update = this.form_last_update;
2014 this.disable_utility_classes = true;
2017 this._super.apply(this, arguments);
2021 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2022 this.dataset.o2m = this;
2023 this.dataset.parent_view = this.view;
2024 this.dataset.on_change.add_last(function() {
2025 self.on_ui_change();
2028 this.is_setted.then(function() {
2032 is_readonly: function() {
2033 return this.readonly || this.force_readonly;
2035 load_views: function() {
2038 var modes = this.node.attrs.mode;
2039 modes = !!modes ? modes.split(",") : ["tree"];
2041 _.each(modes, function(mode) {
2044 view_type: mode == "tree" ? "list" : mode,
2045 options: { sidebar : false }
2047 if (self.field.views && self.field.views[mode]) {
2048 view.embedded_view = self.field.views[mode];
2050 if(view.view_type === "list") {
2051 view.options.selectable = self.multi_selection;
2052 if (self.is_readonly()) {
2053 view.options.addable = null;
2054 view.options.deletable = null;
2056 } else if (view.view_type === "form") {
2057 if (self.is_readonly()) {
2058 view.view_type = 'page';
2060 view.options.not_interactible_on_create = true;
2066 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views);
2067 this.viewmanager.template = 'One2Many.viewmanager';
2068 this.viewmanager.registry = openerp.web.views.clone({
2069 list: 'openerp.web.form.One2ManyListView',
2070 form: 'openerp.web.FormView',
2071 page: 'openerp.web.PageView'
2073 var once = $.Deferred().then(function() {
2074 self.init_form_last_update.resolve();
2076 var def = $.Deferred().then(function() {
2077 self.initial_is_loaded.resolve();
2079 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2080 if (view_type == "list") {
2081 controller.o2m = self;
2082 if (self.is_readonly())
2083 controller.set_editable(false);
2084 } else if (view_type == "form" || view_type == 'page') {
2085 if (view_type == 'page') {
2086 controller.$element.find(".oe_form_buttons").hide();
2088 controller.on_record_loaded.add_last(function() {
2091 controller.on_pager_action.add_first(function() {
2092 self.save_any_view();
2094 controller.$element.find(".oe_form_button_save").hide();
2095 } else if (view_type == "graph") {
2096 self.reload_current_view()
2100 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2101 $.when(self.save_any_view()).then(function() {
2102 if(n_mode === "list")
2103 setTimeout(function() {self.reload_current_view();}, 0);
2106 this.is_setted.then(function() {
2107 setTimeout(function () {
2108 self.viewmanager.appendTo(self.$element);
2113 reload_current_view: function() {
2115 return self.is_loaded = self.is_loaded.pipe(function() {
2116 var active_view = self.viewmanager.active_view;
2117 var view = self.viewmanager.views[active_view].controller;
2118 if(active_view === "list") {
2119 return view.reload_content();
2120 } else if (active_view === "form" || active_view === 'page') {
2121 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2122 self.dataset.index = 0;
2124 var act = function() {
2125 return view.do_show();
2127 self.form_last_update = self.form_last_update.pipe(act, act);
2128 return self.form_last_update;
2129 } else if (active_view === "graph") {
2130 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2134 set_value: function(value) {
2135 value = value || [];
2137 this.dataset.reset_ids([]);
2138 if(value.length >= 1 && value[0] instanceof Array) {
2140 _.each(value, function(command) {
2141 var obj = {values: command[2]};
2142 switch (command[0]) {
2143 case commands.CREATE:
2144 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2146 self.dataset.to_create.push(obj);
2147 self.dataset.cache.push(_.clone(obj));
2150 case commands.UPDATE:
2151 obj['id'] = command[1];
2152 self.dataset.to_write.push(obj);
2153 self.dataset.cache.push(_.clone(obj));
2156 case commands.DELETE:
2157 self.dataset.to_delete.push({id: command[1]});
2159 case commands.LINK_TO:
2160 ids.push(command[1]);
2162 case commands.DELETE_ALL:
2163 self.dataset.delete_all = true;
2168 this.dataset.set_ids(ids);
2169 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2171 this.dataset.delete_all = true;
2172 _.each(value, function(command) {
2173 var obj = {values: command};
2174 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2176 self.dataset.to_create.push(obj);
2177 self.dataset.cache.push(_.clone(obj));
2181 this.dataset.set_ids(ids);
2184 this.dataset.reset_ids(value);
2186 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2187 this.dataset.index = 0;
2189 self.is_setted.resolve();
2190 return self.reload_current_view();
2192 get_value: function() {
2196 this.save_any_view();
2197 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2198 val = val.concat(_.map(this.dataset.ids, function(id) {
2199 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2201 return commands.create(alter_order.values);
2203 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2205 return commands.update(alter_order.id, alter_order.values);
2207 return commands.link_to(id);
2209 return val.concat(_.map(
2210 this.dataset.to_delete, function(x) {
2211 return commands['delete'](x.id);}));
2213 save_any_view: function() {
2214 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2215 this.viewmanager.views[this.viewmanager.active_view] &&
2216 this.viewmanager.views[this.viewmanager.active_view].controller) {
2217 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2218 if (this.viewmanager.active_view === "form") {
2219 var res = $.when(view.do_save());
2220 // it seems line there are some cases when this happens
2221 /*if (!res.isResolved() && !res.isRejected()) {
2222 console.warn("Asynchronous get_value() is not supported in form view.");
2225 } else if (this.viewmanager.active_view === "list") {
2226 var res = $.when(view.ensure_saved());
2227 // it seems line there are some cases when this happens
2228 /*if (!res.isResolved() && !res.isRejected()) {
2229 console.warn("Asynchronous get_value() is not supported in list view.");
2236 is_valid: function() {
2238 return this._super();
2240 validate: function() {
2241 this.invalid = false;
2242 if (!this.viewmanager.views[this.viewmanager.active_view])
2244 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2245 if (this.viewmanager.active_view === "form") {
2246 for (var f in view.fields) {
2248 if (!f.is_valid()) {
2249 this.invalid = true;
2255 is_dirty: function() {
2256 this.save_any_view();
2257 return this._super();
2259 update_dom: function() {
2260 this._super.apply(this, arguments);
2262 if (this.previous_readonly !== this.readonly) {
2263 this.previous_readonly = this.readonly;
2264 if (this.viewmanager) {
2265 this.is_loaded = this.is_loaded.pipe(function() {
2266 self.viewmanager.stop();
2267 return $.when(self.load_views()).then(function() {
2268 self.reload_current_view();
2276 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2277 get_context: function() {
2278 this.context = this.o2m.build_context();
2279 return this.context;
2283 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2284 _template: 'One2Many.listview',
2285 do_add_record: function () {
2286 if (this.options.editable) {
2287 this._super.apply(this, arguments);
2290 var pop = new openerp.web.form.SelectCreatePopup(this);
2291 pop.on_default_get.add(self.dataset.on_default_get);
2292 pop.select_element(self.o2m.field.relation,{
2293 initial_view: "form",
2294 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2295 create_function: function(data, callback, error_callback) {
2296 return self.o2m.dataset.create(data).then(function(r) {
2297 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2298 self.o2m.dataset.on_change();
2299 }).then(callback, error_callback);
2301 read_function: function() {
2302 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2304 parent_view: self.o2m.view,
2305 form_view_options: {'not_interactible_on_create':true}
2306 }, self.o2m.build_domain(), self.o2m.build_context());
2307 pop.on_select_elements.add_last(function() {
2308 self.o2m.reload_current_view();
2312 do_activate_record: function(index, id) {
2314 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2315 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(),{
2317 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2318 parent_view: self.o2m.view,
2319 read_function: function() {
2320 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2322 form_view_options: {'not_interactible_on_create':true},
2323 readonly: self.o2m.is_readonly()
2325 pop.on_write.add(function(id, data) {
2326 self.o2m.dataset.write(id, data, {}, function(r) {
2327 self.o2m.reload_current_view();
2333 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2334 template: 'FieldMany2Many',
2335 multi_selection: false,
2336 init: function(view, node) {
2337 this._super(view, node);
2338 this.list_id = _.uniqueId("many2many");
2339 this.is_loaded = $.Deferred();
2340 this.initial_is_loaded = this.is_loaded;
2341 this.is_setted = $.Deferred();
2344 this._super.apply(this, arguments);
2348 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2349 this.dataset.m2m = this;
2350 this.dataset.on_unlink.add_last(function(ids) {
2351 self.on_ui_change();
2354 this.is_setted.then(function() {
2358 set_value: function(value) {
2359 value = value || [];
2360 if (value.length >= 1 && value[0] instanceof Array) {
2361 value = value[0][2];
2364 this.dataset.set_ids(value);
2366 self.reload_content();
2367 this.is_setted.resolve();
2369 get_value: function() {
2370 return [commands.replace_with(this.dataset.ids)];
2372 validate: function() {
2373 this.invalid = false;
2375 is_readonly: function() {
2376 return this.readonly || this.force_readonly;
2378 load_view: function() {
2380 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2381 'addable': self.is_readonly() ? null : 'Add',
2382 'deletable': self.is_readonly() ? false : true,
2383 'selectable': self.multi_selection
2385 var embedded = (this.field.views || {}).tree;
2387 this.list_view.set_embedded_view(embedded);
2389 this.list_view.m2m_field = this;
2390 var loaded = $.Deferred();
2391 this.list_view.on_loaded.add_last(function() {
2392 self.initial_is_loaded.resolve();
2395 setTimeout(function () {
2396 self.list_view.appendTo($("#" + self.list_id));
2400 reload_content: function() {
2402 this.is_loaded = this.is_loaded.pipe(function() {
2403 return self.list_view.reload_content();
2406 update_dom: function() {
2407 this._super.apply(this, arguments);
2409 if (this.previous_readonly !== this.readonly) {
2410 this.previous_readonly = this.readonly;
2411 if (this.list_view) {
2412 this.is_loaded = this.is_loaded.pipe(function() {
2413 self.list_view.stop();
2414 return $.when(self.load_view()).then(function() {
2415 self.reload_content();
2423 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2424 get_context: function() {
2425 this.context = this.m2m.build_context();
2426 return this.context;
2432 * @extends openerp.web.ListView
2434 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2435 do_add_record: function () {
2436 var pop = new openerp.web.form.SelectCreatePopup(this);
2437 pop.select_element(this.model, {},
2438 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2439 this.m2m_field.build_context());
2441 pop.on_select_elements.add(function(element_ids) {
2442 _.each(element_ids, function(element_id) {
2443 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2444 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2445 self.m2m_field.on_ui_change();
2446 self.reload_content();
2451 do_activate_record: function(index, id) {
2453 var pop = new openerp.web.form.FormOpenPopup(this);
2454 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2455 readonly: this.widget_parent.is_readonly()
2457 pop.on_write_completed.add_last(function() {
2458 self.reload_content();
2465 * @extends openerp.web.OldWidget
2467 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2468 identifier_prefix: "selectcreatepopup",
2469 template: "SelectCreatePopup",
2473 * - initial_view: form or search (default search)
2474 * - disable_multiple_selection
2475 * - alternative_form_view
2476 * - create_function (defaults to a naive saving behavior)
2478 * - form_view_options
2479 * - list_view_options
2482 select_element: function(model, options, domain, context) {
2485 this.domain = domain || [];
2486 this.context = context || {};
2487 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2488 return self.create_row.apply(self, arguments);
2489 }, read_function: null});
2490 this.initial_ids = this.options.initial_ids;
2491 this.created_elements = [];
2492 this.render_element();
2493 openerp.web.form.dialog(this.$element, {close:function() {
2501 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2503 this.dataset.create_function = function() {
2504 return self.options.create_function.apply(null, arguments).then(function(r) {
2505 self.created_elements.push(r.result);
2508 this.dataset.write_function = function() {
2509 return self.write_row.apply(self, arguments);
2511 this.dataset.read_function = this.options.read_function;
2512 this.dataset.parent_view = this.options.parent_view;
2513 this.dataset.on_default_get.add(this.on_default_get);
2514 if (this.options.initial_view == "search") {
2515 self.rpc('/web/session/eval_domain_and_context', {
2517 contexts: [this.context]
2518 }, function (results) {
2519 var search_defaults = {};
2520 _.each(results.context, function (value, key) {
2521 var match = /^search_default_(.*)$/.exec(key);
2523 search_defaults[match[1]] = value;
2526 self.setup_search_view(search_defaults);
2532 setup_search_view: function(search_defaults) {
2534 if (this.searchview) {
2535 this.searchview.stop();
2537 this.searchview = new openerp.web.SearchView(this,
2538 this.dataset, false, search_defaults);
2539 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2540 if (self.initial_ids) {
2541 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2542 contexts, groupbys);
2543 self.initial_ids = undefined;
2545 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2548 this.searchview.on_loaded.add_last(function () {
2549 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
2550 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
2551 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2552 $cbutton.click(function() {
2555 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2556 if(self.options.disable_multiple_selection) {
2559 $sbutton.click(function() {
2560 self.on_select_elements(self.selected_ids);
2563 self.view_list = new openerp.web.form.SelectCreateListView(self,
2564 self.dataset, false,
2565 _.extend({'deletable': false,
2566 'selectable': !self.options.disable_multiple_selection
2567 }, self.options.list_view_options || {}));
2568 self.view_list.popup = self;
2569 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2570 self.view_list.do_show();
2571 }).pipe(function() {
2572 self.searchview.do_search();
2575 this.searchview.appendTo($("#" + this.element_id + "_search"));
2577 do_search: function(domains, contexts, groupbys) {
2579 this.rpc('/web/session/eval_domain_and_context', {
2580 domains: domains || [],
2581 contexts: contexts || [],
2582 group_by_seq: groupbys || []
2583 }, function (results) {
2584 self.view_list.do_search(results.domain, results.context, results.group_by);
2587 create_row: function() {
2589 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2590 wdataset.parent_view = this.options.parent_view;
2591 return wdataset.create.apply(wdataset, arguments);
2593 write_row: function() {
2595 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2596 wdataset.parent_view = this.options.parent_view;
2597 return wdataset.write.apply(wdataset, arguments);
2599 on_select_elements: function(element_ids) {
2601 on_click_element: function(ids) {
2602 this.selected_ids = ids || [];
2603 if(this.selected_ids.length > 0) {
2604 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2606 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2609 new_object: function() {
2611 if (this.searchview) {
2612 this.searchview.hide();
2614 if (this.view_list) {
2615 this.view_list.$element.hide();
2617 this.dataset.index = null;
2618 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2619 if (this.options.alternative_form_view) {
2620 this.view_form.set_embedded_view(this.options.alternative_form_view);
2622 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2623 this.view_form.on_loaded.add_last(function() {
2624 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2625 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2626 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2627 $nbutton.click(function() {
2628 $.when(self.view_form.do_save()).then(function() {
2629 self.view_form.reload_lock.then(function() {
2630 self.view_form.on_button_new();
2634 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2635 $nbutton.click(function() {
2636 $.when(self.view_form.do_save()).then(function() {
2637 self.view_form.reload_lock.then(function() {
2642 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2643 $cbutton.click(function() {
2647 this.view_form.do_show();
2649 check_exit: function() {
2650 if (this.created_elements.length > 0) {
2651 this.on_select_elements(this.created_elements);
2655 on_default_get: function(res) {}
2658 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2659 do_add_record: function () {
2660 this.popup.new_object();
2662 select_record: function(index) {
2663 this.popup.on_select_elements([this.dataset.ids[index]]);
2666 do_select: function(ids, records) {
2667 this._super(ids, records);
2668 this.popup.on_click_element(ids);
2674 * @extends openerp.web.OldWidget
2676 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2677 identifier_prefix: "formopenpopup",
2678 template: "FormOpenPopup",
2681 * - alternative_form_view
2682 * - auto_write (default true)
2685 * - form_view_options
2688 show_element: function(model, row_id, context, options) {
2690 this.row_id = row_id;
2691 this.context = context || {};
2692 this.options = _.defaults(options || {}, {"auto_write": true});
2693 this.render_element();
2694 this.$element.dialog({title: '',
2702 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2703 this.dataset.fop = this;
2704 this.dataset.ids = [this.row_id];
2705 this.dataset.index = 0;
2706 this.dataset.parent_view = this.options.parent_view;
2707 this.setup_form_view();
2709 on_write: function(id, data) {
2710 if (!this.options.auto_write)
2713 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2714 wdataset.parent_view = this.options.parent_view;
2715 wdataset.write(id, data, {}, function(r) {
2716 self.on_write_completed();
2719 on_write_completed: function() {},
2720 setup_form_view: function() {
2722 var FormClass = this.options.readonly
2723 ? openerp.web.views.get_object('page')
2724 : openerp.web.views.get_object('form');
2725 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2726 if (this.options.alternative_form_view) {
2727 this.view_form.set_embedded_view(this.options.alternative_form_view);
2729 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2730 this.view_form.on_loaded.add_last(function() {
2731 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2732 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2733 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2734 $nbutton.click(function() {
2735 self.view_form.do_save().then(function() {
2739 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2740 $cbutton.click(function() {
2743 if (self.options.readonly) {
2745 $cbutton.text(_t("Close"));
2747 self.view_form.do_show();
2749 this.dataset.on_write.add(this.on_write);
2753 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2754 read_ids: function() {
2755 if (this.fop.options.read_function) {
2756 return this.fop.options.read_function.apply(null, arguments);
2758 return this._super.apply(this, arguments);
2763 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2764 template: 'FieldReference',
2765 init: function(view, node) {
2766 this._super(view, node);
2767 this.fields_view = {
2770 selection: view.fields_view.fields[this.name].selection
2777 this.get_fields_values = view.get_fields_values;
2778 this.do_onchange = this.on_form_changed = this.on_nop;
2779 this.dataset = this.view.dataset;
2780 this.widgets_counter = 0;
2781 this.view_id = 'reference_' + _.uniqueId();
2784 this.fields_order = [];
2785 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2789 this.reference_ready = true;
2790 this.selection.on_value_changed.add_last(this.on_selection_changed);
2791 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2796 on_nop: function() {
2798 on_selection_changed: function() {
2799 if (this.reference_ready) {
2800 var sel = this.selection.get_value();
2801 this.m2o.field.relation = sel;
2802 this.m2o.set_value(null);
2803 this.m2o.$element.toggle(sel !== false);
2808 this.selection.start();
2811 is_valid: function() {
2812 return this.required === false || typeof(this.get_value()) === 'string';
2814 is_dirty: function() {
2815 return this.selection.is_dirty() || this.m2o.is_dirty();
2817 set_value: function(value) {
2819 this.reference_ready = false;
2820 var vals = [], sel_val, m2o_val;
2821 if (typeof(value) === 'string') {
2822 vals = value.split(',');
2824 sel_val = vals[0] || false;
2825 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2826 this.selection.set_value(sel_val);
2827 this.m2o.field.relation = sel_val;
2828 this.m2o.set_value(m2o_val);
2829 this.m2o.$element.toggle(sel_val !== false);
2830 this.reference_ready = true;
2832 get_value: function() {
2833 var model = this.selection.get_value(),
2834 id = this.m2o.get_value();
2835 if (typeof(model) === 'string' && typeof(id) === 'number') {
2836 return model + ',' + id;
2843 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2844 init: function(view, node) {
2845 this._super(view, node);
2846 this.iframe = this.element_id + '_iframe';
2847 this.binary_value = false;
2850 this._super.apply(this, arguments);
2851 this.$element.find('input.oe-binary-file').change(this.on_file_change);
2852 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2853 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2855 human_filesize : function(size) {
2856 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2858 while (size >= 1024) {
2862 return size.toFixed(2) + ' ' + units[i];
2864 on_file_change: function(e) {
2865 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2866 // http://www.html5rocks.com/tutorials/file/dndfiles/
2867 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2868 window[this.iframe] = this.on_file_uploaded;
2869 if ($(e.target).val() != '') {
2870 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2871 this.$element.find('form.oe-binary-form').submit();
2872 this.$element.find('.oe-binary-progress').show();
2873 this.$element.find('.oe-binary').hide();
2876 on_file_uploaded: function(size, name, content_type, file_base64) {
2877 delete(window[this.iframe]);
2878 if (size === false) {
2879 this.do_warn("File Upload", "There was a problem while uploading your file");
2880 // TODO: use openerp web crashmanager
2881 console.warn("Error while uploading file : ", name);
2883 this.on_file_uploaded_and_valid.apply(this, arguments);
2884 this.on_ui_change();
2886 this.$element.find('.oe-binary-progress').hide();
2887 this.$element.find('.oe-binary').show();
2889 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2891 on_save_as: function() {
2892 var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
2893 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
2894 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
2897 on_clear: function() {
2898 if (this.value !== false) {
2900 this.binary_value = false;
2901 this.on_ui_change();
2907 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
2908 template: 'FieldBinaryFile',
2909 update_dom: function() {
2910 this._super.apply(this, arguments);
2911 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
2912 this.$element.find('input[type=text]').attr('disabled', this.readonly);
2914 set_value: function(value) {
2915 this._super.apply(this, arguments);
2916 var show_value = (value != null && value !== false) ? value : '';
2917 this.$element.find('input').eq(0).val(show_value);
2919 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2920 this.value = file_base64;
2921 this.binary_value = true;
2922 var show_value = this.human_filesize(size);
2923 this.$element.find('input').eq(0).val(show_value);
2924 this.set_filename(name);
2926 set_filename: function(value) {
2927 var filename = this.node.attrs.filename;
2928 if (this.view.fields[filename]) {
2929 this.view.fields[filename].set_value(value);
2930 this.view.fields[filename].on_ui_change();
2933 on_clear: function() {
2934 this._super.apply(this, arguments);
2935 this.$element.find('input').eq(0).val('');
2936 this.set_filename('');
2940 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
2941 template: 'FieldBinaryImage',
2943 this._super.apply(this, arguments);
2944 this.$image = this.$element.find('img.oe-binary-image');
2946 update_dom: function() {
2947 this._super.apply(this, arguments);
2948 this.$element.find('.oe-binary').toggle(!this.readonly);
2950 set_value: function(value) {
2951 this._super.apply(this, arguments);
2952 this.set_image_maxwidth();
2953 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
2954 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
2955 this.$image.attr('src', url);
2957 set_image_maxwidth: function() {
2958 this.$image.css('max-width', this.$element.width());
2960 on_file_change: function() {
2961 this.set_image_maxwidth();
2962 this._super.apply(this, arguments);
2964 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2965 this.value = file_base64;
2966 this.binary_value = true;
2967 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2969 on_clear: function() {
2970 this._super.apply(this, arguments);
2971 this.$image.attr('src', '/web/static/src/img/placeholder.png');
2975 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
2976 template: "EmptyComponent",
2979 this.selected_value = null;
2983 set_value: function(value) {
2985 this.selected_value = value;
2989 render_list: function() {
2991 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
2992 function(x) { return _.str.trim(x); });
2993 shown = _.select(shown, function(x) { return x.length > 0; });
2995 if (shown.length == 0) {
2996 this.to_show = this.field.selection;
2998 this.to_show = _.select(this.field.selection, function(x) {
2999 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3003 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3004 this.$element.html(content);
3006 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3007 var color = colors[this.selected_value];
3009 var elem = this.$element.find("li.oe-arrow-list-selected span");
3010 elem.css("border-color", color);
3011 if (this.check_white(color))
3012 elem.css("color", "white");
3013 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3014 elem.css("border-left-color", "rgba(0,0,0,0)");
3015 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3016 elem.css("border-color", "rgba(0,0,0,0)");
3017 elem.css("border-left-color", color);
3020 check_white: function(color) {
3021 var div = $("<div></div>");
3022 div.css("display", "none");
3023 div.css("color", color);
3024 div.appendTo($("body"));
3025 var ncolor = div.css("color");
3027 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3031 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3032 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3043 * Registry of form widgets, called by :js:`openerp.web.FormView`
3045 openerp.web.form.widgets = new openerp.web.Registry({
3046 'frame' : 'openerp.web.form.WidgetFrame',
3047 'group' : 'openerp.web.form.WidgetGroup',
3048 'notebook' : 'openerp.web.form.WidgetNotebook',
3049 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3050 'separator' : 'openerp.web.form.WidgetSeparator',
3051 'label' : 'openerp.web.form.WidgetLabel',
3052 'button' : 'openerp.web.form.WidgetButton',
3053 'char' : 'openerp.web.form.FieldChar',
3054 'email' : 'openerp.web.form.FieldEmail',
3055 'url' : 'openerp.web.form.FieldUrl',
3056 'text' : 'openerp.web.form.FieldText',
3057 'text_wiki' : 'openerp.web.form.FieldText',
3058 'date' : 'openerp.web.form.FieldDate',
3059 'datetime' : 'openerp.web.form.FieldDatetime',
3060 'selection' : 'openerp.web.form.FieldSelection',
3061 'many2one' : 'openerp.web.form.FieldMany2One',
3062 'many2many' : 'openerp.web.form.FieldMany2Many',
3063 'one2many' : 'openerp.web.form.FieldOne2Many',
3064 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3065 'reference' : 'openerp.web.form.FieldReference',
3066 'boolean' : 'openerp.web.form.FieldBoolean',
3067 'float' : 'openerp.web.form.FieldFloat',
3068 'integer': 'openerp.web.form.FieldFloat',
3069 'float_time': 'openerp.web.form.FieldFloat',
3070 'progressbar': 'openerp.web.form.FieldProgressBar',
3071 'image': 'openerp.web.form.FieldBinaryImage',
3072 'binary': 'openerp.web.form.FieldBinaryFile',
3073 'statusbar': 'openerp.web.form.FieldStatus'
3079 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: