1 openerp.web.form = function (openerp) {
3 var _t = openerp.web._t,
5 var QWeb = openerp.web.qweb;
7 openerp.web.views.add('form', 'openerp.web.FormView');
8 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
10 * Indicates that this view is not searchable, and thus that no search
11 * view should be displayed (if there is one active).
15 form_template: "FormView",
16 identifier_prefix: 'formview-',
17 display_name: _lt('Form'),
19 * @constructs openerp.web.FormView
20 * @extends openerp.web.View
22 * @param {openerp.web.Session} session the current openerp session
23 * @param {openerp.web.DataSet} dataset the dataset this view will work with
24 * @param {String} view_id the identifier of the OpenERP view object
25 * @param {Object} options
26 * - sidebar : [true|false]
27 * - resize_textareas : [true|false|max_height]
29 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
31 init: function(parent, dataset, view_id, options) {
33 this.set_default_options(options);
34 this.dataset = dataset;
35 this.model = dataset.model;
36 this.view_id = view_id || false;
37 this.fields_view = {};
39 this.widgets_counter = 0;
41 this.fields_order = [];
43 this.show_invalid = true;
44 this.default_focus_field = null;
45 this.default_focus_button = null;
46 this.registry = openerp.web.form.widgets;
47 this.has_been_loaded = $.Deferred();
48 this.$form_header = null;
49 this.translatable_fields = [];
50 _.defaults(this.options, {
51 "not_interactible_on_create": false
53 this.is_initialized = $.Deferred();
54 this.mutating_mutex = new $.Mutex();
55 this.on_change_mutex = new $.Mutex();
56 this.reload_mutex = new $.Mutex();
60 return this.init_view();
62 init_view: function() {
63 if (this.embedded_view) {
64 var def = $.Deferred().then(this.on_loaded);
66 $.async_when().then(function() {def.resolve(self.embedded_view);});
69 var context = new openerp.web.CompoundContext(this.dataset.get_context());
70 return this.rpc("/web/view/load", {
72 "view_id": this.view_id,
74 toolbar: this.options.sidebar,
81 this.sidebar.attachments.stop();
84 _.each(this.widgets, function(w) {
89 reposition: function ($e) {
93 on_loaded: function(data) {
96 this.fields_order = [];
97 this.fields_view = data;
98 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
100 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
102 this.$element.html(this.rendered);
103 _.each(this.widgets, function(w) {
106 this.$form_header = this.$element.find('.oe_form_header:first');
107 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
108 var action = $(this).data('pager-action');
109 self.on_pager_action(action);
112 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
113 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
115 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
116 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
117 this.sidebar.start();
118 this.sidebar.do_unfold();
119 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
120 this.sidebar.add_toolbar(this.fields_view.toolbar);
121 this.set_common_sidebar_sections(this.sidebar);
123 this.has_been_loaded.resolve();
126 do_load_state: function(state) {
127 if (state.id && this.datarecord.id != state.id) {
128 var idx = this.dataset.get_id_index(state.id);
130 this.dataset.ids.push(state.id)
131 this.dataset.index = this.dataset.ids.length - 1;
137 do_show: function () {
139 this.$element.show().css('visibility', 'hidden');
140 return this.has_been_loaded.pipe(function() {
142 if (self.dataset.index === null) {
143 // null index means we should start a new record
144 result = self.on_button_new();
146 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
147 context : { 'bin_size' : true }
148 }).pipe(self.on_record_loaded);
150 result.pipe(function() {
151 self.$element.css('visibility', 'visible');
154 self.sidebar.$element.show();
159 do_hide: function () {
162 this.sidebar.$element.hide();
165 on_record_loaded: function(record) {
166 var self = this, set_values = [];
168 throw new Error("Form: No record received");
170 this.datarecord = record;
172 _(this.fields).each(function (field, f) {
174 var result = field.set_value(self.datarecord[f] || false);
175 set_values.push(result);
176 $.when(result).then(function() {
180 return $.when.apply(null, set_values).pipe(function() {
182 self.show_invalid = false;
183 // New record: Second pass in order to trigger the onchanges
184 // respecting the fields order defined in the view
185 _.each(self.fields_order, function(field_name) {
186 if (record[field_name] !== undefined) {
187 var field = self.fields[field_name];
189 self.do_onchange(field);
193 self.on_form_changed();
194 self.is_initialized.resolve();
195 self.show_invalid = true;
196 self.do_update_pager(record.id == null);
198 self.sidebar.attachments.do_update();
200 if (self.default_focus_field && !self.embedded_view) {
201 self.default_focus_field.focus();
204 self.do_push_state({id:record.id});
208 on_form_changed: function() {
209 for (var w in this.widgets) {
211 w.process_modifiers();
215 on_pager_action: function(action) {
216 if (this.can_be_discarded()) {
219 this.dataset.index = 0;
222 this.dataset.previous();
228 this.dataset.index = this.dataset.ids.length - 1;
234 do_update_pager: function(hide_index) {
235 var $pager = this.$form_header.find('div.oe_form_pager');
236 var index = hide_index ? '-' : this.dataset.index + 1;
237 $pager.find('button').prop('disabled', this.dataset.ids.length < 2)
238 $pager.find('span.oe_pager_index').html(index);
239 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
241 parse_on_change: function (on_change, widget) {
243 var onchange = _.str.trim(on_change);
244 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
249 var method = call[1];
250 if (!_.str.trim(call[2])) {
251 return {method: method, args: [], context_index: null}
254 var argument_replacement = {
255 'False': function () {return false;},
256 'True': function () {return true;},
257 'None': function () {return null;},
258 'context': function (i) {
260 var ctx = widget.build_context ? widget.build_context() : {};
264 var parent_fields = null, context_index = null;
265 var args = _.map(call[2].split(','), function (a, i) {
266 var field = _.str.trim(a);
268 // literal constant or context
269 if (field in argument_replacement) {
270 return argument_replacement[field](i);
273 if (/^-?\d+(\.\d+)?$/.test(field)) {
274 return Number(field);
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([self.dataset.child_name]);
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 return this.on_change_mutex.exec(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();
340 on_processed_onchange: function(response, processed) {
342 var result = response;
344 for (var f in result.value) {
345 var field = this.fields[f];
346 // If field is not defined in the view, just ignore it
348 var value = result.value[f];
349 processed.push(field.name);
350 if (field.get_value() != value) {
351 field.set_value(value);
353 if (_.indexOf(processed, field.name) < 0) {
354 this.do_onchange(field, processed);
359 this.on_form_changed();
361 if (!_.isEmpty(result.warning)) {
362 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
365 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
372 return $.Deferred().resolve();
375 return $.Deferred().reject();
378 on_button_save: function() {
380 return this.do_save().then(function(result) {
381 self.do_prev_view(result.created);
384 on_button_cancel: function() {
385 return this.do_prev_view();
387 on_button_new: function() {
389 var def = $.Deferred();
390 $.when(this.has_been_loaded).then(function() {
391 if (self.can_be_discarded()) {
392 var keys = _.keys(self.fields_view.fields);
394 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
398 self.on_record_loaded({}).then(function() {
404 return def.promise();
406 can_be_discarded: function() {
407 return true; // FIXME: Disabled until the page view and button refactoring is done
408 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
411 * Triggers saving the form's record. Chooses between creating a new
412 * record or saving an existing one depending on whether the record
413 * already has an id property.
415 * @param {Function} success callback on save success
416 * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
418 do_save: function(success, prepend_on_create) {
420 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
422 var form_invalid = false,
424 first_invalid_field = null;
425 for (var f in self.fields) {
430 if (!first_invalid_field) {
431 first_invalid_field = f;
433 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
434 // Special case 'id' field, do not save this field
435 // on 'create' : save all non readonly fields
436 // on 'edit' : save non readonly modified fields
437 values[f.name] = f.get_value();
441 first_invalid_field.focus();
443 return $.Deferred().reject();
446 if (!self.datarecord.id) {
447 console.log("FormView(", self, ") : About to create", values);
448 save_deferral = self.dataset.create(values).pipe(function(r) {
449 return self.on_created(r, undefined, prepend_on_create);
451 } else if (_.isEmpty(values)) {
452 console.log("FormView(", self, ") : Nothing to save");
453 save_deferral = $.Deferred().resolve({}).promise();
455 console.log("FormView(", self, ") : About to save", values);
456 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
457 return self.on_saved(r);
460 return save_deferral.then(success);
464 return $.Deferred().reject();
468 on_invalid: function() {
470 _.each(this.fields, function(f) {
472 msg += "<li>" + f.string + "</li>";
476 this.do_warn("The following fields are invalid :", msg);
478 on_saved: function(r, success) {
480 // should not happen in the server, but may happen for internal purpose
481 return $.Deferred().reject();
483 return $.when(this.reload()).pipe(function () {
484 return $.when(r).then(success); }, null);
488 * Updates the form' dataset to contain the new record:
490 * * Adds the newly created record to the current dataset (at the end by
492 * * Selects that record (sets the dataset's index to point to the new
494 * * Updates the pager and sidebar displays
497 * @param {Function} success callback to execute after having updated the dataset
498 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
500 on_created: function(r, success, prepend_on_create) {
502 // should not happen in the server, but may happen for internal purpose
503 return $.Deferred().reject();
505 this.datarecord.id = r.result;
506 if (!prepend_on_create) {
507 this.dataset.ids.push(this.datarecord.id);
508 this.dataset.index = this.dataset.ids.length - 1;
510 this.dataset.ids.unshift(this.datarecord.id);
511 this.dataset.index = 0;
513 this.do_update_pager();
515 this.sidebar.attachments.do_update();
517 openerp.log("The record has been created with id #" + this.datarecord.id);
519 return $.when(_.extend(r, {created: true})).then(success);
522 on_action: function (action) {
523 console.debug('Executing action', action);
527 return this.reload_mutex.exec(function() {
528 if (self.dataset.index == null || self.dataset.index < 0) {
529 return $.when(self.on_button_new());
531 return self.dataset.read_index(_.keys(self.fields_view.fields), {
532 context : { 'bin_size' : true }
533 }).pipe(self.on_record_loaded);
537 get_fields_values: function(blacklist) {
538 blacklist = blacklist || [];
540 _.each(this.fields, function(value, key) {
541 if (_.include(blacklist, key))
543 var val = value.get_value();
548 get_selected_ids: function() {
549 var id = this.dataset.ids[this.dataset.index];
550 return id ? [id] : [];
552 recursive_save: function() {
554 return $.when(this.do_save()).pipe(function(res) {
555 if (self.dataset.parent_view)
556 return self.dataset.parent_view.recursive_save();
559 is_dirty: function() {
560 return _.any(this.fields, function (value) {
561 return value.is_dirty();
564 is_interactible_record: function() {
565 var id = this.datarecord.id;
567 if (this.options.not_interactible_on_create)
569 } else if (typeof(id) === "string") {
570 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
575 sidebar_context: function () {
576 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
579 openerp.web.FormDialog = openerp.web.Dialog.extend({
580 init: function(parent, options, view_id, dataset) {
581 this._super(parent, options);
582 this.dataset = dataset;
583 this.view_id = view_id;
588 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
592 this.form.appendTo(this.$element);
593 this.form.on_created.add_last(this.on_form_dialog_saved);
594 this.form.on_saved.add_last(this.on_form_dialog_saved);
597 select_id: function(id) {
598 if (this.form.dataset.select_id(id)) {
599 return this.form.do_show();
601 this.do_warn("Could not find id in dataset");
602 return $.Deferred().reject();
605 on_form_dialog_saved: function(r) {
611 openerp.web.form = {};
613 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
614 init: function(parent, form_view) {
615 var $section = parent.add_section(_t('Attachments'), 'attachments');
616 this.$div = $('<div class="oe-sidebar-attachments"></div>');
617 $section.append(this.$div);
619 this._super(parent, $section.attr('id'));
620 this.view = form_view;
622 do_update: function() {
623 if (!this.view.datarecord.id) {
624 this.on_attachments_loaded([]);
626 (new openerp.web.DataSetSearch(
627 this, 'ir.attachment', this.view.dataset.get_context(),
629 ['res_model', '=', this.view.dataset.model],
630 ['res_id', '=', this.view.datarecord.id],
631 ['type', 'in', ['binary', 'url']]
632 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
635 on_attachments_loaded: function(attachments) {
636 this.attachments = attachments;
637 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
638 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
639 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
641 on_attachment_changed: function(e) {
642 window[this.element_id + '_iframe'] = this.do_update;
643 var $e = $(e.target);
644 if ($e.val() != '') {
645 this.$element.find('form.oe-binary-form').submit();
646 $e.parent().find('input[type=file]').prop('disabled', true);
647 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
650 on_attachment_delete: function(e) {
651 var self = this, $e = $(e.currentTarget);
652 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
653 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
654 this.rpc('/web/dataset/unlink', {
655 model: 'ir.attachment',
656 ids: [parseInt($e.attr('data-id'))]
658 $e.parent().remove();
659 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
665 openerp.web.form.compute_domain = function(expr, fields) {
667 for (var i = expr.length - 1; i >= 0; i--) {
669 if (ex.length == 1) {
670 var top = stack.pop();
673 stack.push(stack.pop() || top);
676 stack.push(stack.pop() && top);
682 throw new Error('Unknown domain operator ' + ex);
686 var field = fields[ex[0]];
688 throw new Error("Domain references unknown field : " + ex[0]);
690 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
694 switch (op.toLowerCase()) {
697 stack.push(field_value == val);
701 stack.push(field_value != val);
704 stack.push(field_value < val);
707 stack.push(field_value > val);
710 stack.push(field_value <= val);
713 stack.push(field_value >= val);
716 stack.push(_(val).contains(field_value));
719 stack.push(!_(val).contains(field_value));
722 console.warn("Unsupported operator in modifiers :", op);
725 return _.all(stack, _.identity);
728 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
730 identifier_prefix: 'formview-widget-',
732 * @constructs openerp.web.form.Widget
733 * @extends openerp.web.Widget
738 init: function(view, node) {
741 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
742 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
743 this.type = this.type || node.tag;
744 this.element_name = this.element_name || this.type;
745 this.element_class = [
746 'formview', this.view.view_id, this.element_name,
747 this.view.widgets_counter++].join("_");
751 this.view.widgets[this.element_class] = this;
752 this.children = node.children;
753 this.colspan = parseInt(node.attrs.colspan || 1, 10);
754 this.decrease_max_width = 0;
756 this.string = this.string || node.attrs.string;
757 this.help = this.help || node.attrs.help;
758 this.invisible = this.modifiers['invisible'] === true;
759 this.classname = 'oe_form_' + this.type;
761 this.align = parseFloat(this.node.attrs.align);
762 if (isNaN(this.align) || this.align === 1) {
763 this.align = 'right';
764 } else if (this.align === 0) {
767 this.align = 'center';
771 this.width = this.node.attrs.width;
774 this.$element = this.view.$element.find(
775 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
777 process_modifiers: function() {
778 var compute_domain = openerp.web.form.compute_domain;
779 for (var a in this.modifiers) {
780 this[a] = compute_domain(this.modifiers[a], this.view.fields);
783 update_dom: function() {
784 this.$element.toggle(!this.invisible);
787 var template = this.template;
788 return QWeb.render(template, { "widget": this });
790 do_attach_tooltip: function(widget, trigger, options) {
791 widget = widget || this;
792 trigger = trigger || this.$element;
796 content: function() {
797 var template = widget.template + '.tooltip';
798 if (!QWeb.has_template(template)) {
799 template = 'WidgetLabel.tooltip';
801 return QWeb.render(template, {
802 debug: openerp.connection.debug,
807 trigger.tipTip(options);
809 _build_view_fields_values: function(blacklist) {
810 var a_dataset = this.view.dataset;
811 var fields_values = this.view.get_fields_values(blacklist);
812 var active_id = a_dataset.ids[a_dataset.index];
813 _.extend(fields_values, {
814 active_id: active_id || false,
815 active_ids: active_id ? [active_id] : [],
816 active_model: a_dataset.model,
819 if (a_dataset.parent_view) {
820 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
822 return fields_values;
824 _build_eval_context: function(blacklist) {
825 var a_dataset = this.view.dataset;
826 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
829 * Builds a new context usable for operations related to fields by merging
830 * the fields'context with the action's context.
832 build_context: function(blacklist) {
833 // only use the model's context if there is not context on the node
834 var v_context = this.node.attrs.context;
836 v_context = (this.field || {}).context || {};
839 if (v_context.__ref || true) { //TODO: remove true
840 var fields_values = this._build_eval_context(blacklist);
841 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
845 build_domain: function() {
846 var f_domain = this.field.domain || [];
847 var n_domain = this.node.attrs.domain || null;
848 // if there is a domain on the node, overrides the model's domain
849 var final_domain = n_domain !== null ? n_domain : f_domain;
850 if (!(final_domain instanceof Array) || true) { //TODO: remove true
851 var fields_values = this._build_eval_context();
852 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
858 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
859 template: 'WidgetFrame',
860 init: function(view, node) {
861 this._super(view, node);
862 this.columns = parseInt(node.attrs.col || 4, 10);
867 for (var i = 0; i < node.children.length; i++) {
868 var n = node.children[i];
869 if (n.tag == "newline") {
875 this.set_row_cells_with(this.table[this.table.length - 1]);
878 if (this.table.length) {
879 this.set_row_cells_with(this.table[this.table.length - 1]);
882 this.table.push(row);
887 set_row_cells_with: function(row) {
890 row_length = row.length;
891 for (var i = 0; i < row.length; i++) {
892 if (row[i].always_invisible) {
895 bypass += row[i].width === undefined ? 0 : 1;
896 max_width -= row[i].decrease_max_width;
899 var size_unit = Math.round(max_width / (this.columns - bypass)),
901 for (var i = 0; i < row.length; i++) {
903 if (w.always_invisible) {
906 colspan_sum += w.colspan;
907 if (w.width === undefined) {
908 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
910 w.width = width + '%';
914 handle_node: function(node) {
916 if (node.tag == 'field') {
917 type = this.view.fields_view.fields[node.attrs.name] || {};
918 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
919 // This way we can retain backward compatibility between addons and old clients
920 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
921 node.attrs.nolabel = '1';
924 var widget = new (this.view.registry.get_any(
925 [node.attrs.widget, type.type, node.tag])) (this.view, node);
926 if (node.tag == 'field') {
927 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
928 this.view.default_focus_field = widget;
930 if (node.attrs.nolabel != '1') {
931 var label = new (this.view.registry.get_object('label')) (this.view, node);
932 label["for"] = widget;
933 this.add_widget(label, widget.colspan + 1);
936 this.add_widget(widget);
938 add_widget: function(widget, colspan) {
939 var current_row = this.table[this.table.length - 1];
940 if (!widget.always_invisible) {
941 colspan = colspan || widget.colspan;
942 if (current_row.length && (this.x + colspan) > this.columns) {
943 current_row = this.add_row();
945 this.x += widget.colspan;
947 current_row.push(widget);
952 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
953 template: 'WidgetGroup'
956 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
957 template: 'WidgetNotebook',
958 init: function(view, node) {
959 this._super(view, node);
961 for (var i = 0; i < node.children.length; i++) {
962 var n = node.children[i];
963 if (n.tag == "page") {
964 var page = new (this.view.registry.get_object('notebookpage'))(
965 this.view, n, this, this.pages.length);
966 this.pages.push(page);
972 this._super.apply(this, arguments);
973 this.$element.find('> ul > li').each(function (index, tab_li) {
974 var page = self.pages[index],
975 id = _.uniqueId(self.element_name + '-');
976 page.element_id = id;
977 $(tab_li).find('a').attr('href', '#' + id);
979 this.$element.find('> div').each(function (index, page) {
980 page.id = self.pages[index].element_id;
982 this.$element.tabs();
983 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
984 if (openerp.connection.debug) {
985 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
986 defaultPosition: 'top'
990 do_select_first_visible_tab: function() {
991 for (var i = 0; i < this.pages.length; i++) {
992 var page = this.pages[i];
993 if (page.invisible === false) {
994 this.$element.tabs('select', page.index);
1001 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1002 template: 'WidgetNotebookPage',
1003 init: function(view, node, notebook, index) {
1004 this.notebook = notebook;
1006 this.element_name = 'page_' + index;
1007 this._super(view, node);
1010 this._super.apply(this, arguments);
1011 this.$element_tab = this.notebook.$element.find(
1012 '> ul > li:eq(' + this.index + ')');
1014 update_dom: function() {
1015 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1016 this.notebook.do_select_first_visible_tab();
1018 this.$element_tab.toggle(!this.invisible);
1019 this.$element.toggle(!this.invisible);
1023 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1024 template: 'WidgetSeparator',
1025 init: function(view, node) {
1026 this._super(view, node);
1027 this.orientation = node.attrs.orientation || 'horizontal';
1028 if (this.orientation === 'vertical') {
1031 this.classname += '_' + this.orientation;
1035 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1036 template: 'WidgetButton',
1037 init: function(view, node) {
1038 this._super(view, node);
1039 this.force_disabled = false;
1041 // We don't have button key bindings in the webclient
1042 this.string = this.string.replace(/_/g, '');
1044 if (node.attrs.default_focus == '1') {
1045 // TODO fme: provide enter key binding to widgets
1046 this.view.default_focus_button = this;
1050 this._super.apply(this, arguments);
1051 this.$element.find("button").click(this.on_click);
1052 if (this.help || openerp.connection.debug) {
1053 this.do_attach_tooltip();
1056 on_click: function() {
1058 this.force_disabled = true;
1059 this.check_disable();
1060 this.execute_action().always(function() {
1061 self.force_disabled = false;
1062 self.check_disable();
1066 execute_action: function() {
1068 var exec_action = function() {
1069 if (self.node.attrs.confirm) {
1070 var def = $.Deferred();
1071 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1072 title: _t('Confirm'),
1075 {text: _t("Ok"), click: function() {
1076 self.on_confirmed().then(function() {
1079 $(this).dialog("close");
1082 {text: _t("Cancel"), click: function() {
1084 $(this).dialog("close");
1089 return def.promise();
1091 return self.on_confirmed();
1094 if (!this.node.attrs.special) {
1095 return this.view.recursive_save().pipe(exec_action);
1097 return exec_action();
1100 on_confirmed: function() {
1103 var context = this.node.attrs.context;
1104 if (context && context.__ref) {
1105 context = new openerp.web.CompoundContext(context);
1106 context.set_eval_context(this._build_eval_context());
1109 return this.view.do_execute_action(
1110 _.extend({}, this.node.attrs, {context: context}),
1111 this.view.dataset, this.view.datarecord.id, function () {
1115 update_dom: function() {
1117 this.check_disable();
1119 check_disable: function() {
1120 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1121 this.$element.find('button').prop('disabled', disabled);
1122 this.$element.find("button").css('color', disabled ? 'grey' : '');
1126 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1127 template: 'WidgetLabel',
1128 init: function(view, node) {
1129 this.element_name = 'label_' + node.attrs.name;
1131 this._super(view, node);
1133 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1134 this.template = "WidgetParagraph";
1135 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1136 // Widgets default to right-aligned, but paragraph defaults to
1138 if (isNaN(parseFloat(this.node.attrs.align))) {
1139 this.align = 'left';
1144 this.decrease_max_width = 1;
1148 render: function () {
1149 if (this['for'] && this.type !== 'label') {
1150 return QWeb.render(this.template, {widget: this['for']});
1152 // Actual label widgets should not have a false and have type label
1153 return QWeb.render(this.template, {widget: this});
1158 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1159 this.do_attach_tooltip(self['for']);
1161 this.$element.find("label").dblclick(function() {
1162 var widget = self['for'] || self;
1163 openerp.log(widget.element_class , widget);
1169 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1171 * @constructs openerp.web.form.Field
1172 * @extends openerp.web.form.Widget
1177 init: function(view, node) {
1178 this.name = node.attrs.name;
1179 this.value = undefined;
1180 view.fields[this.name] = this;
1181 view.fields_order.push(this.name);
1182 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1183 this.element_name = "field_" + this.name + "_" + this.type;
1185 this._super(view, node);
1187 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1190 this.field = view.fields_view.fields[node.attrs.name] || {};
1191 this.string = node.attrs.string || this.field.string;
1192 this.help = node.attrs.help || this.field.help;
1193 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1194 this.readonly = this.modifiers['readonly'] === true;
1195 this.required = this.modifiers['required'] === true;
1196 this.invalid = this.dirty = false;
1198 this.classname = 'oe_form_field_' + this.type;
1201 this._super.apply(this, arguments);
1202 if (this.field.translate) {
1203 this.view.translatable_fields.push(this);
1204 this.$element.find('.oe_field_translate').click(this.on_translate);
1206 if (this.nolabel && openerp.connection.debug) {
1207 this.do_attach_tooltip(this, this.$element, {
1208 defaultPosition: 'top'
1212 set_value: function(value) {
1214 this.invalid = false;
1216 this.on_value_changed();
1218 set_value_from_ui: function() {
1219 this.on_value_changed();
1221 on_value_changed: function() {
1223 on_translate: function() {
1224 this.view.open_translate_dialog(this);
1226 get_value: function() {
1229 is_valid: function() {
1230 return !this.invalid;
1232 is_dirty: function() {
1233 return this.dirty && !this.readonly;
1235 get_on_change_value: function() {
1236 return this.get_value();
1238 update_dom: function() {
1239 this._super.apply(this, arguments);
1240 if (this.field.translate) {
1241 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1243 if (!this.disable_utility_classes) {
1244 this.$element.toggleClass('disabled', this.readonly);
1245 this.$element.toggleClass('required', this.required);
1246 if (this.view.show_invalid) {
1247 this.$element.toggleClass('invalid', !this.is_valid());
1251 on_ui_change: function() {
1254 if (this.is_valid()) {
1255 this.set_value_from_ui();
1256 this.view.do_onchange(this);
1257 this.view.on_form_changed();
1262 validate: function() {
1263 this.invalid = false;
1270 get_definition_options: function() {
1271 if (!this.definition_options) {
1272 var str = this.node.attrs.options || '{}';
1273 this.definition_options = JSON.parse(str);
1275 return this.definition_options;
1279 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1280 template: 'FieldChar',
1281 init: function (view, node) {
1282 this._super(view, node);
1283 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1286 this._super.apply(this, arguments);
1287 this.$element.find('input').change(this.on_ui_change);
1289 set_value: function(value) {
1290 this._super.apply(this, arguments);
1291 var show_value = openerp.web.format_value(value, this, '');
1292 this.$element.find('input').val(show_value);
1295 update_dom: function() {
1296 this._super.apply(this, arguments);
1297 this.$element.find('input').prop('disabled', this.readonly);
1299 set_value_from_ui: function() {
1300 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1303 validate: function() {
1304 this.invalid = false;
1306 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1307 this.invalid = this.required && value === '';
1309 this.invalid = true;
1313 this.$element.find('input').focus();
1317 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1318 template: 'FieldEmail',
1320 this._super.apply(this, arguments);
1321 this.$element.find('button').click(this.on_button_clicked);
1323 on_button_clicked: function() {
1324 if (!this.value || !this.is_valid()) {
1325 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1327 location.href = 'mailto:' + this.value;
1332 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1333 template: 'FieldUrl',
1335 this._super.apply(this, arguments);
1336 this.$element.find('button').click(this.on_button_clicked);
1338 on_button_clicked: function() {
1340 this.do_warn("Resource error", "This resource is empty");
1342 window.open(this.value);
1347 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1348 init: function (view, node) {
1349 this._super(view, node);
1350 if (node.attrs.digits) {
1351 this.parse_digits(node.attrs.digits);
1353 this.digits = view.fields_view.fields[node.attrs.name].digits;
1356 parse_digits: function (digits_attr) {
1357 // could use a Python parser instead.
1358 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1359 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1361 set_value: function(value) {
1362 if (value === false || value === undefined) {
1363 // As in GTK client, floats default to 0
1366 this._super.apply(this, [value]);
1370 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1371 template: "web.datetimepicker",
1372 jqueryui_object: 'datetimepicker',
1373 type_of_date: "datetime",
1374 init: function(parent) {
1375 this._super(parent);
1376 this.name = parent.name;
1380 this.$input = this.$element.find('input.oe_datepicker_master');
1381 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1382 this.$input.change(this.on_change);
1384 onSelect: this.on_picker_select,
1388 showButtonPanel: true
1390 this.$element.find('img.oe_datepicker_trigger').click(function() {
1391 if (!self.readonly) {
1392 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1393 self.$input_picker.show();
1394 self.picker('show');
1395 self.$input_picker.hide();
1398 this.set_readonly(false);
1401 picker: function() {
1402 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1404 on_picker_select: function(text, instance) {
1405 var date = this.picker('getDate');
1406 this.$input.val(date ? this.format_client(date) : '').change();
1408 set_value: function(value) {
1410 this.$input.val(value ? this.format_client(value) : '');
1412 get_value: function() {
1415 set_value_from_ui: function() {
1416 var value = this.$input.val() || false;
1417 this.value = this.parse_client(value);
1419 set_readonly: function(readonly) {
1420 this.readonly = readonly;
1421 this.$input.prop('disabled', this.readonly);
1422 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1424 is_valid: function(required) {
1425 var value = this.$input.val();
1430 this.parse_client(value);
1438 this.$input.focus();
1440 parse_client: function(v) {
1441 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1443 format_client: function(v) {
1444 return openerp.web.format_value(v, {"widget": this.type_of_date});
1446 on_change: function() {
1447 if (this.is_valid()) {
1448 this.set_value_from_ui();
1453 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1454 jqueryui_object: 'datepicker',
1455 type_of_date: "date"
1458 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1459 template: "EmptyComponent",
1460 build_widget: function() {
1461 return new openerp.web.DateTimeWidget(this);
1465 this._super.apply(this, arguments);
1466 this.datewidget = this.build_widget();
1467 this.datewidget.on_change.add_last(this.on_ui_change);
1468 this.datewidget.appendTo(this.$element);
1470 set_value: function(value) {
1472 this.datewidget.set_value(value);
1474 get_value: function() {
1475 return this.datewidget.get_value();
1477 update_dom: function() {
1478 this._super.apply(this, arguments);
1479 this.datewidget.set_readonly(this.readonly);
1481 validate: function() {
1482 this.invalid = !this.datewidget.is_valid(this.required);
1485 this.datewidget.focus();
1489 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1490 build_widget: function() {
1491 return new openerp.web.DateWidget(this);
1495 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1496 template: 'FieldText',
1498 this._super.apply(this, arguments);
1499 this.$element.find('textarea').change(this.on_ui_change);
1500 this.resized = false;
1502 set_value: function(value) {
1503 this._super.apply(this, arguments);
1504 var show_value = openerp.web.format_value(value, this, '');
1505 this.$element.find('textarea').val(show_value);
1506 if (!this.resized && this.view.options.resize_textareas) {
1507 this.do_resize(this.view.options.resize_textareas);
1508 this.resized = true;
1511 update_dom: function() {
1512 this._super.apply(this, arguments);
1513 this.$element.find('textarea').prop('disabled', this.readonly);
1515 set_value_from_ui: function() {
1516 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1519 validate: function() {
1520 this.invalid = false;
1522 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1523 this.invalid = this.required && value === '';
1525 this.invalid = true;
1529 this.$element.find('textarea').focus();
1531 do_resize: function(max_height) {
1532 max_height = parseInt(max_height, 10);
1533 var $input = this.$element.find('textarea'),
1534 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1536 $div.text($input.val());
1537 _.each('font-family,font-size,white-space'.split(','), function(style) {
1538 $div.css(style, $input.css(style));
1540 $div.appendTo($('body'));
1541 new_height = $div.height();
1542 if (new_height < 90) {
1545 if (!isNaN(max_height) && new_height > max_height) {
1546 new_height = max_height;
1549 $input.height(new_height);
1552 this.resized = false;
1556 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1557 template: 'FieldBoolean',
1560 this._super.apply(this, arguments);
1561 this.$element.find('input').click(self.on_ui_change);
1563 set_value: function(value) {
1564 this._super.apply(this, arguments);
1565 this.$element.find('input')[0].checked = value;
1567 set_value_from_ui: function() {
1568 this.value = this.$element.find('input').is(':checked');
1571 update_dom: function() {
1572 this._super.apply(this, arguments);
1573 this.$element.find('input').prop('disabled', this.readonly);
1576 this.$element.find('input').focus();
1580 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1581 template: 'FieldProgressBar',
1583 this._super.apply(this, arguments);
1584 this.$element.find('div').progressbar({
1586 disabled: this.readonly
1589 set_value: function(value) {
1590 this._super.apply(this, arguments);
1591 var show_value = Number(value);
1592 if (isNaN(show_value)) {
1595 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1599 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1600 // to replace view editor
1603 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1604 template: 'FieldSelection',
1605 init: function(view, node) {
1607 this._super(view, node);
1608 this.values = _.clone(this.field.selection);
1609 _.each(this.values, function(v, i) {
1610 if (v[0] === false && v[1] === '') {
1611 self.values.splice(i, 1);
1614 this.values.unshift([false, '']);
1617 // Flag indicating whether we're in an event chain containing a change
1618 // event on the select, in order to know what to do on keyup[RETURN]:
1619 // * If the user presses [RETURN] as part of changing the value of a
1620 // selection, we should just let the value change and not let the
1621 // event broadcast further (e.g. to validating the current state of
1622 // the form in editable list view, which would lead to saving the
1623 // current row or switching to the next one)
1624 // * If the user presses [RETURN] with a select closed (side-effect:
1625 // also if the user opened the select and pressed [RETURN] without
1626 // changing the selected value), takes the action as validating the
1628 var ischanging = false;
1629 this._super.apply(this, arguments);
1630 this.$element.find('select')
1631 .change(this.on_ui_change)
1632 .change(function () { ischanging = true; })
1633 .click(function () { ischanging = false; })
1634 .keyup(function (e) {
1635 if (e.which !== 13 || !ischanging) { return; }
1636 e.stopPropagation();
1640 set_value: function(value) {
1641 value = value === null ? false : value;
1642 value = value instanceof Array ? value[0] : value;
1645 for (var i = 0, ii = this.values.length; i < ii; i++) {
1646 if (this.values[i][0] === value) index = i;
1648 this.$element.find('select')[0].selectedIndex = index;
1650 set_value_from_ui: function() {
1651 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1654 update_dom: function() {
1655 this._super.apply(this, arguments);
1656 this.$element.find('select').prop('disabled', this.readonly);
1658 validate: function() {
1659 var value = this.values[this.$element.find('select')[0].selectedIndex];
1660 this.invalid = !(value && !(this.required && value[0] === false));
1663 this.$element.find('select').focus();
1667 // jquery autocomplete tweak to allow html
1669 var proto = $.ui.autocomplete.prototype,
1670 initSource = proto._initSource;
1672 function filter( array, term ) {
1673 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1674 return $.grep( array, function(value) {
1675 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1680 _initSource: function() {
1681 if ( this.options.html && $.isArray(this.options.source) ) {
1682 this.source = function( request, response ) {
1683 response( filter( this.options.source, request.term ) );
1686 initSource.call( this );
1690 _renderItem: function( ul, item) {
1691 return $( "<li></li>" )
1692 .data( "item.autocomplete", item )
1693 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1699 openerp.web.form.dialog = function(content, options) {
1700 options = _.extend({
1705 var dialog = new openerp.web.Dialog(null, options, content).open();
1706 return dialog.$element;
1709 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1710 template: 'FieldMany2One',
1711 init: function(view, node) {
1712 this._super(view, node);
1715 this.cm_id = _.uniqueId('m2o_cm_');
1716 this.last_search = [];
1717 this.tmp_value = undefined;
1722 this.$input = this.$element.find("input");
1723 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1724 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1727 var init_context_menu_def = $.Deferred().then(function(e) {
1728 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1729 rdataset.call("get", ['action', 'client_action_relate',
1730 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1731 .then(function(result) {
1732 self.related_entries = result;
1734 var $cmenu = $("#" + self.cm_id);
1735 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1737 bindings[self.cm_id + "_search"] = function() {
1738 self._search_create_popup("search");
1740 bindings[self.cm_id + "_create"] = function() {
1741 self._search_create_popup("form");
1743 bindings[self.cm_id + "_open"] = function() {
1747 var pop = new openerp.web.form.FormOpenPopup(self.view);
1749 self.field.relation,
1751 self.build_context(),
1753 title: _t("Open: ") + (self.string || self.name)
1756 pop.on_write_completed.add_last(function() {
1757 self.set_value(self.value[0]);
1760 _.each(_.range(self.related_entries.length), function(i) {
1761 bindings[self.cm_id + "_related_" + i] = function() {
1762 self.open_related(self.related_entries[i]);
1765 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1766 bindings: bindings, itemStyle: {"color": ""},
1767 onContextMenu: function() {
1769 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1771 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1773 if (!self.readonly) {
1774 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1776 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1779 }, menuStyle: {width: "200px"}
1781 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1784 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1785 this.$menu_btn.click(ctx_callback);
1787 // some behavior for input
1788 this.$input.keyup(function() {
1789 if (self.$input.val() === "") {
1790 self._change_int_value(null);
1791 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1792 self._change_int_value(undefined);
1795 this.$drop_down.click(function() {
1798 if (self.$input.autocomplete("widget").is(":visible")) {
1799 self.$input.autocomplete("close");
1802 self.$input.autocomplete("search", "");
1804 self.$input.autocomplete("search");
1806 self.$input.focus();
1809 var anyoneLoosesFocus = function() {
1810 if (!self.$input.is(":focus") &&
1811 !self.$input.autocomplete("widget").is(":visible") &&
1813 if (self.value === undefined && self.last_search.length > 0) {
1814 self._change_int_ext_value(self.last_search[0]);
1816 self._change_int_ext_value(null);
1820 this.$input.focusout(anyoneLoosesFocus);
1822 var isSelecting = false;
1824 this.$input.autocomplete({
1825 source: function(req, resp) { self.get_search_result(req, resp); },
1826 select: function(event, ui) {
1830 self._change_int_value([item.id, item.name]);
1831 } else if (item.action) {
1832 self._change_int_value(undefined);
1837 focus: function(e, ui) {
1841 close: anyoneLoosesFocus,
1845 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1846 this.$input.keyup(function(e) {
1847 if (e.which === 13) {
1849 e.stopPropagation();
1851 isSelecting = false;
1854 // autocomplete component content handling
1855 get_search_result: function(request, response) {
1856 var search_val = request.term;
1859 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1861 dataset.name_search(search_val, self.build_domain(), 'ilike',
1862 this.limit + 1, function(data) {
1863 self.last_search = data;
1864 // possible selections for the m2o
1865 var values = _.map(data, function(x) {
1866 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1869 // search more... if more results that max
1870 if (values.length > self.limit) {
1871 values = values.slice(0, self.limit);
1872 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
1873 dataset.name_search(search_val, self.build_domain(), 'ilike'
1874 , false, function(data) {
1875 self._change_int_value(null);
1876 self._search_create_popup("search", data);
1881 var raw_result = _(data.result).map(function(x) {return x[1];});
1882 if (search_val.length > 0 &&
1883 !_.include(raw_result, search_val) &&
1884 (!self.value || search_val !== self.value[1])) {
1885 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
1886 $('<span />').text(search_val).html()), action: function() {
1887 self._quick_create(search_val);
1891 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
1892 self._change_int_value(null);
1893 self._search_create_popup("form", undefined, {"default_name": search_val});
1899 _quick_create: function(name) {
1901 var slow_create = function() {
1902 self._change_int_value(null);
1903 self._search_create_popup("form", undefined, {"default_name": name});
1905 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
1906 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1907 dataset.name_create(name, function(data) {
1908 self._change_int_ext_value(data);
1909 }).fail(function(error, event) {
1910 event.preventDefault();
1916 // all search/create popup handling
1917 _search_create_popup: function(view, ids, context) {
1919 var pop = new openerp.web.form.SelectCreatePopup(this);
1921 self.field.relation,
1923 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
1924 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1926 disable_multiple_selection: true
1928 self.build_domain(),
1929 new openerp.web.CompoundContext(self.build_context(), context || {})
1931 pop.on_select_elements.add(function(element_ids) {
1932 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1933 dataset.name_get([element_ids[0]], function(data) {
1934 self._change_int_ext_value(data[0]);
1938 _change_int_ext_value: function(value) {
1939 this._change_int_value(value);
1940 this.$input.val(this.value ? this.value[1] : "");
1942 _change_int_value: function(value) {
1944 var back_orig_value = this.original_value;
1945 if (this.value === null || this.value) {
1946 this.original_value = this.value;
1948 if (back_orig_value === undefined) { // first use after a set_value()
1951 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1952 !== (this.value ? this.value[0] : null))) {
1953 this.on_ui_change();
1956 set_value: function(value) {
1957 value = value || null;
1958 this.invalid = false;
1960 this.tmp_value = value;
1962 self.on_value_changed();
1963 var real_set_value = function(rval) {
1964 self.tmp_value = undefined;
1966 self.original_value = undefined;
1967 self._change_int_ext_value(rval);
1969 if (value && !(value instanceof Array)) {
1970 // name_get in a m2o does not use the context of the field
1971 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
1972 dataset.name_get([value], function(data) {
1973 real_set_value(data[0]);
1974 }).fail(function() {self.tmp_value = undefined;});
1976 $.async_when().then(function() {real_set_value(value);});
1979 get_value: function() {
1980 if (this.tmp_value !== undefined) {
1981 if (this.tmp_value instanceof Array) {
1982 return this.tmp_value[0];
1984 return this.tmp_value ? this.tmp_value : false;
1986 if (this.value === undefined)
1987 return this.original_value ? this.original_value[0] : false;
1988 return this.value ? this.value[0] : false;
1990 validate: function() {
1991 this.invalid = false;
1992 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1994 this.invalid = this.required;
1997 open_related: function(related) {
2001 var additional_context = {
2002 active_id: self.value[0],
2003 active_ids: [self.value[0]],
2004 active_model: self.field.relation
2006 self.rpc("/web/action/load", {
2007 action_id: related[2].id,
2008 context: additional_context
2009 }, function(result) {
2010 result.result.context = _.extend(result.result.context || {}, additional_context);
2011 self.do_action(result.result);
2014 focus: function () {
2015 this.$input.focus();
2017 update_dom: function() {
2018 this._super.apply(this, arguments);
2019 this.$input.prop('disabled', this.readonly);
2024 # Values: (0, 0, { fields }) create
2025 # (1, ID, { fields }) update
2026 # (2, ID) remove (delete)
2027 # (3, ID) unlink one (target id or target of relation)
2029 # (5) unlink all (only valid for one2many)
2034 'create': function (values) {
2035 return [commands.CREATE, false, values];
2037 // (1, id, {values})
2039 'update': function (id, values) {
2040 return [commands.UPDATE, id, values];
2044 'delete': function (id) {
2045 return [commands.DELETE, id, false];
2047 // (3, id[, _]) removes relation, but not linked record itself
2049 'forget': function (id) {
2050 return [commands.FORGET, id, false];
2054 'link_to': function (id) {
2055 return [commands.LINK_TO, id, false];
2059 'delete_all': function () {
2060 return [5, false, false];
2062 // (6, _, ids) replaces all linked records with provided ids
2064 'replace_with': function (ids) {
2065 return [6, false, ids];
2068 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2069 template: 'FieldOne2Many',
2070 multi_selection: false,
2071 init: function(view, node) {
2072 this._super(view, node);
2073 this.is_loaded = $.Deferred();
2074 this.initial_is_loaded = this.is_loaded;
2075 this.is_setted = $.Deferred();
2076 this.form_last_update = $.Deferred();
2077 this.init_form_last_update = this.form_last_update;
2078 this.disable_utility_classes = true;
2081 this._super.apply(this, arguments);
2085 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2086 this.dataset.o2m = this;
2087 this.dataset.parent_view = this.view;
2088 this.dataset.child_name = this.name;
2089 //this.dataset.child_name =
2090 this.dataset.on_change.add_last(function() {
2091 self.trigger_on_change();
2094 this.is_setted.then(function() {
2098 trigger_on_change: function() {
2099 var tmp = this.doing_on_change;
2100 this.doing_on_change = true;
2101 this.on_ui_change();
2102 this.doing_on_change = tmp;
2104 is_readonly: function() {
2105 return this.readonly || this.force_readonly;
2107 load_views: function() {
2110 var modes = this.node.attrs.mode;
2111 modes = !!modes ? modes.split(",") : ["tree"];
2113 _.each(modes, function(mode) {
2116 view_type: mode == "tree" ? "list" : mode,
2117 options: { sidebar : false }
2119 if (self.field.views && self.field.views[mode]) {
2120 view.embedded_view = self.field.views[mode];
2122 if(view.view_type === "list") {
2123 view.options.selectable = self.multi_selection;
2124 if (self.is_readonly()) {
2125 view.options.addable = null;
2126 view.options.deletable = null;
2127 view.options.isClarkGable = false;
2129 } else if (view.view_type === "form") {
2130 if (self.is_readonly()) {
2131 view.view_type = 'page';
2133 view.options.not_interactible_on_create = true;
2139 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2140 this.viewmanager.template = 'One2Many.viewmanager';
2141 this.viewmanager.registry = openerp.web.views.clone({
2142 list: 'openerp.web.form.One2ManyListView',
2143 form: 'openerp.web.form.One2ManyFormView',
2144 page: 'openerp.web.PageView'
2146 var once = $.Deferred().then(function() {
2147 self.init_form_last_update.resolve();
2149 var def = $.Deferred().then(function() {
2150 self.initial_is_loaded.resolve();
2152 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2153 if (view_type == "list") {
2154 controller.o2m = self;
2155 if (self.is_readonly())
2156 controller.set_editable(false);
2157 } else if (view_type == "form" || view_type == 'page') {
2158 if (view_type == 'page' || self.is_readonly()) {
2159 $(".oe_form_buttons", controller.$element).children().remove();
2161 controller.on_record_loaded.add_last(function() {
2164 controller.on_pager_action.add_first(function() {
2165 self.save_any_view();
2167 } else if (view_type == "graph") {
2168 self.reload_current_view()
2172 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2173 $.when(self.save_any_view()).then(function() {
2174 if(n_mode === "list")
2175 $.async_when().then(function() {self.reload_current_view();});
2178 this.is_setted.then(function() {
2179 $.async_when().then(function () {
2180 self.viewmanager.appendTo(self.$element);
2185 reload_current_view: function() {
2187 return self.is_loaded = self.is_loaded.pipe(function() {
2188 var active_view = self.viewmanager.active_view;
2189 var view = self.viewmanager.views[active_view].controller;
2190 if(active_view === "list") {
2191 return view.reload_content();
2192 } else if (active_view === "form" || active_view === 'page') {
2193 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2194 self.dataset.index = 0;
2196 var act = function() {
2197 return view.do_show();
2199 self.form_last_update = self.form_last_update.pipe(act, act);
2200 return self.form_last_update;
2201 } else if (active_view === "graph") {
2202 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2206 set_value: function(value) {
2207 value = value || [];
2209 this.dataset.reset_ids([]);
2210 if(value.length >= 1 && value[0] instanceof Array) {
2212 _.each(value, function(command) {
2213 var obj = {values: command[2]};
2214 switch (command[0]) {
2215 case commands.CREATE:
2216 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2218 self.dataset.to_create.push(obj);
2219 self.dataset.cache.push(_.clone(obj));
2222 case commands.UPDATE:
2223 obj['id'] = command[1];
2224 self.dataset.to_write.push(obj);
2225 self.dataset.cache.push(_.clone(obj));
2228 case commands.DELETE:
2229 self.dataset.to_delete.push({id: command[1]});
2231 case commands.LINK_TO:
2232 ids.push(command[1]);
2234 case commands.DELETE_ALL:
2235 self.dataset.delete_all = true;
2240 this.dataset.set_ids(ids);
2241 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2243 this.dataset.delete_all = true;
2244 _.each(value, function(command) {
2245 var obj = {values: command};
2246 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2248 self.dataset.to_create.push(obj);
2249 self.dataset.cache.push(_.clone(obj));
2253 this.dataset.set_ids(ids);
2256 this.dataset.reset_ids(value);
2258 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2259 this.dataset.index = 0;
2261 self.is_setted.resolve();
2262 return self.reload_current_view();
2264 get_value: function() {
2268 this.save_any_view();
2269 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2270 val = val.concat(_.map(this.dataset.ids, function(id) {
2271 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2273 return commands.create(alter_order.values);
2275 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2277 return commands.update(alter_order.id, alter_order.values);
2279 return commands.link_to(id);
2281 return val.concat(_.map(
2282 this.dataset.to_delete, function(x) {
2283 return commands['delete'](x.id);}));
2285 save_any_view: function() {
2286 if (this.doing_on_change)
2288 return this.session.synchronized_mode(_.bind(function() {
2289 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2290 this.viewmanager.views[this.viewmanager.active_view] &&
2291 this.viewmanager.views[this.viewmanager.active_view].controller) {
2292 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2293 if (this.viewmanager.active_view === "form") {
2294 if (!view.is_initialized.isResolved()) {
2297 var res = $.when(view.do_save());
2298 if (!res.isResolved() && !res.isRejected()) {
2299 console.warn("Asynchronous get_value() is not supported in form view.");
2302 } else if (this.viewmanager.active_view === "list") {
2303 var res = $.when(view.ensure_saved());
2304 if (!res.isResolved() && !res.isRejected()) {
2305 console.warn("Asynchronous get_value() is not supported in list view.");
2313 is_valid: function() {
2315 return this._super();
2317 validate: function() {
2318 this.invalid = false;
2319 if (!this.viewmanager.views[this.viewmanager.active_view])
2321 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2322 if (this.viewmanager.active_view === "form") {
2323 for (var f in view.fields) {
2325 if (!f.is_valid()) {
2326 this.invalid = true;
2332 is_dirty: function() {
2333 this.save_any_view();
2334 return this._super();
2336 update_dom: function() {
2337 this._super.apply(this, arguments);
2339 if (this.previous_readonly !== this.readonly) {
2340 this.previous_readonly = this.readonly;
2341 if (this.viewmanager) {
2342 this.is_loaded = this.is_loaded.pipe(function() {
2343 self.viewmanager.stop();
2344 return $.when(self.load_views()).then(function() {
2345 self.reload_current_view();
2353 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2354 get_context: function() {
2355 this.context = this.o2m.build_context([this.o2m.name]);
2356 return this.context;
2360 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2361 _template: 'One2Many.listview',
2362 do_add_record: function () {
2363 if (this.options.editable) {
2364 this._super.apply(this, arguments);
2367 var pop = new openerp.web.form.SelectCreatePopup(this);
2368 pop.on_default_get.add(self.dataset.on_default_get);
2370 self.o2m.field.relation,
2372 title: _t("Create: ") + self.name,
2373 initial_view: "form",
2374 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2375 create_function: function(data, callback, error_callback) {
2376 return self.o2m.dataset.create(data).then(function(r) {
2377 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2378 self.o2m.dataset.on_change();
2379 }).then(callback, error_callback);
2381 read_function: function() {
2382 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2384 parent_view: self.o2m.view,
2385 child_name: self.o2m.name,
2386 form_view_options: {'not_interactible_on_create':true}
2388 self.o2m.build_domain(),
2389 self.o2m.build_context()
2391 pop.on_select_elements.add_last(function() {
2392 self.o2m.reload_current_view();
2396 do_activate_record: function(index, id) {
2398 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2399 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2400 title: _t("Open: ") + self.name,
2402 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2403 parent_view: self.o2m.view,
2404 child_name: self.o2m.name,
2405 read_function: function() {
2406 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2408 form_view_options: {'not_interactible_on_create':true},
2409 readonly: self.o2m.is_readonly()
2411 pop.on_write.add(function(id, data) {
2412 self.o2m.dataset.write(id, data, {}, function(r) {
2413 self.o2m.reload_current_view();
2417 do_button_action: function (name, id, callback) {
2419 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2420 return this._super(name, id, _.bind(def.resolve, def));
2424 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2425 form_template: 'One2Many.formview',
2426 on_loaded: function(data) {
2429 this.$form_header.find('button.oe_form_button_create').click(function() {
2430 self.do_save().then(self.on_button_new);
2435 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2436 template: 'FieldMany2Many',
2437 multi_selection: false,
2438 init: function(view, node) {
2439 this._super(view, node);
2440 this.list_id = _.uniqueId("many2many");
2441 this.is_loaded = $.Deferred();
2442 this.initial_is_loaded = this.is_loaded;
2443 this.is_setted = $.Deferred();
2446 this._super.apply(this, arguments);
2450 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2451 this.dataset.m2m = this;
2452 this.dataset.on_unlink.add_last(function(ids) {
2453 self.on_ui_change();
2456 this.is_setted.then(function() {
2460 set_value: function(value) {
2461 value = value || [];
2462 if (value.length >= 1 && value[0] instanceof Array) {
2463 value = value[0][2];
2466 this.dataset.set_ids(value);
2468 self.reload_content();
2469 this.is_setted.resolve();
2471 get_value: function() {
2472 return [commands.replace_with(this.dataset.ids)];
2474 validate: function() {
2475 this.invalid = false;
2477 is_readonly: function() {
2478 return this.readonly || this.force_readonly;
2480 load_view: function() {
2482 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2483 'addable': self.is_readonly() ? null : _t("Add"),
2484 'deletable': self.is_readonly() ? false : true,
2485 'selectable': self.multi_selection,
2486 'isClarkGable': self.is_readonly() ? false : true
2488 var embedded = (this.field.views || {}).tree;
2490 this.list_view.set_embedded_view(embedded);
2492 this.list_view.m2m_field = this;
2493 var loaded = $.Deferred();
2494 this.list_view.on_loaded.add_last(function() {
2495 self.initial_is_loaded.resolve();
2498 $.async_when().then(function () {
2499 self.list_view.appendTo($("#" + self.list_id));
2503 reload_content: function() {
2505 this.is_loaded = this.is_loaded.pipe(function() {
2506 return self.list_view.reload_content();
2509 update_dom: function() {
2510 this._super.apply(this, arguments);
2512 if (this.previous_readonly !== this.readonly) {
2513 this.previous_readonly = this.readonly;
2514 if (this.list_view) {
2515 this.is_loaded = this.is_loaded.pipe(function() {
2516 self.list_view.stop();
2517 return $.when(self.load_view()).then(function() {
2518 self.reload_content();
2526 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2527 get_context: function() {
2528 this.context = this.m2m.build_context();
2529 return this.context;
2535 * @extends openerp.web.ListView
2537 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2538 do_add_record: function () {
2539 var pop = new openerp.web.form.SelectCreatePopup(this);
2543 title: _t("Add: ") + this.name
2545 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2546 this.m2m_field.build_context()
2549 pop.on_select_elements.add(function(element_ids) {
2550 _.each(element_ids, function(element_id) {
2551 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2552 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2553 self.m2m_field.on_ui_change();
2554 self.reload_content();
2559 do_activate_record: function(index, id) {
2561 var pop = new openerp.web.form.FormOpenPopup(this);
2562 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2563 title: _t("Open: ") + this.name,
2564 readonly: this.widget_parent.is_readonly()
2566 pop.on_write_completed.add_last(function() {
2567 self.reload_content();
2574 * @extends openerp.web.OldWidget
2576 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2577 identifier_prefix: "selectcreatepopup",
2578 template: "SelectCreatePopup",
2582 * - initial_view: form or search (default search)
2583 * - disable_multiple_selection
2584 * - alternative_form_view
2585 * - create_function (defaults to a naive saving behavior)
2588 * - form_view_options
2589 * - list_view_options
2592 select_element: function(model, options, domain, context) {
2595 this.domain = domain || [];
2596 this.context = context || {};
2597 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2598 return self.create_row.apply(self, arguments);
2599 }, read_function: null});
2600 this.initial_ids = this.options.initial_ids;
2601 this.created_elements = [];
2602 this.render_element();
2603 openerp.web.form.dialog(this.$element, {
2607 title: options.title || ""
2614 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2616 this.dataset.create_function = function() {
2617 return self.options.create_function.apply(null, arguments).then(function(r) {
2618 self.created_elements.push(r.result);
2621 this.dataset.write_function = function() {
2622 return self.write_row.apply(self, arguments);
2624 this.dataset.read_function = this.options.read_function;
2625 this.dataset.parent_view = this.options.parent_view;
2626 this.dataset.child_name = this.options.child_name;
2627 this.dataset.on_default_get.add(this.on_default_get);
2628 if (this.options.initial_view == "search") {
2629 self.rpc('/web/session/eval_domain_and_context', {
2631 contexts: [this.context]
2632 }, function (results) {
2633 var search_defaults = {};
2634 _.each(results.context, function (value, key) {
2635 var match = /^search_default_(.*)$/.exec(key);
2637 search_defaults[match[1]] = value;
2640 self.setup_search_view(search_defaults);
2646 setup_search_view: function(search_defaults) {
2648 if (this.searchview) {
2649 this.searchview.stop();
2651 this.searchview = new openerp.web.SearchView(this,
2652 this.dataset, false, search_defaults);
2653 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2654 if (self.initial_ids) {
2655 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2656 contexts, groupbys);
2657 self.initial_ids = undefined;
2659 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2662 this.searchview.on_loaded.add_last(function () {
2663 self.view_list = new openerp.web.form.SelectCreateListView(self,
2664 self.dataset, false,
2665 _.extend({'deletable': false,
2666 'selectable': !self.options.disable_multiple_selection
2667 }, self.options.list_view_options || {}));
2668 self.view_list.popup = self;
2669 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2670 self.view_list.do_show();
2671 }).pipe(function() {
2672 self.searchview.do_search();
2674 self.view_list.on_loaded.add_last(function() {
2675 var $buttons = self.view_list.$element.find(".oe-actions");
2676 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2677 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2678 $cbutton.click(function() {
2681 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2682 if(self.options.disable_multiple_selection) {
2685 $sbutton.click(function() {
2686 self.on_select_elements(self.selected_ids);
2691 this.searchview.appendTo($("#" + this.element_id + "_search"));
2693 do_search: function(domains, contexts, groupbys) {
2695 this.rpc('/web/session/eval_domain_and_context', {
2696 domains: domains || [],
2697 contexts: contexts || [],
2698 group_by_seq: groupbys || []
2699 }, function (results) {
2700 self.view_list.do_search(results.domain, results.context, results.group_by);
2703 create_row: function() {
2705 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2706 wdataset.parent_view = this.options.parent_view;
2707 wdataset.child_name = this.options.child_name;
2708 return wdataset.create.apply(wdataset, arguments);
2710 write_row: function() {
2712 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2713 wdataset.parent_view = this.options.parent_view;
2714 wdataset.child_name = this.options.child_name;
2715 return wdataset.write.apply(wdataset, arguments);
2717 on_select_elements: function(element_ids) {
2719 on_click_element: function(ids) {
2720 this.selected_ids = ids || [];
2721 if(this.selected_ids.length > 0) {
2722 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2724 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2727 new_object: function() {
2729 if (this.searchview) {
2730 this.searchview.hide();
2732 if (this.view_list) {
2733 this.view_list.$element.hide();
2735 this.dataset.index = null;
2736 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2737 if (this.options.alternative_form_view) {
2738 this.view_form.set_embedded_view(this.options.alternative_form_view);
2740 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2741 this.view_form.on_loaded.add_last(function() {
2742 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2743 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2744 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2745 $nbutton.click(function() {
2746 $.when(self.view_form.do_save()).then(function() {
2747 self.view_form.reload_mutex.exec(function() {
2748 self.view_form.on_button_new();
2752 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2753 $nbutton.click(function() {
2754 $.when(self.view_form.do_save()).then(function() {
2755 self.view_form.reload_mutex.exec(function() {
2760 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2761 $cbutton.click(function() {
2765 this.view_form.do_show();
2767 check_exit: function() {
2768 if (this.created_elements.length > 0) {
2769 this.on_select_elements(this.created_elements);
2773 on_default_get: function(res) {}
2776 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2777 do_add_record: function () {
2778 this.popup.new_object();
2780 select_record: function(index) {
2781 this.popup.on_select_elements([this.dataset.ids[index]]);
2784 do_select: function(ids, records) {
2785 this._super(ids, records);
2786 this.popup.on_click_element(ids);
2792 * @extends openerp.web.OldWidget
2794 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2795 identifier_prefix: "formopenpopup",
2796 template: "FormOpenPopup",
2799 * - alternative_form_view
2800 * - auto_write (default true)
2804 * - form_view_options
2807 show_element: function(model, row_id, context, options) {
2809 this.row_id = row_id;
2810 this.context = context || {};
2811 this.options = _.defaults(options || {}, {"auto_write": true});
2812 this.render_element();
2813 this.$element.dialog({
2814 title: options.title || '',
2823 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2824 this.dataset.fop = this;
2825 this.dataset.ids = [this.row_id];
2826 this.dataset.index = 0;
2827 this.dataset.parent_view = this.options.parent_view;
2828 this.dataset.child_name = this.options.child_name;
2829 this.setup_form_view();
2831 on_write: function(id, data) {
2832 if (!this.options.auto_write)
2835 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2836 wdataset.parent_view = this.options.parent_view;
2837 wdataset.child_name = this.options.child_name;
2838 wdataset.write(id, data, {}, function(r) {
2839 self.on_write_completed();
2842 on_write_completed: function() {},
2843 setup_form_view: function() {
2845 var FormClass = this.options.readonly
2846 ? openerp.web.views.get_object('page')
2847 : openerp.web.views.get_object('form');
2848 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2849 if (this.options.alternative_form_view) {
2850 this.view_form.set_embedded_view(this.options.alternative_form_view);
2852 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2853 this.view_form.on_loaded.add_last(function() {
2854 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2855 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2856 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2857 $nbutton.click(function() {
2858 self.view_form.do_save().then(function() {
2862 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2863 $cbutton.click(function() {
2866 if (self.options.readonly) {
2868 $cbutton.text(_t("Close"));
2870 self.view_form.do_show();
2872 this.dataset.on_write.add(this.on_write);
2876 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2877 read_ids: function() {
2878 if (this.fop.options.read_function) {
2879 return this.fop.options.read_function.apply(null, arguments);
2881 return this._super.apply(this, arguments);
2886 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2887 template: 'FieldReference',
2888 init: function(view, node) {
2889 this._super(view, node);
2890 this.fields_view = {
2893 selection: view.fields_view.fields[this.name].selection
2900 this.get_fields_values = view.get_fields_values;
2901 this.do_onchange = this.on_form_changed = this.on_nop;
2902 this.dataset = this.view.dataset;
2903 this.widgets_counter = 0;
2904 this.view_id = 'reference_' + _.uniqueId();
2907 this.fields_order = [];
2908 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2912 this.reference_ready = true;
2913 this.selection.on_value_changed.add_last(this.on_selection_changed);
2914 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2919 on_nop: function() {
2921 on_selection_changed: function() {
2922 if (this.reference_ready) {
2923 var sel = this.selection.get_value();
2924 this.m2o.field.relation = sel;
2925 this.m2o.set_value(null);
2926 this.m2o.$element.toggle(sel !== false);
2931 this.selection.start();
2934 is_valid: function() {
2935 return this.required === false || typeof(this.get_value()) === 'string';
2937 is_dirty: function() {
2938 return this.selection.is_dirty() || this.m2o.is_dirty();
2940 set_value: function(value) {
2942 this.reference_ready = false;
2943 var vals = [], sel_val, m2o_val;
2944 if (typeof(value) === 'string') {
2945 vals = value.split(',');
2947 sel_val = vals[0] || false;
2948 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2949 this.selection.set_value(sel_val);
2950 this.m2o.field.relation = sel_val;
2951 this.m2o.set_value(m2o_val);
2952 this.m2o.$element.toggle(sel_val !== false);
2953 this.reference_ready = true;
2955 get_value: function() {
2956 var model = this.selection.get_value(),
2957 id = this.m2o.get_value();
2958 if (typeof(model) === 'string' && typeof(id) === 'number') {
2959 return model + ',' + id;
2966 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2967 init: function(view, node) {
2968 this._super(view, node);
2969 this.iframe = this.element_id + '_iframe';
2970 this.binary_value = false;
2973 this._super.apply(this, arguments);
2974 this.$element.find('input.oe-binary-file').change(this.on_file_change);
2975 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2976 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2978 human_filesize : function(size) {
2979 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2981 while (size >= 1024) {
2985 return size.toFixed(2) + ' ' + units[i];
2987 on_file_change: function(e) {
2988 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2989 // http://www.html5rocks.com/tutorials/file/dndfiles/
2990 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2991 window[this.iframe] = this.on_file_uploaded;
2992 if ($(e.target).val() != '') {
2993 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2994 this.$element.find('form.oe-binary-form').submit();
2995 this.$element.find('.oe-binary-progress').show();
2996 this.$element.find('.oe-binary').hide();
2999 on_file_uploaded: function(size, name, content_type, file_base64) {
3000 delete(window[this.iframe]);
3001 if (size === false) {
3002 this.do_warn("File Upload", "There was a problem while uploading your file");
3003 // TODO: use openerp web crashmanager
3004 console.warn("Error while uploading file : ", name);
3006 this.on_file_uploaded_and_valid.apply(this, arguments);
3007 this.on_ui_change();
3009 this.$element.find('.oe-binary-progress').hide();
3010 this.$element.find('.oe-binary').show();
3012 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3014 on_save_as: function() {
3015 var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
3016 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
3017 '&filename_field=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
3020 on_clear: function() {
3021 if (this.value !== false) {
3023 this.binary_value = false;
3024 this.on_ui_change();
3030 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3031 template: 'FieldBinaryFile',
3032 update_dom: function() {
3033 this._super.apply(this, arguments);
3034 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3035 this.$element.find('input[type=text]').prop('disabled', this.readonly);
3037 set_value: function(value) {
3038 this._super.apply(this, arguments);
3040 if (this.node.attrs.filename) {
3041 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3043 show_value = (value != null && value !== false) ? value : '';
3045 this.$element.find('input').eq(0).val(show_value);
3047 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3048 this.value = file_base64;
3049 this.binary_value = true;
3050 var show_value = name + " (" + this.human_filesize(size) + ")";
3051 this.$element.find('input').eq(0).val(show_value);
3052 this.set_filename(name);
3054 set_filename: function(value) {
3055 var filename = this.node.attrs.filename;
3056 if (this.view.fields[filename]) {
3057 this.view.fields[filename].set_value(value);
3058 this.view.fields[filename].on_ui_change();
3061 on_clear: function() {
3062 this._super.apply(this, arguments);
3063 this.$element.find('input').eq(0).val('');
3064 this.set_filename('');
3068 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3069 template: 'FieldBinaryImage',
3071 this._super.apply(this, arguments);
3072 this.$image = this.$element.find('img.oe-binary-image');
3074 update_dom: function() {
3075 this._super.apply(this, arguments);
3076 this.$element.find('.oe-binary').toggle(!this.readonly);
3078 set_value: function(value) {
3079 this._super.apply(this, arguments);
3080 this.set_image_maxwidth();
3081 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3082 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3083 this.$image.attr('src', url);
3085 set_image_maxwidth: function() {
3086 this.$image.css('max-width', this.$element.width());
3088 on_file_change: function() {
3089 this.set_image_maxwidth();
3090 this._super.apply(this, arguments);
3092 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3093 this.value = file_base64;
3094 this.binary_value = true;
3095 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3097 on_clear: function() {
3098 this._super.apply(this, arguments);
3099 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3103 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3104 template: "EmptyComponent",
3107 this.selected_value = null;
3111 set_value: function(value) {
3113 this.selected_value = value;
3117 render_list: function() {
3119 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3120 function(x) { return _.str.trim(x); });
3121 shown = _.select(shown, function(x) { return x.length > 0; });
3123 if (shown.length == 0) {
3124 this.to_show = this.field.selection;
3126 this.to_show = _.select(this.field.selection, function(x) {
3127 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3131 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3132 this.$element.html(content);
3134 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3135 var color = colors[this.selected_value];
3137 var elem = this.$element.find("li.oe-arrow-list-selected span");
3138 elem.css("border-color", color);
3139 if (this.check_white(color))
3140 elem.css("color", "white");
3141 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3142 elem.css("border-left-color", "rgba(0,0,0,0)");
3143 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3144 elem.css("border-color", "rgba(0,0,0,0)");
3145 elem.css("border-left-color", color);
3148 check_white: function(color) {
3149 var div = $("<div></div>");
3150 div.css("display", "none");
3151 div.css("color", color);
3152 div.appendTo($("body"));
3153 var ncolor = div.css("color");
3155 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3159 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3160 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3168 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3169 render: function () {
3170 var $root = $('<div class="oe_form_html_view">');
3171 this.render_children(this, $root);
3172 return $root.html();
3174 render_children: function (object, $into) {
3176 fields = this.view.fields_view.fields;
3177 _(object.children).each(function (child) {
3178 if (typeof child === 'string') {
3180 } else if (child.tag === 'field') {
3182 new (self.view.registry.get_object('frame'))(
3183 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3186 var $child = $(document.createElement(child.tag))
3189 self.render_children(child, $child);
3197 * Registry of form widgets, called by :js:`openerp.web.FormView`
3199 openerp.web.form.widgets = new openerp.web.Registry({
3200 'frame' : 'openerp.web.form.WidgetFrame',
3201 'group' : 'openerp.web.form.WidgetGroup',
3202 'notebook' : 'openerp.web.form.WidgetNotebook',
3203 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3204 'separator' : 'openerp.web.form.WidgetSeparator',
3205 'label' : 'openerp.web.form.WidgetLabel',
3206 'button' : 'openerp.web.form.WidgetButton',
3207 'char' : 'openerp.web.form.FieldChar',
3208 'email' : 'openerp.web.form.FieldEmail',
3209 'url' : 'openerp.web.form.FieldUrl',
3210 'text' : 'openerp.web.form.FieldText',
3211 'text_wiki' : 'openerp.web.form.FieldText',
3212 'date' : 'openerp.web.form.FieldDate',
3213 'datetime' : 'openerp.web.form.FieldDatetime',
3214 'selection' : 'openerp.web.form.FieldSelection',
3215 'many2one' : 'openerp.web.form.FieldMany2One',
3216 'many2many' : 'openerp.web.form.FieldMany2Many',
3217 'one2many' : 'openerp.web.form.FieldOne2Many',
3218 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3219 'reference' : 'openerp.web.form.FieldReference',
3220 'boolean' : 'openerp.web.form.FieldBoolean',
3221 'float' : 'openerp.web.form.FieldFloat',
3222 'integer': 'openerp.web.form.FieldFloat',
3223 'float_time': 'openerp.web.form.FieldFloat',
3224 'progressbar': 'openerp.web.form.FieldProgressBar',
3225 'image': 'openerp.web.form.FieldBinaryImage',
3226 'binary': 'openerp.web.form.FieldBinaryFile',
3227 'statusbar': 'openerp.web.form.FieldStatus',
3228 'html': 'openerp.web.form.WidgetHtml'
3234 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: