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)).pipe(self.on_record_loaded);
148 result.pipe(function() {
149 self.$element.css('visibility', 'visible');
152 self.sidebar.$element.show();
157 do_hide: function () {
160 this.sidebar.$element.hide();
163 on_record_loaded: function(record) {
164 var self = this, set_values = [];
166 throw new Error("Form: No record received");
168 this.datarecord = record;
170 _(this.fields).each(function (field, f) {
172 var result = field.set_value(self.datarecord[f] || false);
173 set_values.push(result);
174 $.when(result).then(function() {
178 return $.when.apply(null, set_values).pipe(function() {
180 self.show_invalid = false;
181 // New record: Second pass in order to trigger the onchanges
182 // respecting the fields order defined in the view
183 _.each(self.fields_order, function(field_name) {
184 if (record[field_name] !== undefined) {
185 var field = self.fields[field_name];
187 self.do_onchange(field);
191 self.on_form_changed();
192 self.is_initialized.resolve();
193 self.show_invalid = true;
194 self.do_update_pager(record.id == null);
196 self.sidebar.attachments.do_update();
198 if (self.default_focus_field && !self.embedded_view) {
199 self.default_focus_field.focus();
202 self.do_push_state({id:record.id});
206 on_form_changed: function() {
207 for (var w in this.widgets) {
209 w.process_modifiers();
213 on_pager_action: function(action) {
214 if (this.can_be_discarded()) {
217 this.dataset.index = 0;
220 this.dataset.previous();
226 this.dataset.index = this.dataset.ids.length - 1;
232 do_update_pager: function(hide_index) {
233 var $pager = this.$form_header.find('div.oe_form_pager');
234 var index = hide_index ? '-' : this.dataset.index + 1;
235 $pager.find('button').prop('disabled', this.dataset.ids.length < 2)
236 $pager.find('span.oe_pager_index').html(index);
237 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
239 parse_on_change: function (on_change, widget) {
241 var onchange = _.str.trim(on_change);
242 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
247 var method = call[1];
248 if (!_.str.trim(call[2])) {
249 return {method: method, args: [], context_index: null}
252 var argument_replacement = {
253 'False': function () {return false;},
254 'True': function () {return true;},
255 'None': function () {return null;},
256 'context': function (i) {
258 var ctx = widget.build_context ? widget.build_context() : {};
262 var parent_fields = null, context_index = null;
263 var args = _.map(call[2].split(','), function (a, i) {
264 var field = _.str.trim(a);
266 // literal constant or context
267 if (field in argument_replacement) {
268 return argument_replacement[field](i);
271 if (/^-?\d+(\.\d+)?$/.test(field)) {
272 return Number(field);
275 if (self.fields[field]) {
276 var value = self.fields[field].get_on_change_value();
277 return value == null ? false : value;
280 var splitted = field.split('.');
281 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
282 if (parent_fields === null) {
283 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
285 var p_val = parent_fields[_.str.trim(splitted[1])];
286 if (p_val !== undefined) {
287 return p_val == null ? false : p_val;
291 var first_char = field[0], last_char = field[field.length-1];
292 if ((first_char === '"' && last_char === '"')
293 || (first_char === "'" && last_char === "'")) {
294 return field.slice(1, -1);
297 throw new Error("Could not get field with name '" + field +
298 "' for onchange '" + onchange + "'");
304 context_index: context_index
307 do_onchange: function(widget, processed) {
309 return this.on_change_mutex.exec(function() {
311 processed = processed || [];
312 var on_change = widget.node.attrs.on_change;
314 var change_spec = self.parse_on_change(on_change, widget);
317 url: '/web/dataset/call',
320 return self.rpc(ajax, {
321 model: self.dataset.model,
322 method: change_spec.method,
323 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
324 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
325 }).pipe(function(response) {
326 return self.on_processed_onchange(response, processed);
329 console.warn("Wrong on_change format", on_change);
334 return $.Deferred().reject();
338 on_processed_onchange: function(response, processed) {
340 var result = response;
342 for (var f in result.value) {
343 var field = this.fields[f];
344 // If field is not defined in the view, just ignore it
346 var value = result.value[f];
347 processed.push(field.name);
348 if (field.get_value() != value) {
349 field.set_value(value);
351 if (_.indexOf(processed, field.name) < 0) {
352 this.do_onchange(field, processed);
357 this.on_form_changed();
359 if (!_.isEmpty(result.warning)) {
360 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
363 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
370 return $.Deferred().resolve();
373 return $.Deferred().reject();
376 on_button_save: function() {
378 return this.do_save().then(function(result) {
379 self.do_prev_view(result.created);
382 on_button_cancel: function() {
383 return this.do_prev_view();
385 on_button_new: function() {
387 var def = $.Deferred();
388 $.when(this.has_been_loaded).then(function() {
389 if (self.can_be_discarded()) {
390 var keys = _.keys(self.fields_view.fields);
392 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
396 self.on_record_loaded({}).then(function() {
402 return def.promise();
404 can_be_discarded: function() {
405 return true; // FIXME: Disabled until the page view and button refactoring is done
406 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
409 * Triggers saving the form's record. Chooses between creating a new
410 * record or saving an existing one depending on whether the record
411 * already has an id property.
413 * @param {Function} success callback on save success
414 * @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)
416 do_save: function(success, prepend_on_create) {
418 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
420 var form_invalid = false,
422 first_invalid_field = null;
423 for (var f in self.fields) {
428 if (!first_invalid_field) {
429 first_invalid_field = f;
431 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
432 // Special case 'id' field, do not save this field
433 // on 'create' : save all non readonly fields
434 // on 'edit' : save non readonly modified fields
435 values[f.name] = f.get_value();
439 first_invalid_field.focus();
441 return $.Deferred().reject();
444 if (!self.datarecord.id) {
445 console.log("FormView(", self, ") : About to create", values);
446 save_deferral = self.dataset.create(values).pipe(function(r) {
447 return self.on_created(r, undefined, prepend_on_create);
449 } else if (_.isEmpty(values)) {
450 console.log("FormView(", self, ") : Nothing to save");
451 save_deferral = $.Deferred().resolve({}).promise();
453 console.log("FormView(", self, ") : About to save", values);
454 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
455 return self.on_saved(r);
458 return save_deferral.then(success);
462 return $.Deferred().reject();
466 on_invalid: function() {
468 _.each(this.fields, function(f) {
470 msg += "<li>" + f.string + "</li>";
474 this.do_warn("The following fields are invalid :", msg);
476 on_saved: function(r, success) {
478 // should not happen in the server, but may happen for internal purpose
479 return $.Deferred().reject();
481 return $.when(this.reload()).pipe(function () {
482 return $.when(r).then(success); }, null);
486 * Updates the form' dataset to contain the new record:
488 * * Adds the newly created record to the current dataset (at the end by
490 * * Selects that record (sets the dataset's index to point to the new
492 * * Updates the pager and sidebar displays
495 * @param {Function} success callback to execute after having updated the dataset
496 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
498 on_created: function(r, success, prepend_on_create) {
500 // should not happen in the server, but may happen for internal purpose
501 return $.Deferred().reject();
503 this.datarecord.id = r.result;
504 if (!prepend_on_create) {
505 this.dataset.ids.push(this.datarecord.id);
506 this.dataset.index = this.dataset.ids.length - 1;
508 this.dataset.ids.unshift(this.datarecord.id);
509 this.dataset.index = 0;
511 this.do_update_pager();
513 this.sidebar.attachments.do_update();
515 openerp.log("The record has been created with id #" + this.datarecord.id);
517 return $.when(_.extend(r, {created: true})).then(success);
520 on_action: function (action) {
521 console.debug('Executing action', action);
525 return this.reload_mutex.exec(function() {
526 if (self.dataset.index == null || self.dataset.index < 0) {
527 return $.when(self.on_button_new());
529 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
533 get_fields_values: function(blacklist) {
534 blacklist = blacklist || [];
536 _.each(this.fields, function(value, key) {
537 if (_.include(blacklist, key))
539 var val = value.get_value();
544 get_selected_ids: function() {
545 var id = this.dataset.ids[this.dataset.index];
546 return id ? [id] : [];
548 recursive_save: function() {
550 return $.when(this.do_save()).pipe(function(res) {
551 if (self.dataset.parent_view)
552 return self.dataset.parent_view.recursive_save();
555 is_dirty: function() {
556 return _.any(this.fields, function (value) {
557 return value.is_dirty();
560 is_interactible_record: function() {
561 var id = this.datarecord.id;
563 if (this.options.not_interactible_on_create)
565 } else if (typeof(id) === "string") {
566 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
571 sidebar_context: function () {
572 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
575 openerp.web.FormDialog = openerp.web.Dialog.extend({
576 init: function(parent, options, view_id, dataset) {
577 this._super(parent, options);
578 this.dataset = dataset;
579 this.view_id = view_id;
584 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
588 this.form.appendTo(this.$element);
589 this.form.on_created.add_last(this.on_form_dialog_saved);
590 this.form.on_saved.add_last(this.on_form_dialog_saved);
593 select_id: function(id) {
594 if (this.form.dataset.select_id(id)) {
595 return this.form.do_show();
597 this.do_warn("Could not find id in dataset");
598 return $.Deferred().reject();
601 on_form_dialog_saved: function(r) {
607 openerp.web.form = {};
609 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
610 init: function(parent, form_view) {
611 var $section = parent.add_section(_t('Attachments'), 'attachments');
612 this.$div = $('<div class="oe-sidebar-attachments"></div>');
613 $section.append(this.$div);
615 this._super(parent, $section.attr('id'));
616 this.view = form_view;
618 do_update: function() {
619 if (!this.view.datarecord.id) {
620 this.on_attachments_loaded([]);
622 (new openerp.web.DataSetSearch(
623 this, 'ir.attachment', this.view.dataset.get_context(),
625 ['res_model', '=', this.view.dataset.model],
626 ['res_id', '=', this.view.datarecord.id],
627 ['type', 'in', ['binary', 'url']]
628 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
631 on_attachments_loaded: function(attachments) {
632 this.attachments = attachments;
633 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
634 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
635 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
637 on_attachment_changed: function(e) {
638 window[this.element_id + '_iframe'] = this.do_update;
639 var $e = $(e.target);
640 if ($e.val() != '') {
641 this.$element.find('form.oe-binary-form').submit();
642 $e.parent().find('input[type=file]').prop('disabled', true);
643 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
646 on_attachment_delete: function(e) {
647 var self = this, $e = $(e.currentTarget);
648 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
649 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
650 this.rpc('/web/dataset/unlink', {
651 model: 'ir.attachment',
652 ids: [parseInt($e.attr('data-id'))]
654 $e.parent().remove();
655 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
661 openerp.web.form.compute_domain = function(expr, fields) {
663 for (var i = expr.length - 1; i >= 0; i--) {
665 if (ex.length == 1) {
666 var top = stack.pop();
669 stack.push(stack.pop() || top);
672 stack.push(stack.pop() && top);
678 throw new Error('Unknown domain operator ' + ex);
682 var field = fields[ex[0]];
684 throw new Error("Domain references unknown field : " + ex[0]);
686 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
690 switch (op.toLowerCase()) {
693 stack.push(field_value == val);
697 stack.push(field_value != val);
700 stack.push(field_value < val);
703 stack.push(field_value > val);
706 stack.push(field_value <= val);
709 stack.push(field_value >= val);
712 stack.push(_(val).contains(field_value));
715 stack.push(!_(val).contains(field_value));
718 console.warn("Unsupported operator in modifiers :", op);
721 return _.all(stack, _.identity);
724 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
726 identifier_prefix: 'formview-widget-',
728 * @constructs openerp.web.form.Widget
729 * @extends openerp.web.Widget
734 init: function(view, node) {
737 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
738 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
739 this.type = this.type || node.tag;
740 this.element_name = this.element_name || this.type;
741 this.element_class = [
742 'formview', this.view.view_id, this.element_name,
743 this.view.widgets_counter++].join("_");
747 this.view.widgets[this.element_class] = this;
748 this.children = node.children;
749 this.colspan = parseInt(node.attrs.colspan || 1, 10);
750 this.decrease_max_width = 0;
752 this.string = this.string || node.attrs.string;
753 this.help = this.help || node.attrs.help;
754 this.invisible = this.modifiers['invisible'] === true;
755 this.classname = 'oe_form_' + this.type;
757 this.align = parseFloat(this.node.attrs.align);
758 if (isNaN(this.align) || this.align === 1) {
759 this.align = 'right';
760 } else if (this.align === 0) {
763 this.align = 'center';
767 this.width = this.node.attrs.width;
770 this.$element = this.view.$element.find(
771 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
773 process_modifiers: function() {
774 var compute_domain = openerp.web.form.compute_domain;
775 for (var a in this.modifiers) {
776 this[a] = compute_domain(this.modifiers[a], this.view.fields);
779 update_dom: function() {
780 this.$element.toggle(!this.invisible);
783 var template = this.template;
784 return QWeb.render(template, { "widget": this });
786 do_attach_tooltip: function(widget, trigger, options) {
787 widget = widget || this;
788 trigger = trigger || this.$element;
792 content: function() {
793 var template = widget.template + '.tooltip';
794 if (!QWeb.has_template(template)) {
795 template = 'WidgetLabel.tooltip';
797 return QWeb.render(template, {
798 debug: openerp.connection.debug,
803 trigger.tipTip(options);
805 _build_view_fields_values: function(blacklist) {
806 var a_dataset = this.view.dataset;
807 var fields_values = this.view.get_fields_values(blacklist);
808 var active_id = a_dataset.ids[a_dataset.index];
809 _.extend(fields_values, {
810 active_id: active_id || false,
811 active_ids: active_id ? [active_id] : [],
812 active_model: a_dataset.model,
815 if (a_dataset.parent_view) {
816 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
818 return fields_values;
820 _build_eval_context: function(blacklist) {
821 var a_dataset = this.view.dataset;
822 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
825 * Builds a new context usable for operations related to fields by merging
826 * the fields'context with the action's context.
828 build_context: function(blacklist) {
829 // only use the model's context if there is not context on the node
830 var v_context = this.node.attrs.context;
832 v_context = (this.field || {}).context || {};
835 if (v_context.__ref || true) { //TODO: remove true
836 var fields_values = this._build_eval_context(blacklist);
837 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
841 build_domain: function() {
842 var f_domain = this.field.domain || [];
843 var n_domain = this.node.attrs.domain || null;
844 // if there is a domain on the node, overrides the model's domain
845 var final_domain = n_domain !== null ? n_domain : f_domain;
846 if (!(final_domain instanceof Array) || true) { //TODO: remove true
847 var fields_values = this._build_eval_context();
848 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
854 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
855 template: 'WidgetFrame',
856 init: function(view, node) {
857 this._super(view, node);
858 this.columns = parseInt(node.attrs.col || 4, 10);
863 for (var i = 0; i < node.children.length; i++) {
864 var n = node.children[i];
865 if (n.tag == "newline") {
871 this.set_row_cells_with(this.table[this.table.length - 1]);
874 if (this.table.length) {
875 this.set_row_cells_with(this.table[this.table.length - 1]);
878 this.table.push(row);
883 set_row_cells_with: function(row) {
886 row_length = row.length;
887 for (var i = 0; i < row.length; i++) {
888 if (row[i].always_invisible) {
891 bypass += row[i].width === undefined ? 0 : 1;
892 max_width -= row[i].decrease_max_width;
895 var size_unit = Math.round(max_width / (this.columns - bypass)),
897 for (var i = 0; i < row.length; i++) {
899 if (w.always_invisible) {
902 colspan_sum += w.colspan;
903 if (w.width === undefined) {
904 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
906 w.width = width + '%';
910 handle_node: function(node) {
912 if (node.tag == 'field') {
913 type = this.view.fields_view.fields[node.attrs.name] || {};
914 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
915 // This way we can retain backward compatibility between addons and old clients
916 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
917 node.attrs.nolabel = '1';
920 var widget = new (this.view.registry.get_any(
921 [node.attrs.widget, type.type, node.tag])) (this.view, node);
922 if (node.tag == 'field') {
923 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
924 this.view.default_focus_field = widget;
926 if (node.attrs.nolabel != '1') {
927 var label = new (this.view.registry.get_object('label')) (this.view, node);
928 label["for"] = widget;
929 this.add_widget(label, widget.colspan + 1);
932 this.add_widget(widget);
934 add_widget: function(widget, colspan) {
935 var current_row = this.table[this.table.length - 1];
936 if (!widget.always_invisible) {
937 colspan = colspan || widget.colspan;
938 if (current_row.length && (this.x + colspan) > this.columns) {
939 current_row = this.add_row();
941 this.x += widget.colspan;
943 current_row.push(widget);
948 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
949 template: 'WidgetGroup'
952 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
953 template: 'WidgetNotebook',
954 init: function(view, node) {
955 this._super(view, node);
957 for (var i = 0; i < node.children.length; i++) {
958 var n = node.children[i];
959 if (n.tag == "page") {
960 var page = new (this.view.registry.get_object('notebookpage'))(
961 this.view, n, this, this.pages.length);
962 this.pages.push(page);
968 this._super.apply(this, arguments);
969 this.$element.find('> ul > li').each(function (index, tab_li) {
970 var page = self.pages[index],
971 id = _.uniqueId(self.element_name + '-');
972 page.element_id = id;
973 $(tab_li).find('a').attr('href', '#' + id);
975 this.$element.find('> div').each(function (index, page) {
976 page.id = self.pages[index].element_id;
978 this.$element.tabs();
979 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
980 if (openerp.connection.debug) {
981 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
982 defaultPosition: 'top'
986 do_select_first_visible_tab: function() {
987 for (var i = 0; i < this.pages.length; i++) {
988 var page = this.pages[i];
989 if (page.invisible === false) {
990 this.$element.tabs('select', page.index);
997 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
998 template: 'WidgetNotebookPage',
999 init: function(view, node, notebook, index) {
1000 this.notebook = notebook;
1002 this.element_name = 'page_' + index;
1003 this._super(view, node);
1006 this._super.apply(this, arguments);
1007 this.$element_tab = this.notebook.$element.find(
1008 '> ul > li:eq(' + this.index + ')');
1010 update_dom: function() {
1011 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1012 this.notebook.do_select_first_visible_tab();
1014 this.$element_tab.toggle(!this.invisible);
1015 this.$element.toggle(!this.invisible);
1019 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1020 template: 'WidgetSeparator',
1021 init: function(view, node) {
1022 this._super(view, node);
1023 this.orientation = node.attrs.orientation || 'horizontal';
1024 if (this.orientation === 'vertical') {
1027 this.classname += '_' + this.orientation;
1031 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1032 template: 'WidgetButton',
1033 init: function(view, node) {
1034 this._super(view, node);
1035 this.force_disabled = false;
1037 // We don't have button key bindings in the webclient
1038 this.string = this.string.replace(/_/g, '');
1040 if (node.attrs.default_focus == '1') {
1041 // TODO fme: provide enter key binding to widgets
1042 this.view.default_focus_button = this;
1046 this._super.apply(this, arguments);
1047 this.$element.find("button").click(this.on_click);
1048 if (this.help || openerp.connection.debug) {
1049 this.do_attach_tooltip();
1052 on_click: function() {
1054 this.force_disabled = true;
1055 this.check_disable();
1056 this.execute_action().always(function() {
1057 self.force_disabled = false;
1058 self.check_disable();
1062 execute_action: function() {
1064 var exec_action = function() {
1065 if (self.node.attrs.confirm) {
1066 var def = $.Deferred();
1067 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1068 title: _t('Confirm'),
1071 {text: _t("Ok"), click: function() {
1072 self.on_confirmed().then(function() {
1075 $(this).dialog("close");
1078 {text: _t("Cancel"), click: function() {
1080 $(this).dialog("close");
1085 return def.promise();
1087 return self.on_confirmed();
1090 if (!this.node.attrs.special) {
1091 return this.view.recursive_save().pipe(exec_action);
1093 return exec_action();
1096 on_confirmed: function() {
1099 var context = this.node.attrs.context;
1100 if (context && context.__ref) {
1101 context = new openerp.web.CompoundContext(context);
1102 context.set_eval_context(this._build_eval_context());
1105 return this.view.do_execute_action(
1106 _.extend({}, this.node.attrs, {context: context}),
1107 this.view.dataset, this.view.datarecord.id, function () {
1111 update_dom: function() {
1113 this.check_disable();
1115 check_disable: function() {
1116 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1117 this.$element.find('button').prop('disabled', disabled);
1118 this.$element.find("button").css('color', disabled ? 'grey' : '');
1122 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1123 template: 'WidgetLabel',
1124 init: function(view, node) {
1125 this.element_name = 'label_' + node.attrs.name;
1127 this._super(view, node);
1129 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1130 this.template = "WidgetParagraph";
1131 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1132 // Widgets default to right-aligned, but paragraph defaults to
1134 if (isNaN(parseFloat(this.node.attrs.align))) {
1135 this.align = 'left';
1140 this.decrease_max_width = 1;
1144 render: function () {
1145 if (this['for'] && this.type !== 'label') {
1146 return QWeb.render(this.template, {widget: this['for']});
1148 // Actual label widgets should not have a false and have type label
1149 return QWeb.render(this.template, {widget: this});
1154 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1155 this.do_attach_tooltip(self['for']);
1157 this.$element.find("label").dblclick(function() {
1158 var widget = self['for'] || self;
1159 openerp.log(widget.element_class , widget);
1165 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1167 * @constructs openerp.web.form.Field
1168 * @extends openerp.web.form.Widget
1173 init: function(view, node) {
1174 this.name = node.attrs.name;
1175 this.value = undefined;
1176 view.fields[this.name] = this;
1177 view.fields_order.push(this.name);
1178 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1179 this.element_name = "field_" + this.name + "_" + this.type;
1181 this._super(view, node);
1183 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1186 this.field = view.fields_view.fields[node.attrs.name] || {};
1187 this.string = node.attrs.string || this.field.string;
1188 this.help = node.attrs.help || this.field.help;
1189 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1190 this.readonly = this.modifiers['readonly'] === true;
1191 this.required = this.modifiers['required'] === true;
1192 this.invalid = this.dirty = false;
1194 this.classname = 'oe_form_field_' + this.type;
1197 this._super.apply(this, arguments);
1198 if (this.field.translate) {
1199 this.view.translatable_fields.push(this);
1200 this.$element.find('.oe_field_translate').click(this.on_translate);
1202 if (this.nolabel && openerp.connection.debug) {
1203 this.do_attach_tooltip(this, this.$element, {
1204 defaultPosition: 'top'
1208 set_value: function(value) {
1210 this.invalid = false;
1212 this.on_value_changed();
1214 set_value_from_ui: function() {
1215 this.on_value_changed();
1217 on_value_changed: function() {
1219 on_translate: function() {
1220 this.view.open_translate_dialog(this);
1222 get_value: function() {
1225 is_valid: function() {
1226 return !this.invalid;
1228 is_dirty: function() {
1229 return this.dirty && !this.readonly;
1231 get_on_change_value: function() {
1232 return this.get_value();
1234 update_dom: function() {
1235 this._super.apply(this, arguments);
1236 if (this.field.translate) {
1237 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1239 if (!this.disable_utility_classes) {
1240 this.$element.toggleClass('disabled', this.readonly);
1241 this.$element.toggleClass('required', this.required);
1242 if (this.view.show_invalid) {
1243 this.$element.toggleClass('invalid', !this.is_valid());
1247 on_ui_change: function() {
1250 if (this.is_valid()) {
1251 this.set_value_from_ui();
1252 this.view.do_onchange(this);
1253 this.view.on_form_changed();
1258 validate: function() {
1259 this.invalid = false;
1266 get_definition_options: function() {
1267 if (!this.definition_options) {
1268 var str = this.node.attrs.options || '{}';
1269 this.definition_options = JSON.parse(str);
1271 return this.definition_options;
1275 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1276 template: 'FieldChar',
1277 init: function (view, node) {
1278 this._super(view, node);
1279 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1282 this._super.apply(this, arguments);
1283 this.$element.find('input').change(this.on_ui_change);
1285 set_value: function(value) {
1286 this._super.apply(this, arguments);
1287 var show_value = openerp.web.format_value(value, this, '');
1288 this.$element.find('input').val(show_value);
1291 update_dom: function() {
1292 this._super.apply(this, arguments);
1293 this.$element.find('input').prop('disabled', this.readonly);
1295 set_value_from_ui: function() {
1296 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1299 validate: function() {
1300 this.invalid = false;
1302 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1303 this.invalid = this.required && value === '';
1305 this.invalid = true;
1309 this.$element.find('input').focus();
1313 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1314 template: 'FieldEmail',
1316 this._super.apply(this, arguments);
1317 this.$element.find('button').click(this.on_button_clicked);
1319 on_button_clicked: function() {
1320 if (!this.value || !this.is_valid()) {
1321 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1323 location.href = 'mailto:' + this.value;
1328 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1329 template: 'FieldUrl',
1331 this._super.apply(this, arguments);
1332 this.$element.find('button').click(this.on_button_clicked);
1334 on_button_clicked: function() {
1336 this.do_warn("Resource error", "This resource is empty");
1338 window.open(this.value);
1343 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1344 init: function (view, node) {
1345 this._super(view, node);
1346 if (node.attrs.digits) {
1347 this.parse_digits(node.attrs.digits);
1349 this.digits = view.fields_view.fields[node.attrs.name].digits;
1352 parse_digits: function (digits_attr) {
1353 // could use a Python parser instead.
1354 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1355 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1357 set_value: function(value) {
1358 if (value === false || value === undefined) {
1359 // As in GTK client, floats default to 0
1362 this._super.apply(this, [value]);
1366 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1367 template: "web.datetimepicker",
1368 jqueryui_object: 'datetimepicker',
1369 type_of_date: "datetime",
1370 init: function(parent) {
1371 this._super(parent);
1372 this.name = parent.name;
1376 this.$input = this.$element.find('input.oe_datepicker_master');
1377 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1378 this.$input.change(this.on_change);
1380 onSelect: this.on_picker_select,
1384 showButtonPanel: true
1386 this.$element.find('img.oe_datepicker_trigger').click(function() {
1387 if (!self.readonly) {
1388 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1389 self.$input_picker.show();
1390 self.picker('show');
1391 self.$input_picker.hide();
1394 this.set_readonly(false);
1397 picker: function() {
1398 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1400 on_picker_select: function(text, instance) {
1401 var date = this.picker('getDate');
1402 this.$input.val(date ? this.format_client(date) : '').change();
1404 set_value: function(value) {
1406 this.$input.val(value ? this.format_client(value) : '');
1408 get_value: function() {
1411 set_value_from_ui: function() {
1412 var value = this.$input.val() || false;
1413 this.value = this.parse_client(value);
1415 set_readonly: function(readonly) {
1416 this.readonly = readonly;
1417 this.$input.prop('disabled', this.readonly);
1418 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1420 is_valid: function(required) {
1421 var value = this.$input.val();
1426 this.parse_client(value);
1434 this.$input.focus();
1436 parse_client: function(v) {
1437 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1439 format_client: function(v) {
1440 return openerp.web.format_value(v, {"widget": this.type_of_date});
1442 on_change: function() {
1443 if (this.is_valid()) {
1444 this.set_value_from_ui();
1449 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1450 jqueryui_object: 'datepicker',
1451 type_of_date: "date"
1454 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1455 template: "EmptyComponent",
1456 build_widget: function() {
1457 return new openerp.web.DateTimeWidget(this);
1461 this._super.apply(this, arguments);
1462 this.datewidget = this.build_widget();
1463 this.datewidget.on_change.add_last(this.on_ui_change);
1464 this.datewidget.appendTo(this.$element);
1466 set_value: function(value) {
1468 this.datewidget.set_value(value);
1470 get_value: function() {
1471 return this.datewidget.get_value();
1473 update_dom: function() {
1474 this._super.apply(this, arguments);
1475 this.datewidget.set_readonly(this.readonly);
1477 validate: function() {
1478 this.invalid = !this.datewidget.is_valid(this.required);
1481 this.datewidget.focus();
1485 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1486 build_widget: function() {
1487 return new openerp.web.DateWidget(this);
1491 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1492 template: 'FieldText',
1494 this._super.apply(this, arguments);
1495 this.$element.find('textarea').change(this.on_ui_change);
1496 this.resized = false;
1498 set_value: function(value) {
1499 this._super.apply(this, arguments);
1500 var show_value = openerp.web.format_value(value, this, '');
1501 this.$element.find('textarea').val(show_value);
1502 if (!this.resized && this.view.options.resize_textareas) {
1503 this.do_resize(this.view.options.resize_textareas);
1504 this.resized = true;
1507 update_dom: function() {
1508 this._super.apply(this, arguments);
1509 this.$element.find('textarea').prop('disabled', this.readonly);
1511 set_value_from_ui: function() {
1512 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1515 validate: function() {
1516 this.invalid = false;
1518 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1519 this.invalid = this.required && value === '';
1521 this.invalid = true;
1525 this.$element.find('textarea').focus();
1527 do_resize: function(max_height) {
1528 max_height = parseInt(max_height, 10);
1529 var $input = this.$element.find('textarea'),
1530 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1532 $div.text($input.val());
1533 _.each('font-family,font-size,white-space'.split(','), function(style) {
1534 $div.css(style, $input.css(style));
1536 $div.appendTo($('body'));
1537 new_height = $div.height();
1538 if (new_height < 90) {
1541 if (!isNaN(max_height) && new_height > max_height) {
1542 new_height = max_height;
1545 $input.height(new_height);
1548 this.resized = false;
1552 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1553 template: 'FieldBoolean',
1556 this._super.apply(this, arguments);
1557 this.$element.find('input').click(self.on_ui_change);
1559 set_value: function(value) {
1560 this._super.apply(this, arguments);
1561 this.$element.find('input')[0].checked = value;
1563 set_value_from_ui: function() {
1564 this.value = this.$element.find('input').is(':checked');
1567 update_dom: function() {
1568 this._super.apply(this, arguments);
1569 this.$element.find('input').prop('disabled', this.readonly);
1572 this.$element.find('input').focus();
1576 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1577 template: 'FieldProgressBar',
1579 this._super.apply(this, arguments);
1580 this.$element.find('div').progressbar({
1582 disabled: this.readonly
1585 set_value: function(value) {
1586 this._super.apply(this, arguments);
1587 var show_value = Number(value);
1588 if (isNaN(show_value)) {
1591 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1595 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1596 // to replace view editor
1599 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1600 template: 'FieldSelection',
1601 init: function(view, node) {
1603 this._super(view, node);
1604 this.values = _.clone(this.field.selection);
1605 _.each(this.values, function(v, i) {
1606 if (v[0] === false && v[1] === '') {
1607 self.values.splice(i, 1);
1610 this.values.unshift([false, '']);
1613 // Flag indicating whether we're in an event chain containing a change
1614 // event on the select, in order to know what to do on keyup[RETURN]:
1615 // * If the user presses [RETURN] as part of changing the value of a
1616 // selection, we should just let the value change and not let the
1617 // event broadcast further (e.g. to validating the current state of
1618 // the form in editable list view, which would lead to saving the
1619 // current row or switching to the next one)
1620 // * If the user presses [RETURN] with a select closed (side-effect:
1621 // also if the user opened the select and pressed [RETURN] without
1622 // changing the selected value), takes the action as validating the
1624 var ischanging = false;
1625 this._super.apply(this, arguments);
1626 this.$element.find('select')
1627 .change(this.on_ui_change)
1628 .change(function () { ischanging = true; })
1629 .click(function () { ischanging = false; })
1630 .keyup(function (e) {
1631 if (e.which !== 13 || !ischanging) { return; }
1632 e.stopPropagation();
1636 set_value: function(value) {
1637 value = value === null ? false : value;
1638 value = value instanceof Array ? value[0] : value;
1641 for (var i = 0, ii = this.values.length; i < ii; i++) {
1642 if (this.values[i][0] === value) index = i;
1644 this.$element.find('select')[0].selectedIndex = index;
1646 set_value_from_ui: function() {
1647 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1650 update_dom: function() {
1651 this._super.apply(this, arguments);
1652 this.$element.find('select').prop('disabled', this.readonly);
1654 validate: function() {
1655 var value = this.values[this.$element.find('select')[0].selectedIndex];
1656 this.invalid = !(value && !(this.required && value[0] === false));
1659 this.$element.find('select').focus();
1663 // jquery autocomplete tweak to allow html
1665 var proto = $.ui.autocomplete.prototype,
1666 initSource = proto._initSource;
1668 function filter( array, term ) {
1669 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1670 return $.grep( array, function(value) {
1671 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1676 _initSource: function() {
1677 if ( this.options.html && $.isArray(this.options.source) ) {
1678 this.source = function( request, response ) {
1679 response( filter( this.options.source, request.term ) );
1682 initSource.call( this );
1686 _renderItem: function( ul, item) {
1687 return $( "<li></li>" )
1688 .data( "item.autocomplete", item )
1689 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1695 openerp.web.form.dialog = function(content, options) {
1696 options = _.extend({
1701 options.autoOpen = true;
1702 var dialog = new openerp.web.Dialog(null, options).open();
1703 return dialog.$element.html(content);
1706 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1707 template: 'FieldMany2One',
1708 init: function(view, node) {
1709 this._super(view, node);
1712 this.cm_id = _.uniqueId('m2o_cm_');
1713 this.last_search = [];
1714 this.tmp_value = undefined;
1719 this.$input = this.$element.find("input");
1720 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1721 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1724 var init_context_menu_def = $.Deferred().then(function(e) {
1725 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1726 rdataset.call("get", ['action', 'client_action_relate',
1727 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1728 .then(function(result) {
1729 self.related_entries = result;
1731 var $cmenu = $("#" + self.cm_id);
1732 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1734 bindings[self.cm_id + "_search"] = function() {
1735 self._search_create_popup("search");
1737 bindings[self.cm_id + "_create"] = function() {
1738 self._search_create_popup("form");
1740 bindings[self.cm_id + "_open"] = function() {
1744 var pop = new openerp.web.form.FormOpenPopup(self.view);
1746 self.field.relation,
1748 self.build_context(),
1750 title: _t("Open: ") + (self.string || self.name)
1753 pop.on_write_completed.add_last(function() {
1754 self.set_value(self.value[0]);
1757 _.each(_.range(self.related_entries.length), function(i) {
1758 bindings[self.cm_id + "_related_" + i] = function() {
1759 self.open_related(self.related_entries[i]);
1762 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1763 bindings: bindings, itemStyle: {"color": ""},
1764 onContextMenu: function() {
1766 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1768 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1770 if (!self.readonly) {
1771 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1773 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1776 }, menuStyle: {width: "200px"}
1778 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1781 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1782 this.$menu_btn.bind('contextmenu', ctx_callback);
1783 this.$menu_btn.click(ctx_callback);
1785 // some behavior for input
1786 this.$input.keyup(function() {
1787 if (self.$input.val() === "") {
1788 self._change_int_value(null);
1789 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1790 self._change_int_value(undefined);
1793 this.$drop_down.click(function() {
1796 if (self.$input.autocomplete("widget").is(":visible")) {
1797 self.$input.autocomplete("close");
1800 self.$input.autocomplete("search", "");
1802 self.$input.autocomplete("search");
1804 self.$input.focus();
1807 var anyoneLoosesFocus = function() {
1808 if (!self.$input.is(":focus") &&
1809 !self.$input.autocomplete("widget").is(":visible") &&
1811 if (self.value === undefined && self.last_search.length > 0) {
1812 self._change_int_ext_value(self.last_search[0]);
1814 self._change_int_ext_value(null);
1818 this.$input.focusout(anyoneLoosesFocus);
1820 var isSelecting = false;
1822 this.$input.autocomplete({
1823 source: function(req, resp) { self.get_search_result(req, resp); },
1824 select: function(event, ui) {
1828 self._change_int_value([item.id, item.name]);
1829 } else if (item.action) {
1830 self._change_int_value(undefined);
1835 focus: function(e, ui) {
1839 close: anyoneLoosesFocus,
1843 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1844 this.$input.keyup(function(e) {
1845 if (e.which === 13) {
1847 e.stopPropagation();
1849 isSelecting = false;
1852 // autocomplete component content handling
1853 get_search_result: function(request, response) {
1854 var search_val = request.term;
1857 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1859 dataset.name_search(search_val, self.build_domain(), 'ilike',
1860 this.limit + 1, function(data) {
1861 self.last_search = data;
1862 // possible selections for the m2o
1863 var values = _.map(data, function(x) {
1864 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1867 // search more... if more results that max
1868 if (values.length > self.limit) {
1869 values = values.slice(0, self.limit);
1870 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
1871 dataset.name_search(search_val, self.build_domain(), 'ilike'
1872 , false, function(data) {
1873 self._change_int_value(null);
1874 self._search_create_popup("search", data);
1879 var raw_result = _(data.result).map(function(x) {return x[1];});
1880 if (search_val.length > 0 &&
1881 !_.include(raw_result, search_val) &&
1882 (!self.value || search_val !== self.value[1])) {
1883 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
1884 $('<span />').text(search_val).html()), action: function() {
1885 self._quick_create(search_val);
1889 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
1890 self._change_int_value(null);
1891 self._search_create_popup("form", undefined, {"default_name": search_val});
1897 _quick_create: function(name) {
1899 var slow_create = function() {
1900 self._change_int_value(null);
1901 self._search_create_popup("form", undefined, {"default_name": name});
1903 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
1904 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1905 dataset.name_create(name, function(data) {
1906 self._change_int_ext_value(data);
1907 }).fail(function(error, event) {
1908 event.preventDefault();
1914 // all search/create popup handling
1915 _search_create_popup: function(view, ids, context) {
1917 var pop = new openerp.web.form.SelectCreatePopup(this);
1919 self.field.relation,
1921 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
1922 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1924 disable_multiple_selection: true
1926 self.build_domain(),
1927 new openerp.web.CompoundContext(self.build_context(), context || {})
1929 pop.on_select_elements.add(function(element_ids) {
1930 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1931 dataset.name_get([element_ids[0]], function(data) {
1932 self._change_int_ext_value(data[0]);
1936 _change_int_ext_value: function(value) {
1937 this._change_int_value(value);
1938 this.$input.val(this.value ? this.value[1] : "");
1940 _change_int_value: function(value) {
1942 var back_orig_value = this.original_value;
1943 if (this.value === null || this.value) {
1944 this.original_value = this.value;
1946 if (back_orig_value === undefined) { // first use after a set_value()
1949 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1950 !== (this.value ? this.value[0] : null))) {
1951 this.on_ui_change();
1954 set_value: function(value) {
1955 value = value || null;
1956 this.invalid = false;
1958 this.tmp_value = value;
1960 self.on_value_changed();
1961 var real_set_value = function(rval) {
1962 self.tmp_value = undefined;
1964 self.original_value = undefined;
1965 self._change_int_ext_value(rval);
1967 if (value && !(value instanceof Array)) {
1968 // name_get in a m2o does not use the context of the field
1969 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
1970 dataset.name_get([value], function(data) {
1971 real_set_value(data[0]);
1972 }).fail(function() {self.tmp_value = undefined;});
1974 $.async_when().then(function() {real_set_value(value);});
1977 get_value: function() {
1978 if (this.tmp_value !== undefined) {
1979 if (this.tmp_value instanceof Array) {
1980 return this.tmp_value[0];
1982 return this.tmp_value ? this.tmp_value : false;
1984 if (this.value === undefined)
1985 return this.original_value ? this.original_value[0] : false;
1986 return this.value ? this.value[0] : false;
1988 validate: function() {
1989 this.invalid = false;
1990 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1992 this.invalid = this.required;
1995 open_related: function(related) {
1999 var additional_context = {
2000 active_id: self.value[0],
2001 active_ids: [self.value[0]],
2002 active_model: self.field.relation
2004 self.rpc("/web/action/load", {
2005 action_id: related[2].id,
2006 context: additional_context
2007 }, function(result) {
2008 result.result.context = _.extend(result.result.context || {}, additional_context);
2009 self.do_action(result.result);
2012 focus: function () {
2013 this.$input.focus();
2015 update_dom: function() {
2016 this._super.apply(this, arguments);
2017 this.$input.prop('disabled', this.readonly);
2022 # Values: (0, 0, { fields }) create
2023 # (1, ID, { fields }) update
2024 # (2, ID) remove (delete)
2025 # (3, ID) unlink one (target id or target of relation)
2027 # (5) unlink all (only valid for one2many)
2032 'create': function (values) {
2033 return [commands.CREATE, false, values];
2035 // (1, id, {values})
2037 'update': function (id, values) {
2038 return [commands.UPDATE, id, values];
2042 'delete': function (id) {
2043 return [commands.DELETE, id, false];
2045 // (3, id[, _]) removes relation, but not linked record itself
2047 'forget': function (id) {
2048 return [commands.FORGET, id, false];
2052 'link_to': function (id) {
2053 return [commands.LINK_TO, id, false];
2057 'delete_all': function () {
2058 return [5, false, false];
2060 // (6, _, ids) replaces all linked records with provided ids
2062 'replace_with': function (ids) {
2063 return [6, false, ids];
2066 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2067 template: 'FieldOne2Many',
2068 multi_selection: false,
2069 init: function(view, node) {
2070 this._super(view, node);
2071 this.is_loaded = $.Deferred();
2072 this.initial_is_loaded = this.is_loaded;
2073 this.is_setted = $.Deferred();
2074 this.form_last_update = $.Deferred();
2075 this.init_form_last_update = this.form_last_update;
2076 this.disable_utility_classes = true;
2079 this._super.apply(this, arguments);
2083 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2084 this.dataset.o2m = this;
2085 this.dataset.parent_view = this.view;
2086 this.dataset.child_name = this.name;
2087 //this.dataset.child_name =
2088 this.dataset.on_change.add_last(function() {
2089 self.trigger_on_change();
2092 this.is_setted.then(function() {
2096 trigger_on_change: function() {
2097 var tmp = this.doing_on_change;
2098 this.doing_on_change = true;
2099 this.on_ui_change();
2100 this.doing_on_change = tmp;
2102 is_readonly: function() {
2103 return this.readonly || this.force_readonly;
2105 load_views: function() {
2108 var modes = this.node.attrs.mode;
2109 modes = !!modes ? modes.split(",") : ["tree"];
2111 _.each(modes, function(mode) {
2114 view_type: mode == "tree" ? "list" : mode,
2115 options: { sidebar : false }
2117 if (self.field.views && self.field.views[mode]) {
2118 view.embedded_view = self.field.views[mode];
2120 if(view.view_type === "list") {
2121 view.options.selectable = self.multi_selection;
2122 if (self.is_readonly()) {
2123 view.options.addable = null;
2124 view.options.deletable = null;
2125 view.options.isClarkGable = false;
2127 } else if (view.view_type === "form") {
2128 if (self.is_readonly()) {
2129 view.view_type = 'page';
2131 view.options.not_interactible_on_create = true;
2137 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2138 this.viewmanager.template = 'One2Many.viewmanager';
2139 this.viewmanager.registry = openerp.web.views.clone({
2140 list: 'openerp.web.form.One2ManyListView',
2141 form: 'openerp.web.form.One2ManyFormView',
2142 page: 'openerp.web.PageView'
2144 var once = $.Deferred().then(function() {
2145 self.init_form_last_update.resolve();
2147 var def = $.Deferred().then(function() {
2148 self.initial_is_loaded.resolve();
2150 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2151 if (view_type == "list") {
2152 controller.o2m = self;
2153 if (self.is_readonly())
2154 controller.set_editable(false);
2155 } else if (view_type == "form" || view_type == 'page') {
2156 if (view_type == 'page' || self.is_readonly()) {
2157 $(".oe_form_buttons", controller.$element).children().remove();
2159 controller.on_record_loaded.add_last(function() {
2162 controller.on_pager_action.add_first(function() {
2163 self.save_any_view();
2165 } else if (view_type == "graph") {
2166 self.reload_current_view()
2170 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2171 $.when(self.save_any_view()).then(function() {
2172 if(n_mode === "list")
2173 $.async_when().then(function() {self.reload_current_view();});
2176 this.is_setted.then(function() {
2177 $.async_when().then(function () {
2178 self.viewmanager.appendTo(self.$element);
2183 reload_current_view: function() {
2185 return self.is_loaded = self.is_loaded.pipe(function() {
2186 var active_view = self.viewmanager.active_view;
2187 var view = self.viewmanager.views[active_view].controller;
2188 if(active_view === "list") {
2189 return view.reload_content();
2190 } else if (active_view === "form" || active_view === 'page') {
2191 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2192 self.dataset.index = 0;
2194 var act = function() {
2195 return view.do_show();
2197 self.form_last_update = self.form_last_update.pipe(act, act);
2198 return self.form_last_update;
2199 } else if (active_view === "graph") {
2200 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2204 set_value: function(value) {
2205 value = value || [];
2207 this.dataset.reset_ids([]);
2208 if(value.length >= 1 && value[0] instanceof Array) {
2210 _.each(value, function(command) {
2211 var obj = {values: command[2]};
2212 switch (command[0]) {
2213 case commands.CREATE:
2214 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2216 self.dataset.to_create.push(obj);
2217 self.dataset.cache.push(_.clone(obj));
2220 case commands.UPDATE:
2221 obj['id'] = command[1];
2222 self.dataset.to_write.push(obj);
2223 self.dataset.cache.push(_.clone(obj));
2226 case commands.DELETE:
2227 self.dataset.to_delete.push({id: command[1]});
2229 case commands.LINK_TO:
2230 ids.push(command[1]);
2232 case commands.DELETE_ALL:
2233 self.dataset.delete_all = true;
2238 this.dataset.set_ids(ids);
2239 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2241 this.dataset.delete_all = true;
2242 _.each(value, function(command) {
2243 var obj = {values: command};
2244 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2246 self.dataset.to_create.push(obj);
2247 self.dataset.cache.push(_.clone(obj));
2251 this.dataset.set_ids(ids);
2254 this.dataset.reset_ids(value);
2256 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2257 this.dataset.index = 0;
2259 self.is_setted.resolve();
2260 return self.reload_current_view();
2262 get_value: function() {
2266 this.save_any_view();
2267 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2268 val = val.concat(_.map(this.dataset.ids, function(id) {
2269 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2271 return commands.create(alter_order.values);
2273 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2275 return commands.update(alter_order.id, alter_order.values);
2277 return commands.link_to(id);
2279 return val.concat(_.map(
2280 this.dataset.to_delete, function(x) {
2281 return commands['delete'](x.id);}));
2283 save_any_view: function() {
2284 if (this.doing_on_change)
2286 return this.session.synchronized_mode(_.bind(function() {
2287 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2288 this.viewmanager.views[this.viewmanager.active_view] &&
2289 this.viewmanager.views[this.viewmanager.active_view].controller) {
2290 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2291 if (this.viewmanager.active_view === "form") {
2292 if (!view.is_initialized.isResolved()) {
2295 var res = $.when(view.do_save());
2296 if (!res.isResolved() && !res.isRejected()) {
2297 console.warn("Asynchronous get_value() is not supported in form view.");
2300 } else if (this.viewmanager.active_view === "list") {
2301 var res = $.when(view.ensure_saved());
2302 if (!res.isResolved() && !res.isRejected()) {
2303 console.warn("Asynchronous get_value() is not supported in list view.");
2311 is_valid: function() {
2313 return this._super();
2315 validate: function() {
2316 this.invalid = false;
2317 if (!this.viewmanager.views[this.viewmanager.active_view])
2319 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2320 if (this.viewmanager.active_view === "form") {
2321 for (var f in view.fields) {
2323 if (!f.is_valid()) {
2324 this.invalid = true;
2330 is_dirty: function() {
2331 this.save_any_view();
2332 return this._super();
2334 update_dom: function() {
2335 this._super.apply(this, arguments);
2337 if (this.previous_readonly !== this.readonly) {
2338 this.previous_readonly = this.readonly;
2339 if (this.viewmanager) {
2340 this.is_loaded = this.is_loaded.pipe(function() {
2341 self.viewmanager.stop();
2342 return $.when(self.load_views()).then(function() {
2343 self.reload_current_view();
2351 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2352 get_context: function() {
2353 this.context = this.o2m.build_context([this.o2m.name]);
2354 return this.context;
2358 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2359 _template: 'One2Many.listview',
2360 do_add_record: function () {
2361 if (this.options.editable) {
2362 this._super.apply(this, arguments);
2365 var pop = new openerp.web.form.SelectCreatePopup(this);
2366 pop.on_default_get.add(self.dataset.on_default_get);
2368 self.o2m.field.relation,
2370 title: _t("Create: ") + self.name,
2371 initial_view: "form",
2372 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2373 create_function: function(data, callback, error_callback) {
2374 return self.o2m.dataset.create(data).then(function(r) {
2375 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2376 self.o2m.dataset.on_change();
2377 }).then(callback, error_callback);
2379 read_function: function() {
2380 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2382 parent_view: self.o2m.view,
2383 child_name: self.o2m.name,
2384 form_view_options: {'not_interactible_on_create':true}
2386 self.o2m.build_domain(),
2387 self.o2m.build_context()
2389 pop.on_select_elements.add_last(function() {
2390 self.o2m.reload_current_view();
2394 do_activate_record: function(index, id) {
2396 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2397 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2398 title: _t("Open: ") + self.name,
2400 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2401 parent_view: self.o2m.view,
2402 child_name: self.o2m.name,
2403 read_function: function() {
2404 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2406 form_view_options: {'not_interactible_on_create':true},
2407 readonly: self.o2m.is_readonly()
2409 pop.on_write.add(function(id, data) {
2410 self.o2m.dataset.write(id, data, {}, function(r) {
2411 self.o2m.reload_current_view();
2415 do_button_action: function (name, id, callback) {
2417 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2418 return this._super(name, id, _.bind(def.resolve, def));
2422 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2423 form_template: 'One2Many.formview',
2424 on_loaded: function(data) {
2426 this.$form_header.find('button.oe_form_button_create').click(this.on_button_new);
2430 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2431 template: 'FieldMany2Many',
2432 multi_selection: false,
2433 init: function(view, node) {
2434 this._super(view, node);
2435 this.list_id = _.uniqueId("many2many");
2436 this.is_loaded = $.Deferred();
2437 this.initial_is_loaded = this.is_loaded;
2438 this.is_setted = $.Deferred();
2441 this._super.apply(this, arguments);
2445 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2446 this.dataset.m2m = this;
2447 this.dataset.on_unlink.add_last(function(ids) {
2448 self.on_ui_change();
2451 this.is_setted.then(function() {
2455 set_value: function(value) {
2456 value = value || [];
2457 if (value.length >= 1 && value[0] instanceof Array) {
2458 value = value[0][2];
2461 this.dataset.set_ids(value);
2463 self.reload_content();
2464 this.is_setted.resolve();
2466 get_value: function() {
2467 return [commands.replace_with(this.dataset.ids)];
2469 validate: function() {
2470 this.invalid = false;
2472 is_readonly: function() {
2473 return this.readonly || this.force_readonly;
2475 load_view: function() {
2477 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2478 'addable': self.is_readonly() ? null : _t("Add"),
2479 'deletable': self.is_readonly() ? false : true,
2480 'selectable': self.multi_selection,
2481 'isClarkGable': self.is_readonly() ? false : true
2483 var embedded = (this.field.views || {}).tree;
2485 this.list_view.set_embedded_view(embedded);
2487 this.list_view.m2m_field = this;
2488 var loaded = $.Deferred();
2489 this.list_view.on_loaded.add_last(function() {
2490 self.initial_is_loaded.resolve();
2493 $.async_when().then(function () {
2494 self.list_view.appendTo($("#" + self.list_id));
2498 reload_content: function() {
2500 this.is_loaded = this.is_loaded.pipe(function() {
2501 return self.list_view.reload_content();
2504 update_dom: function() {
2505 this._super.apply(this, arguments);
2507 if (this.previous_readonly !== this.readonly) {
2508 this.previous_readonly = this.readonly;
2509 if (this.list_view) {
2510 this.is_loaded = this.is_loaded.pipe(function() {
2511 self.list_view.stop();
2512 return $.when(self.load_view()).then(function() {
2513 self.reload_content();
2521 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2522 get_context: function() {
2523 this.context = this.m2m.build_context();
2524 return this.context;
2530 * @extends openerp.web.ListView
2532 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2533 do_add_record: function () {
2534 var pop = new openerp.web.form.SelectCreatePopup(this);
2538 title: _t("Add: ") + this.name
2540 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2541 this.m2m_field.build_context()
2544 pop.on_select_elements.add(function(element_ids) {
2545 _.each(element_ids, function(element_id) {
2546 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2547 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2548 self.m2m_field.on_ui_change();
2549 self.reload_content();
2554 do_activate_record: function(index, id) {
2556 var pop = new openerp.web.form.FormOpenPopup(this);
2557 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2558 title: _t("Open: ") + this.name,
2559 readonly: this.widget_parent.is_readonly()
2561 pop.on_write_completed.add_last(function() {
2562 self.reload_content();
2569 * @extends openerp.web.OldWidget
2571 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2572 identifier_prefix: "selectcreatepopup",
2573 template: "SelectCreatePopup",
2577 * - initial_view: form or search (default search)
2578 * - disable_multiple_selection
2579 * - alternative_form_view
2580 * - create_function (defaults to a naive saving behavior)
2583 * - form_view_options
2584 * - list_view_options
2587 select_element: function(model, options, domain, context) {
2590 this.domain = domain || [];
2591 this.context = context || {};
2592 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2593 return self.create_row.apply(self, arguments);
2594 }, read_function: null});
2595 this.initial_ids = this.options.initial_ids;
2596 this.created_elements = [];
2597 this.render_element();
2598 openerp.web.form.dialog(this.$element, {
2602 title: options.title || ""
2609 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2611 this.dataset.create_function = function() {
2612 return self.options.create_function.apply(null, arguments).then(function(r) {
2613 self.created_elements.push(r.result);
2616 this.dataset.write_function = function() {
2617 return self.write_row.apply(self, arguments);
2619 this.dataset.read_function = this.options.read_function;
2620 this.dataset.parent_view = this.options.parent_view;
2621 this.dataset.child_name = this.options.child_name;
2622 this.dataset.on_default_get.add(this.on_default_get);
2623 if (this.options.initial_view == "search") {
2624 self.rpc('/web/session/eval_domain_and_context', {
2626 contexts: [this.context]
2627 }, function (results) {
2628 var search_defaults = {};
2629 _.each(results.context, function (value, key) {
2630 var match = /^search_default_(.*)$/.exec(key);
2632 search_defaults[match[1]] = value;
2635 self.setup_search_view(search_defaults);
2641 setup_search_view: function(search_defaults) {
2643 if (this.searchview) {
2644 this.searchview.stop();
2646 this.searchview = new openerp.web.SearchView(this,
2647 this.dataset, false, search_defaults);
2648 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2649 if (self.initial_ids) {
2650 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2651 contexts, groupbys);
2652 self.initial_ids = undefined;
2654 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2657 this.searchview.on_loaded.add_last(function () {
2658 self.view_list = new openerp.web.form.SelectCreateListView(self,
2659 self.dataset, false,
2660 _.extend({'deletable': false,
2661 'selectable': !self.options.disable_multiple_selection
2662 }, self.options.list_view_options || {}));
2663 self.view_list.popup = self;
2664 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2665 self.view_list.do_show();
2666 }).pipe(function() {
2667 self.searchview.do_search();
2669 self.view_list.on_loaded.add_last(function() {
2670 var $buttons = self.view_list.$element.find(".oe-actions");
2671 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2672 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2673 $cbutton.click(function() {
2676 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2677 if(self.options.disable_multiple_selection) {
2680 $sbutton.click(function() {
2681 self.on_select_elements(self.selected_ids);
2686 this.searchview.appendTo($("#" + this.element_id + "_search"));
2688 do_search: function(domains, contexts, groupbys) {
2690 this.rpc('/web/session/eval_domain_and_context', {
2691 domains: domains || [],
2692 contexts: contexts || [],
2693 group_by_seq: groupbys || []
2694 }, function (results) {
2695 self.view_list.do_search(results.domain, results.context, results.group_by);
2698 create_row: function() {
2700 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2701 wdataset.parent_view = this.options.parent_view;
2702 wdataset.child_name = this.options.child_name;
2703 return wdataset.create.apply(wdataset, arguments);
2705 write_row: function() {
2707 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2708 wdataset.parent_view = this.options.parent_view;
2709 wdataset.child_name = this.options.child_name;
2710 return wdataset.write.apply(wdataset, arguments);
2712 on_select_elements: function(element_ids) {
2714 on_click_element: function(ids) {
2715 this.selected_ids = ids || [];
2716 if(this.selected_ids.length > 0) {
2717 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2719 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2722 new_object: function() {
2724 if (this.searchview) {
2725 this.searchview.hide();
2727 if (this.view_list) {
2728 this.view_list.$element.hide();
2730 this.dataset.index = null;
2731 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2732 if (this.options.alternative_form_view) {
2733 this.view_form.set_embedded_view(this.options.alternative_form_view);
2735 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2736 this.view_form.on_loaded.add_last(function() {
2737 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2738 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2739 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2740 $nbutton.click(function() {
2741 $.when(self.view_form.do_save()).then(function() {
2742 self.view_form.reload_mutex.exec(function() {
2743 self.view_form.on_button_new();
2747 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2748 $nbutton.click(function() {
2749 $.when(self.view_form.do_save()).then(function() {
2750 self.view_form.reload_mutex.exec(function() {
2755 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2756 $cbutton.click(function() {
2760 this.view_form.do_show();
2762 check_exit: function() {
2763 if (this.created_elements.length > 0) {
2764 this.on_select_elements(this.created_elements);
2768 on_default_get: function(res) {}
2771 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2772 do_add_record: function () {
2773 this.popup.new_object();
2775 select_record: function(index) {
2776 this.popup.on_select_elements([this.dataset.ids[index]]);
2779 do_select: function(ids, records) {
2780 this._super(ids, records);
2781 this.popup.on_click_element(ids);
2787 * @extends openerp.web.OldWidget
2789 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2790 identifier_prefix: "formopenpopup",
2791 template: "FormOpenPopup",
2794 * - alternative_form_view
2795 * - auto_write (default true)
2799 * - form_view_options
2802 show_element: function(model, row_id, context, options) {
2804 this.row_id = row_id;
2805 this.context = context || {};
2806 this.options = _.defaults(options || {}, {"auto_write": true});
2807 this.render_element();
2808 this.$element.dialog({
2809 title: options.title || '',
2818 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2819 this.dataset.fop = this;
2820 this.dataset.ids = [this.row_id];
2821 this.dataset.index = 0;
2822 this.dataset.parent_view = this.options.parent_view;
2823 this.dataset.child_name = this.options.child_name;
2824 this.setup_form_view();
2826 on_write: function(id, data) {
2827 if (!this.options.auto_write)
2830 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2831 wdataset.parent_view = this.options.parent_view;
2832 wdataset.child_name = this.options.child_name;
2833 wdataset.write(id, data, {}, function(r) {
2834 self.on_write_completed();
2837 on_write_completed: function() {},
2838 setup_form_view: function() {
2840 var FormClass = this.options.readonly
2841 ? openerp.web.views.get_object('page')
2842 : openerp.web.views.get_object('form');
2843 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2844 if (this.options.alternative_form_view) {
2845 this.view_form.set_embedded_view(this.options.alternative_form_view);
2847 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2848 this.view_form.on_loaded.add_last(function() {
2849 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2850 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2851 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2852 $nbutton.click(function() {
2853 self.view_form.do_save().then(function() {
2857 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2858 $cbutton.click(function() {
2861 if (self.options.readonly) {
2863 $cbutton.text(_t("Close"));
2865 self.view_form.do_show();
2867 this.dataset.on_write.add(this.on_write);
2871 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2872 read_ids: function() {
2873 if (this.fop.options.read_function) {
2874 return this.fop.options.read_function.apply(null, arguments);
2876 return this._super.apply(this, arguments);
2881 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2882 template: 'FieldReference',
2883 init: function(view, node) {
2884 this._super(view, node);
2885 this.fields_view = {
2888 selection: view.fields_view.fields[this.name].selection
2895 this.get_fields_values = view.get_fields_values;
2896 this.do_onchange = this.on_form_changed = this.on_nop;
2897 this.dataset = this.view.dataset;
2898 this.widgets_counter = 0;
2899 this.view_id = 'reference_' + _.uniqueId();
2902 this.fields_order = [];
2903 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2907 this.reference_ready = true;
2908 this.selection.on_value_changed.add_last(this.on_selection_changed);
2909 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2914 on_nop: function() {
2916 on_selection_changed: function() {
2917 if (this.reference_ready) {
2918 var sel = this.selection.get_value();
2919 this.m2o.field.relation = sel;
2920 this.m2o.set_value(null);
2921 this.m2o.$element.toggle(sel !== false);
2926 this.selection.start();
2929 is_valid: function() {
2930 return this.required === false || typeof(this.get_value()) === 'string';
2932 is_dirty: function() {
2933 return this.selection.is_dirty() || this.m2o.is_dirty();
2935 set_value: function(value) {
2937 this.reference_ready = false;
2938 var vals = [], sel_val, m2o_val;
2939 if (typeof(value) === 'string') {
2940 vals = value.split(',');
2942 sel_val = vals[0] || false;
2943 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2944 this.selection.set_value(sel_val);
2945 this.m2o.field.relation = sel_val;
2946 this.m2o.set_value(m2o_val);
2947 this.m2o.$element.toggle(sel_val !== false);
2948 this.reference_ready = true;
2950 get_value: function() {
2951 var model = this.selection.get_value(),
2952 id = this.m2o.get_value();
2953 if (typeof(model) === 'string' && typeof(id) === 'number') {
2954 return model + ',' + id;
2961 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2962 init: function(view, node) {
2963 this._super(view, node);
2964 this.iframe = this.element_id + '_iframe';
2965 this.binary_value = false;
2968 this._super.apply(this, arguments);
2969 this.$element.find('input.oe-binary-file').change(this.on_file_change);
2970 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2971 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2973 human_filesize : function(size) {
2974 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2976 while (size >= 1024) {
2980 return size.toFixed(2) + ' ' + units[i];
2982 on_file_change: function(e) {
2983 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2984 // http://www.html5rocks.com/tutorials/file/dndfiles/
2985 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2986 window[this.iframe] = this.on_file_uploaded;
2987 if ($(e.target).val() != '') {
2988 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2989 this.$element.find('form.oe-binary-form').submit();
2990 this.$element.find('.oe-binary-progress').show();
2991 this.$element.find('.oe-binary').hide();
2994 on_file_uploaded: function(size, name, content_type, file_base64) {
2995 delete(window[this.iframe]);
2996 if (size === false) {
2997 this.do_warn("File Upload", "There was a problem while uploading your file");
2998 // TODO: use openerp web crashmanager
2999 console.warn("Error while uploading file : ", name);
3001 this.on_file_uploaded_and_valid.apply(this, arguments);
3002 this.on_ui_change();
3004 this.$element.find('.oe-binary-progress').hide();
3005 this.$element.find('.oe-binary').show();
3007 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3009 on_save_as: function() {
3010 var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
3011 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
3012 '&filename_field=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
3015 on_clear: function() {
3016 if (this.value !== false) {
3018 this.binary_value = false;
3019 this.on_ui_change();
3025 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3026 template: 'FieldBinaryFile',
3027 update_dom: function() {
3028 this._super.apply(this, arguments);
3029 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3030 this.$element.find('input[type=text]').prop('disabled', this.readonly);
3032 set_value: function(value) {
3033 this._super.apply(this, arguments);
3035 if (this.node.attrs.filename) {
3036 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3038 show_value = (value != null && value !== false) ? value : '';
3040 this.$element.find('input').eq(0).val(show_value);
3042 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3043 this.value = file_base64;
3044 this.binary_value = true;
3045 var show_value = name + " (" + this.human_filesize(size) + ")";
3046 this.$element.find('input').eq(0).val(show_value);
3047 this.set_filename(name);
3049 set_filename: function(value) {
3050 var filename = this.node.attrs.filename;
3051 if (this.view.fields[filename]) {
3052 this.view.fields[filename].set_value(value);
3053 this.view.fields[filename].on_ui_change();
3056 on_clear: function() {
3057 this._super.apply(this, arguments);
3058 this.$element.find('input').eq(0).val('');
3059 this.set_filename('');
3063 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3064 template: 'FieldBinaryImage',
3066 this._super.apply(this, arguments);
3067 this.$image = this.$element.find('img.oe-binary-image');
3069 update_dom: function() {
3070 this._super.apply(this, arguments);
3071 this.$element.find('.oe-binary').toggle(!this.readonly);
3073 set_value: function(value) {
3074 this._super.apply(this, arguments);
3075 this.set_image_maxwidth();
3076 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3077 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3078 this.$image.attr('src', url);
3080 set_image_maxwidth: function() {
3081 this.$image.css('max-width', this.$element.width());
3083 on_file_change: function() {
3084 this.set_image_maxwidth();
3085 this._super.apply(this, arguments);
3087 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3088 this.value = file_base64;
3089 this.binary_value = true;
3090 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3092 on_clear: function() {
3093 this._super.apply(this, arguments);
3094 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3098 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3099 template: "EmptyComponent",
3102 this.selected_value = null;
3106 set_value: function(value) {
3108 this.selected_value = value;
3112 render_list: function() {
3114 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3115 function(x) { return _.str.trim(x); });
3116 shown = _.select(shown, function(x) { return x.length > 0; });
3118 if (shown.length == 0) {
3119 this.to_show = this.field.selection;
3121 this.to_show = _.select(this.field.selection, function(x) {
3122 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3126 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3127 this.$element.html(content);
3129 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3130 var color = colors[this.selected_value];
3132 var elem = this.$element.find("li.oe-arrow-list-selected span");
3133 elem.css("border-color", color);
3134 if (this.check_white(color))
3135 elem.css("color", "white");
3136 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3137 elem.css("border-left-color", "rgba(0,0,0,0)");
3138 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3139 elem.css("border-color", "rgba(0,0,0,0)");
3140 elem.css("border-left-color", color);
3143 check_white: function(color) {
3144 var div = $("<div></div>");
3145 div.css("display", "none");
3146 div.css("color", color);
3147 div.appendTo($("body"));
3148 var ncolor = div.css("color");
3150 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3154 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3155 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3163 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3164 render: function () {
3165 var $root = $('<div class="oe_form_html_view">');
3166 this.render_children(this, $root);
3167 return $root.html();
3169 render_children: function (object, $into) {
3171 fields = this.view.fields_view.fields;
3172 _(object.children).each(function (child) {
3173 if (typeof child === 'string') {
3175 } else if (child.tag === 'field') {
3177 new (self.view.registry.get_object('frame'))(
3178 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3181 var $child = $(document.createElement(child.tag))
3184 self.render_children(child, $child);
3192 * Registry of form widgets, called by :js:`openerp.web.FormView`
3194 openerp.web.form.widgets = new openerp.web.Registry({
3195 'frame' : 'openerp.web.form.WidgetFrame',
3196 'group' : 'openerp.web.form.WidgetGroup',
3197 'notebook' : 'openerp.web.form.WidgetNotebook',
3198 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3199 'separator' : 'openerp.web.form.WidgetSeparator',
3200 'label' : 'openerp.web.form.WidgetLabel',
3201 'button' : 'openerp.web.form.WidgetButton',
3202 'char' : 'openerp.web.form.FieldChar',
3203 'email' : 'openerp.web.form.FieldEmail',
3204 'url' : 'openerp.web.form.FieldUrl',
3205 'text' : 'openerp.web.form.FieldText',
3206 'text_wiki' : 'openerp.web.form.FieldText',
3207 'date' : 'openerp.web.form.FieldDate',
3208 'datetime' : 'openerp.web.form.FieldDatetime',
3209 'selection' : 'openerp.web.form.FieldSelection',
3210 'many2one' : 'openerp.web.form.FieldMany2One',
3211 'many2many' : 'openerp.web.form.FieldMany2Many',
3212 'one2many' : 'openerp.web.form.FieldOne2Many',
3213 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3214 'reference' : 'openerp.web.form.FieldReference',
3215 'boolean' : 'openerp.web.form.FieldBoolean',
3216 'float' : 'openerp.web.form.FieldFloat',
3217 'integer': 'openerp.web.form.FieldFloat',
3218 'float_time': 'openerp.web.form.FieldFloat',
3219 'progressbar': 'openerp.web.form.FieldProgressBar',
3220 'image': 'openerp.web.form.FieldBinaryImage',
3221 'binary': 'openerp.web.form.FieldBinaryFile',
3222 'statusbar': 'openerp.web.form.FieldStatus',
3223 'html': 'openerp.web.form.WidgetHtml'
3229 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: