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 display_name: _lt('Form'),
18 * @constructs openerp.web.FormView
19 * @extends openerp.web.View
21 * @param {openerp.web.Session} session the current openerp session
22 * @param {openerp.web.DataSet} dataset the dataset this view will work with
23 * @param {String} view_id the identifier of the OpenERP view object
24 * @param {Object} options
25 * - sidebar : [true|false]
26 * - resize_textareas : [true|false|max_height]
28 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
30 init: function(parent, dataset, view_id, options) {
32 this.set_default_options(options);
33 this.dataset = dataset;
34 this.model = dataset.model;
35 this.view_id = view_id || false;
36 this.fields_view = {};
38 this.widgets_counter = 0;
40 this.fields_order = [];
42 this.default_focus_field = null;
43 this.default_focus_button = null;
44 this.registry = openerp.web.form.widgets;
45 this.has_been_loaded = $.Deferred();
46 this.$form_header = null;
47 this.translatable_fields = [];
48 _.defaults(this.options, {
49 "not_interactible_on_create": false
51 this.is_initialized = $.Deferred();
52 this.mutating_mutex = new $.Mutex();
53 this.on_change_mutex = new $.Mutex();
54 this.reload_mutex = new $.Mutex();
58 return this.init_view();
60 init_view: function() {
61 if (this.embedded_view) {
62 var def = $.Deferred().then(this.on_loaded);
64 $.async_when().then(function() {def.resolve(self.embedded_view);});
67 var context = new openerp.web.CompoundContext(this.dataset.get_context());
68 return this.rpc("/web/view/load", {
70 "view_id": this.view_id,
72 toolbar: this.options.sidebar,
79 this.sidebar.attachments.stop();
82 _.each(this.widgets, function(w) {
87 reposition: function ($e) {
91 on_loaded: function(data) {
94 this.fields_order = [];
95 this.fields_view = data;
96 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
98 this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
100 this.$element.html(this.rendered);
101 _.each(this.widgets, function(w) {
104 this.$form_header = this.$element.find('.oe_form_header:first');
105 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
106 var action = $(this).data('pager-action');
107 self.on_pager_action(action);
110 this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
111 this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
113 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
114 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
115 this.sidebar.start();
116 this.sidebar.do_unfold();
117 this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
118 this.sidebar.add_toolbar(this.fields_view.toolbar);
119 this.set_common_sidebar_sections(this.sidebar);
121 this.sidebar.add_section(_t('Customize'), 'customize');
122 this.sidebar.add_items('customize', [{
123 label: _t('Set Default'),
125 callback: function (item) {
126 item.form.open_defaults_dialog();
130 this.has_been_loaded.resolve();
133 do_load_state: function(state, warm) {
134 if (state.id && this.datarecord.id != state.id) {
135 if (!this.dataset.get_id_index(state.id)) {
136 this.dataset.ids.push(state.id);
138 this.dataset.select_id(state.id);
145 do_show: function () {
147 this.$element.show().css('visibility', 'hidden');
148 return this.has_been_loaded.pipe(function() {
150 if (self.dataset.index === null) {
151 // null index means we should start a new record
152 result = self.on_button_new();
154 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
155 context : { 'bin_size' : true }
156 }).pipe(self.on_record_loaded);
158 result.pipe(function() {
159 self.$element.css('visibility', 'visible');
162 self.sidebar.$element.show();
167 do_hide: function () {
170 this.sidebar.$element.hide();
173 on_record_loaded: function(record) {
174 var self = this, set_values = [];
176 this.do_warn("Form", "The record could not be found in the database.", true);
177 return $.Deferred().reject();
179 this.datarecord = record;
181 _(this.fields).each(function (field, f) {
183 var result = field.set_value(self.datarecord[f] || false);
184 set_values.push(result);
185 $.when(result).then(function() {
189 return $.when.apply(null, set_values).pipe(function() {
191 // New record: Second pass in order to trigger the onchanges
192 // respecting the fields order defined in the view
193 _.each(self.fields_order, function(field_name) {
194 if (record[field_name] !== undefined) {
195 var field = self.fields[field_name];
197 self.do_onchange(field);
201 self.on_form_changed();
202 self.is_initialized.resolve();
203 self.do_update_pager(record.id == null);
205 self.sidebar.attachments.do_update();
207 if (self.default_focus_field && !self.embedded_view) {
208 self.default_focus_field.focus();
211 self.do_push_state({id:record.id});
213 self.$element.removeClass('oe_form_dirty');
216 on_form_changed: function(changed_by_user) {
217 if (changed_by_user) {
218 this.$element.addClass('oe_form_dirty');
220 for (var w in this.widgets) {
222 w.process_modifiers();
229 on_pager_action: function(action) {
230 if (this.can_be_discarded()) {
233 this.dataset.index = 0;
236 this.dataset.previous();
242 this.dataset.index = this.dataset.ids.length - 1;
248 do_update_pager: function(hide_index) {
249 var $pager = this.$form_header.find('div.oe_form_pager');
250 var index = hide_index ? '-' : this.dataset.index + 1;
251 $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
252 $pager.find('span.oe_pager_index').html(index);
253 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
255 parse_on_change: function (on_change, widget) {
257 var onchange = _.str.trim(on_change);
258 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
263 var method = call[1];
264 if (!_.str.trim(call[2])) {
265 return {method: method, args: [], context_index: null}
268 var argument_replacement = {
269 'False': function () {return false;},
270 'True': function () {return true;},
271 'None': function () {return null;},
272 'context': function (i) {
274 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
278 var parent_fields = null, context_index = null;
279 var args = _.map(call[2].split(','), function (a, i) {
280 var field = _.str.trim(a);
282 // literal constant or context
283 if (field in argument_replacement) {
284 return argument_replacement[field](i);
287 if (/^-?\d+(\.\d+)?$/.test(field)) {
288 return Number(field);
291 if (self.fields[field]) {
292 var value = self.fields[field].get_on_change_value();
293 return value == null ? false : value;
296 var splitted = field.split('.');
297 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
298 if (parent_fields === null) {
299 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
301 var p_val = parent_fields[_.str.trim(splitted[1])];
302 if (p_val !== undefined) {
303 return p_val == null ? false : p_val;
307 var first_char = field[0], last_char = field[field.length-1];
308 if ((first_char === '"' && last_char === '"')
309 || (first_char === "'" && last_char === "'")) {
310 return field.slice(1, -1);
313 throw new Error("Could not get field with name '" + field +
314 "' for onchange '" + onchange + "'");
320 context_index: context_index
323 do_onchange: function(widget, processed) {
325 return this.on_change_mutex.exec(function() {
327 var response = {}, can_process_onchange = $.Deferred();
328 processed = processed || [];
329 processed.push(widget.name);
330 var on_change = widget.node.attrs.on_change;
332 var change_spec = self.parse_on_change(on_change, widget);
335 url: '/web/dataset/onchange',
338 can_process_onchange = self.rpc(ajax, {
339 model: self.dataset.model,
340 method: change_spec.method,
341 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
342 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
343 }).then(function(r) {
344 _.extend(response, r);
347 console.warn("Wrong on_change format", on_change);
350 // fail if onchange failed
351 if (can_process_onchange.isRejected()) {
352 return can_process_onchange;
355 if (widget.field['change_default']) {
356 var fieldname = widget.name, value;
357 if (response.value && (fieldname in response.value)) {
358 // Use value from onchange if onchange executed
359 value = response.value[fieldname];
361 // otherwise get form value for field
362 value = self.fields[fieldname].get_on_change_value();
364 var condition = fieldname + '=' + value;
367 can_process_onchange = self.rpc({
368 url: '/web/dataset/call',
372 method: 'get_defaults',
373 args: [self.model, condition]
374 }).then(function (results) {
375 if (!results.length) { return; }
376 if (!response.value) {
379 for(var i=0; i<results.length; ++i) {
380 // [whatever, key, value]
381 var triplet = results[i];
382 response.value[triplet[1]] = triplet[2];
387 if (can_process_onchange.isRejected()) {
388 return can_process_onchange;
391 return self.on_processed_onchange(response, processed);
394 return $.Deferred().reject();
398 on_processed_onchange: function(response, processed) {
400 var result = response;
402 for (var f in result.value) {
403 if (!result.value.hasOwnProperty(f)) { continue; }
404 var field = this.fields[f];
405 // If field is not defined in the view, just ignore it
407 var value = result.value[f];
408 if (field.get_value() != value) {
409 field.set_value(value);
411 if (!_.contains(processed, field.name)) {
412 this.do_onchange(field, processed);
417 this.on_form_changed();
419 if (!_.isEmpty(result.warning)) {
420 $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
423 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
428 function edit_domain(node) {
429 var new_domain = result.domain[node.attrs.name];
431 node.attrs.domain = new_domain;
433 _(node.children).each(edit_domain);
435 edit_domain(this.fields_view.arch);
437 return $.Deferred().resolve();
440 return $.Deferred().reject();
443 on_button_save: function() {
445 return this.do_save().then(function(result) {
446 self.do_prev_view({'created': result.created, 'default': 'page'});
449 on_button_cancel: function() {
450 return this.do_prev_view({'default': 'page'});
452 on_button_new: function() {
454 var def = $.Deferred();
455 $.when(this.has_been_loaded).then(function() {
456 if (self.can_be_discarded()) {
457 var keys = _.keys(self.fields_view.fields);
459 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
463 self.on_record_loaded({}).then(function() {
469 return def.promise();
471 can_be_discarded: function() {
472 return true; // FIXME: Disabled until the page view and button refactoring is done
473 return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
476 * Triggers saving the form's record. Chooses between creating a new
477 * record or saving an existing one depending on whether the record
478 * already has an id property.
480 * @param {Function} success callback on save success
481 * @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)
483 do_save: function(success, prepend_on_create) {
485 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
487 var form_invalid = false,
489 first_invalid_field = null;
490 for (var f in self.fields) {
495 if (!first_invalid_field) {
496 first_invalid_field = f;
498 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
499 // Special case 'id' field, do not save this field
500 // on 'create' : save all non readonly fields
501 // on 'edit' : save non readonly modified fields
502 values[f.name] = f.get_value();
506 first_invalid_field.focus();
508 return $.Deferred().reject();
511 if (!self.datarecord.id) {
512 //console.log("FormView(", self, ") : About to create", values);
513 save_deferral = self.dataset.create(values).pipe(function(r) {
514 return self.on_created(r, undefined, prepend_on_create);
516 } else if (_.isEmpty(values)) {
517 //console.log("FormView(", self, ") : Nothing to save");
518 save_deferral = $.Deferred().resolve({}).promise();
520 //console.log("FormView(", self, ") : About to save", values);
521 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
522 return self.on_saved(r);
525 return save_deferral.then(success);
529 return $.Deferred().reject();
533 on_invalid: function() {
535 _.each(this.fields, function(f) {
537 msg += "<li>" + f.string + "</li>";
541 this.do_warn("The following fields are invalid :", msg);
543 on_saved: function(r, success) {
545 // should not happen in the server, but may happen for internal purpose
546 return $.Deferred().reject();
548 return $.when(this.reload()).pipe(function () {
549 return $.when(r).then(success); }, null);
553 * Updates the form' dataset to contain the new record:
555 * * Adds the newly created record to the current dataset (at the end by
557 * * Selects that record (sets the dataset's index to point to the new
559 * * Updates the pager and sidebar displays
562 * @param {Function} success callback to execute after having updated the dataset
563 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
565 on_created: function(r, success, prepend_on_create) {
567 // should not happen in the server, but may happen for internal purpose
568 return $.Deferred().reject();
570 this.datarecord.id = r.result;
571 if (!prepend_on_create) {
572 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
573 this.dataset.index = this.dataset.ids.length - 1;
575 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
576 this.dataset.index = 0;
578 this.do_update_pager();
580 this.sidebar.attachments.do_update();
582 //openerp.log("The record has been created with id #" + this.datarecord.id);
584 return $.when(_.extend(r, {created: true})).then(success);
587 on_action: function (action) {
588 console.debug('Executing action', action);
592 return this.reload_mutex.exec(function() {
593 if (self.dataset.index == null || self.dataset.index < 0) {
594 return $.when(self.on_button_new());
596 return self.dataset.read_index(_.keys(self.fields_view.fields), {
597 context : { 'bin_size' : true }
598 }).pipe(self.on_record_loaded);
602 get_fields_values: function(blacklist) {
603 blacklist = blacklist || [];
605 var ids = this.get_selected_ids();
606 values["id"] = ids.length > 0 ? ids[0] : false;
607 _.each(this.fields, function(value, key) {
608 if (_.include(blacklist, key))
610 var val = value.get_value();
615 get_selected_ids: function() {
616 var id = this.dataset.ids[this.dataset.index];
617 return id ? [id] : [];
619 recursive_save: function() {
621 return $.when(this.do_save()).pipe(function(res) {
622 if (self.dataset.parent_view)
623 return self.dataset.parent_view.recursive_save();
626 is_dirty: function() {
627 return _.any(this.fields, function (value) {
628 return value.is_dirty();
631 is_interactible_record: function() {
632 var id = this.datarecord.id;
634 if (this.options.not_interactible_on_create)
636 } else if (typeof(id) === "string") {
637 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
642 sidebar_context: function () {
643 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
645 open_defaults_dialog: function () {
647 var fields = _.chain(this.fields)
648 .map(function (field, name) {
649 var value = field.get_value();
650 // ignore fields which are empty, invisible, readonly, o2m
655 || field.field.type === 'one2many'
656 || field.field.type === 'many2many') {
660 switch(field.field.type) {
662 displayed = _(field.values).find(function (option) {
663 return option[0] === value;
667 displayed = field.value[1] || value;
675 string: field.string,
677 displayed: displayed,
678 // convert undefined to false
679 change_default: !!field.field.change_default
683 .sortBy(function (field) { return field.string; })
685 var conditions = _.chain(fields)
686 .filter(function (field) { return field.change_default; })
689 var d = new openerp.web.Dialog(this, {
690 title: _t("Set Default"),
693 conditions: conditions
696 {text: _t("Close"), click: function () { d.close(); }},
697 {text: _t("Save default"), click: function () {
698 var $defaults = d.$element.find('#formview_default_fields');
699 var field_to_set = $defaults.val();
701 $defaults.parent().addClass('invalid');
704 var condition = d.$element.find('#formview_default_conditions').val(),
705 all_users = d.$element.find('#formview_default_all').is(':checked');
706 new openerp.web.DataSet(self, 'ir.values').call(
710 self.fields[field_to_set].get_value(),
714 ]).then(function () { d.close(); });
718 d.template = 'FormView.set_default';
722 openerp.web.FormDialog = openerp.web.Dialog.extend({
723 init: function(parent, options, view_id, dataset) {
724 this._super(parent, options);
725 this.dataset = dataset;
726 this.view_id = view_id;
731 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
735 this.form.appendTo(this.$element);
736 this.form.on_created.add_last(this.on_form_dialog_saved);
737 this.form.on_saved.add_last(this.on_form_dialog_saved);
740 select_id: function(id) {
741 if (this.form.dataset.select_id(id)) {
742 return this.form.do_show();
744 this.do_warn("Could not find id in dataset");
745 return $.Deferred().reject();
748 on_form_dialog_saved: function(r) {
754 openerp.web.form = {};
756 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
757 init: function(parent, form_view) {
758 var $section = parent.add_section(_t('Attachments'), 'attachments');
759 this.$div = $('<div class="oe-sidebar-attachments"></div>');
760 $section.append(this.$div);
762 this._super(parent, $section.attr('id'));
763 this.view = form_view;
765 do_update: function() {
766 if (!this.view.datarecord.id) {
767 this.on_attachments_loaded([]);
769 (new openerp.web.DataSetSearch(
770 this, 'ir.attachment', this.view.dataset.get_context(),
772 ['res_model', '=', this.view.dataset.model],
773 ['res_id', '=', this.view.datarecord.id],
774 ['type', 'in', ['binary', 'url']]
775 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
778 on_attachments_loaded: function(attachments) {
779 this.attachments = attachments;
780 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
781 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
782 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
784 on_attachment_changed: function(e) {
785 window[this.element_id + '_iframe'] = this.do_update;
786 var $e = $(e.target);
787 if ($e.val() != '') {
788 this.$element.find('form.oe-binary-form').submit();
789 $e.parent().find('input[type=file]').prop('disabled', true);
790 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
793 on_attachment_delete: function(e) {
794 var self = this, $e = $(e.currentTarget);
795 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
796 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
797 this.rpc('/web/dataset/unlink', {
798 model: 'ir.attachment',
799 ids: [parseInt($e.attr('data-id'))]
801 $e.parent().remove();
802 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
808 openerp.web.form.compute_domain = function(expr, fields) {
810 for (var i = expr.length - 1; i >= 0; i--) {
812 if (ex.length == 1) {
813 var top = stack.pop();
816 stack.push(stack.pop() || top);
819 stack.push(stack.pop() && top);
825 throw new Error(_.str.sprintf(
826 _t("Unknown operator %s in domain %s"),
827 ex, JSON.stringify(expr)));
831 var field = fields[ex[0]];
833 throw new Error(_.str.sprintf(
834 _t("Unknown field %s in domain %s"),
835 ex[0], JSON.stringify(expr)));
837 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
841 switch (op.toLowerCase()) {
844 stack.push(field_value == val);
848 stack.push(field_value != val);
851 stack.push(field_value < val);
854 stack.push(field_value > val);
857 stack.push(field_value <= val);
860 stack.push(field_value >= val);
863 if (!_.isArray(val)) val = [val];
864 stack.push(_(val).contains(field_value));
867 if (!_.isArray(val)) val = [val];
868 stack.push(!_(val).contains(field_value));
872 _t("Unsupported operator %s in domain %s"),
873 op, JSON.stringify(expr));
876 return _.all(stack, _.identity);
879 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
882 * @constructs openerp.web.form.Widget
883 * @extends openerp.web.OldWidget
888 init: function(view, node) {
891 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
892 this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
893 this.type = this.type || node.tag;
894 this.element_name = this.element_name || this.type;
895 this.element_class = [
896 'formview', this.view.view_id, this.element_name,
897 this.view.widgets_counter++].join("_");
901 this.view.widgets[this.element_class] = this;
902 this.children = node.children;
903 this.colspan = parseInt(node.attrs.colspan || 1, 10);
904 this.decrease_max_width = 0;
906 this.string = this.string || node.attrs.string;
907 this.help = this.help || node.attrs.help;
908 this.invisible = this.modifiers['invisible'] === true;
909 this.classname = 'oe_form_' + this.type;
911 this.align = parseFloat(this.node.attrs.align);
912 if (isNaN(this.align) || this.align === 1) {
913 this.align = 'right';
914 } else if (this.align === 0) {
917 this.align = 'center';
921 this.width = this.node.attrs.width;
924 this.$element = this.view.$element.find(
925 '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
928 this._super.apply(this, arguments);
931 process_modifiers: function() {
932 var compute_domain = openerp.web.form.compute_domain;
933 for (var a in this.modifiers) {
934 this[a] = compute_domain(this.modifiers[a], this.view.fields);
937 update_dom: function() {
938 this.$element.toggle(!this.invisible);
941 var template = this.template;
942 return QWeb.render(template, { "widget": this });
944 do_attach_tooltip: function(widget, trigger, options) {
945 widget = widget || this;
946 trigger = trigger || this.$element;
952 var template = widget.template + '.tooltip';
953 if (!QWeb.has_template(template)) {
954 template = 'WidgetLabel.tooltip';
956 return QWeb.render(template, {
957 debug: openerp.connection.debug,
960 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
965 trigger.tipsy(options);
967 _build_view_fields_values: function(blacklist) {
968 var a_dataset = this.view.dataset;
969 var fields_values = this.view.get_fields_values(blacklist);
970 var active_id = a_dataset.ids[a_dataset.index];
971 _.extend(fields_values, {
972 active_id: active_id || false,
973 active_ids: active_id ? [active_id] : [],
974 active_model: a_dataset.model,
977 if (a_dataset.parent_view) {
978 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
980 return fields_values;
982 _build_eval_context: function(blacklist) {
983 var a_dataset = this.view.dataset;
984 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
987 * Builds a new context usable for operations related to fields by merging
988 * the fields'context with the action's context.
990 build_context: function(blacklist) {
991 // only use the model's context if there is not context on the node
992 var v_context = this.node.attrs.context;
994 v_context = (this.field || {}).context || {};
997 if (v_context.__ref || true) { //TODO: remove true
998 var fields_values = this._build_eval_context(blacklist);
999 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1003 build_domain: function() {
1004 var f_domain = this.field.domain || [];
1005 var n_domain = this.node.attrs.domain || null;
1006 // if there is a domain on the node, overrides the model's domain
1007 var final_domain = n_domain !== null ? n_domain : f_domain;
1008 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1009 var fields_values = this._build_eval_context();
1010 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1012 return final_domain;
1016 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1017 template: 'WidgetFrame',
1018 init: function(view, node) {
1019 this._super(view, node);
1020 this.columns = parseInt(node.attrs.col || 4, 10);
1025 for (var i = 0; i < node.children.length; i++) {
1026 var n = node.children[i];
1027 if (n.tag == "newline") {
1030 this.handle_node(n);
1033 this.set_row_cells_with(this.table[this.table.length - 1]);
1035 add_row: function(){
1036 if (this.table.length) {
1037 this.set_row_cells_with(this.table[this.table.length - 1]);
1040 this.table.push(row);
1045 set_row_cells_with: function(row) {
1048 row_length = row.length;
1049 for (var i = 0; i < row.length; i++) {
1050 if (row[i].always_invisible) {
1053 bypass += row[i].width === undefined ? 0 : 1;
1054 max_width -= row[i].decrease_max_width;
1057 var size_unit = Math.round(max_width / (this.columns - bypass)),
1059 for (var i = 0; i < row.length; i++) {
1061 if (w.always_invisible) {
1064 colspan_sum += w.colspan;
1065 if (w.width === undefined) {
1066 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1068 w.width = width + '%';
1072 handle_node: function(node) {
1074 if (node.tag == 'field') {
1075 type = this.view.fields_view.fields[node.attrs.name] || {};
1076 if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1077 // This way we can retain backward compatibility between addons and old clients
1078 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1079 node.attrs.nolabel = '1';
1082 var widget = new (this.view.registry.get_any(
1083 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1084 if (node.tag == 'field') {
1085 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1086 this.view.default_focus_field = widget;
1088 if (node.attrs.nolabel != '1') {
1089 var label = new (this.view.registry.get_object('label')) (this.view, node);
1090 label["for"] = widget;
1091 this.add_widget(label, widget.colspan + 1);
1094 this.add_widget(widget);
1096 add_widget: function(widget, colspan) {
1097 var current_row = this.table[this.table.length - 1];
1098 if (!widget.always_invisible) {
1099 colspan = colspan || widget.colspan;
1100 if (current_row.length && (this.x + colspan) > this.columns) {
1101 current_row = this.add_row();
1103 this.x += widget.colspan;
1105 current_row.push(widget);
1110 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1111 template: 'WidgetGroup'
1114 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1115 template: 'WidgetNotebook',
1116 init: function(view, node) {
1117 this._super(view, node);
1119 for (var i = 0; i < node.children.length; i++) {
1120 var n = node.children[i];
1121 if (n.tag == "page") {
1122 var page = new (this.view.registry.get_object('notebookpage'))(
1123 this.view, n, this, this.pages.length);
1124 this.pages.push(page);
1130 this._super.apply(this, arguments);
1131 this.$element.find('> ul > li').each(function (index, tab_li) {
1132 var page = self.pages[index],
1133 id = _.uniqueId(self.element_name + '-');
1134 page.element_id = id;
1135 $(tab_li).find('a').attr('href', '#' + id);
1137 this.$element.find('> div').each(function (index, page) {
1138 page.id = self.pages[index].element_id;
1140 this.$element.tabs();
1141 this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1142 if (openerp.connection.debug) {
1143 this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1148 do_select_first_visible_tab: function() {
1149 for (var i = 0; i < this.pages.length; i++) {
1150 var page = this.pages[i];
1151 if (page.invisible === false) {
1152 this.$element.tabs('select', page.index);
1159 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1160 template: 'WidgetNotebookPage',
1161 init: function(view, node, notebook, index) {
1162 this.notebook = notebook;
1164 this.element_name = 'page_' + index;
1165 this._super(view, node);
1168 this._super.apply(this, arguments);
1169 this.$element_tab = this.notebook.$element.find(
1170 '> ul > li:eq(' + this.index + ')');
1172 update_dom: function() {
1173 if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1174 this.notebook.do_select_first_visible_tab();
1176 this.$element_tab.toggle(!this.invisible);
1177 this.$element.toggle(!this.invisible);
1181 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1182 template: 'WidgetSeparator',
1183 init: function(view, node) {
1184 this._super(view, node);
1185 this.orientation = node.attrs.orientation || 'horizontal';
1186 if (this.orientation === 'vertical') {
1189 this.classname += '_' + this.orientation;
1193 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1194 template: 'WidgetButton',
1195 init: function(view, node) {
1196 this._super(view, node);
1197 this.force_disabled = false;
1199 // We don't have button key bindings in the webclient
1200 this.string = this.string.replace(/_/g, '');
1202 if (node.attrs.default_focus == '1') {
1203 // TODO fme: provide enter key binding to widgets
1204 this.view.default_focus_button = this;
1208 this._super.apply(this, arguments);
1209 this.$element.find("button").click(this.on_click);
1210 if (this.help || openerp.connection.debug) {
1211 this.do_attach_tooltip();
1214 on_click: function() {
1216 this.force_disabled = true;
1217 this.check_disable();
1218 this.execute_action().always(function() {
1219 self.force_disabled = false;
1220 self.check_disable();
1223 execute_action: function() {
1225 var exec_action = function() {
1226 if (self.node.attrs.confirm) {
1227 var def = $.Deferred();
1228 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1229 title: _t('Confirm'),
1232 {text: _t("Cancel"), click: function() {
1234 $(this).dialog("close");
1237 {text: _t("Ok"), click: function() {
1238 self.on_confirmed().then(function() {
1241 $(this).dialog("close");
1246 return def.promise();
1248 return self.on_confirmed();
1251 if (!this.node.attrs.special) {
1252 return this.view.recursive_save().pipe(exec_action);
1254 return exec_action();
1257 on_confirmed: function() {
1260 var context = this.node.attrs.context;
1261 if (context && context.__ref) {
1262 context = new openerp.web.CompoundContext(context);
1263 context.set_eval_context(this._build_eval_context());
1266 return this.view.do_execute_action(
1267 _.extend({}, this.node.attrs, {context: context}),
1268 this.view.dataset, this.view.datarecord.id, function () {
1272 update_dom: function() {
1273 this._super.apply(this, arguments);
1274 this.check_disable();
1276 check_disable: function() {
1277 var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1278 this.$element.find('button').prop('disabled', disabled);
1279 this.$element.find("button").css('color', disabled ? 'grey' : '');
1283 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1284 template: 'WidgetLabel',
1285 init: function(view, node) {
1286 this.element_name = 'label_' + node.attrs.name;
1288 this._super(view, node);
1290 if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1291 this.string = this.node.children[0];
1292 this.align = 'left';
1295 if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1296 this.template = "WidgetParagraph";
1297 this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1298 // Widgets default to right-aligned, but paragraph defaults to
1300 if (isNaN(parseFloat(this.node.attrs.align))) {
1301 this.align = 'left';
1304 this.multilines = this.string && _.str.lines(this.string).length > 1;
1308 this.decrease_max_width = 1;
1312 render: function () {
1313 if (this['for'] && this.type !== 'label') {
1314 return QWeb.render(this.template, {widget: this['for']});
1316 // Actual label widgets should not have a false and have type label
1317 return QWeb.render(this.template, {widget: this});
1322 if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1323 this.do_attach_tooltip(self['for']);
1325 this.$element.find("label").dblclick(function() {
1326 var widget = self['for'] || self;
1327 openerp.log(widget.element_class , widget);
1333 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1335 * @constructs openerp.web.form.Field
1336 * @extends openerp.web.form.Widget
1341 init: function(view, node) {
1342 this.name = node.attrs.name;
1343 this.value = undefined;
1344 view.fields[this.name] = this;
1345 view.fields_order.push(this.name);
1346 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1347 this.element_name = "field_" + this.name + "_" + this.type;
1349 this._super(view, node);
1351 if (node.attrs.nolabel != '1' && this.colspan > 1) {
1354 this.field = view.fields_view.fields[node.attrs.name] || {};
1355 this.string = node.attrs.string || this.field.string;
1356 this.help = node.attrs.help || this.field.help;
1357 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1358 this.readonly = this.modifiers['readonly'] === true;
1359 this.required = this.modifiers['required'] === true;
1360 this.invalid = this.dirty = false;
1362 this.classname = 'oe_form_field_' + this.type;
1365 this._super.apply(this, arguments);
1366 if (this.field.translate) {
1367 this.view.translatable_fields.push(this);
1368 this.$element.addClass('oe_form_field_translatable');
1369 this.$element.find('.oe_field_translate').click(this.on_translate);
1371 if (this.nolabel && openerp.connection.debug) {
1372 this.do_attach_tooltip(this, this.$element);
1375 set_value: function(value) {
1377 this.invalid = false;
1379 this.on_value_changed();
1381 set_value_from_ui: function() {
1382 this.on_value_changed();
1384 on_value_changed: function() {
1386 on_translate: function() {
1387 this.view.open_translate_dialog(this);
1389 get_value: function() {
1392 is_valid: function() {
1393 return !this.invalid;
1395 is_dirty: function() {
1396 return this.dirty && !this.readonly;
1398 get_on_change_value: function() {
1399 return this.get_value();
1401 update_dom: function(show_invalid) {
1402 this._super.apply(this, arguments);
1403 if (this.field.translate) {
1404 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1406 if (!this.disable_utility_classes) {
1407 this.$element.toggleClass('disabled', this.readonly);
1408 this.$element.toggleClass('required', this.required);
1410 this.$element.toggleClass('invalid', !this.is_valid());
1414 on_ui_change: function() {
1417 if (this.is_valid()) {
1418 this.set_value_from_ui();
1419 this.view.do_onchange(this);
1420 this.view.on_form_changed(true);
1422 this.update_dom(true);
1425 validate: function() {
1426 this.invalid = false;
1428 focus: function($element) {
1430 setTimeout(function() {
1438 get_definition_options: function() {
1439 if (!this.definition_options) {
1440 var str = this.node.attrs.options || '{}';
1441 this.definition_options = JSON.parse(str);
1443 return this.definition_options;
1447 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1448 template: 'FieldChar',
1449 init: function (view, node) {
1450 this._super(view, node);
1451 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1454 this._super.apply(this, arguments);
1455 this.$element.find('input').change(this.on_ui_change);
1457 set_value: function(value) {
1458 this._super.apply(this, arguments);
1459 var show_value = openerp.web.format_value(value, this, '');
1460 this.$element.find('input').val(show_value);
1463 update_dom: function() {
1464 this._super.apply(this, arguments);
1465 this.$element.find('input').prop('readonly', this.readonly);
1467 set_value_from_ui: function() {
1468 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1471 validate: function() {
1472 this.invalid = false;
1474 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1475 this.invalid = this.required && value === '';
1477 this.invalid = true;
1480 focus: function($element) {
1481 this._super($element || this.$element.find('input:first'));
1485 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1486 update_dom: function() {
1487 this._super.apply(this, arguments);
1488 this.$element.find('input').prop('readonly', true);
1492 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1493 template: 'FieldEmail',
1495 this._super.apply(this, arguments);
1496 this.$element.find('button').click(this.on_button_clicked);
1498 on_button_clicked: function() {
1499 if (!this.value || !this.is_valid()) {
1500 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1502 location.href = 'mailto:' + this.value;
1507 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1508 template: 'FieldUrl',
1510 this._super.apply(this, arguments);
1511 this.$element.find('button').click(this.on_button_clicked);
1513 on_button_clicked: function() {
1515 this.do_warn("Resource error", "This resource is empty");
1517 window.open(this.value);
1522 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1523 init: function (view, node) {
1524 this._super(view, node);
1525 if (node.attrs.digits) {
1526 this.parse_digits(node.attrs.digits);
1528 this.digits = view.fields_view.fields[node.attrs.name].digits;
1531 parse_digits: function (digits_attr) {
1532 // could use a Python parser instead.
1533 var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1534 return [parseInt(match[1], 10), parseInt(match[2], 10)];
1536 set_value: function(value) {
1537 if (value === false || value === undefined) {
1538 // As in GTK client, floats default to 0
1541 this._super.apply(this, [value]);
1545 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1546 template: "web.datetimepicker",
1547 jqueryui_object: 'datetimepicker',
1548 type_of_date: "datetime",
1549 init: function(parent) {
1550 this._super(parent);
1551 this.name = parent.name;
1555 this.$input = this.$element.find('input.oe_datepicker_master');
1556 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1557 this.$input.change(this.on_change);
1559 onSelect: this.on_picker_select,
1563 showButtonPanel: true
1565 this.$element.find('img.oe_datepicker_trigger').click(function() {
1566 if (!self.readonly && !self.picker('widget').is(':visible')) {
1567 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1568 self.$input_picker.show();
1569 self.picker('show');
1570 self.$input_picker.hide();
1573 this.set_readonly(false);
1576 picker: function() {
1577 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1579 on_picker_select: function(text, instance) {
1580 var date = this.picker('getDate');
1581 this.$input.val(date ? this.format_client(date) : '').change();
1583 set_value: function(value) {
1585 this.$input.val(value ? this.format_client(value) : '');
1587 get_value: function() {
1590 set_value_from_ui: function() {
1591 var value = this.$input.val() || false;
1592 this.value = this.parse_client(value);
1594 set_readonly: function(readonly) {
1595 this.readonly = readonly;
1596 this.$input.prop('readonly', this.readonly);
1597 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1599 is_valid: function(required) {
1600 var value = this.$input.val();
1605 this.parse_client(value);
1612 parse_client: function(v) {
1613 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1615 format_client: function(v) {
1616 return openerp.web.format_value(v, {"widget": this.type_of_date});
1618 on_change: function() {
1619 if (this.is_valid()) {
1620 this.set_value_from_ui();
1625 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1626 jqueryui_object: 'datepicker',
1627 type_of_date: "date"
1630 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1631 template: "EmptyComponent",
1632 build_widget: function() {
1633 return new openerp.web.DateTimeWidget(this);
1637 this._super.apply(this, arguments);
1638 this.datewidget = this.build_widget();
1639 this.datewidget.on_change.add_last(this.on_ui_change);
1640 this.datewidget.appendTo(this.$element);
1642 set_value: function(value) {
1644 this.datewidget.set_value(value);
1646 get_value: function() {
1647 return this.datewidget.get_value();
1649 update_dom: function() {
1650 this._super.apply(this, arguments);
1651 this.datewidget.set_readonly(this.readonly);
1653 validate: function() {
1654 this.invalid = !this.datewidget.is_valid(this.required);
1656 focus: function($element) {
1657 this._super($element || this.datewidget.$input);
1661 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1662 build_widget: function() {
1663 return new openerp.web.DateWidget(this);
1667 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1668 template: 'FieldText',
1670 this._super.apply(this, arguments);
1671 this.$element.find('textarea').change(this.on_ui_change);
1672 this.resized = false;
1674 set_value: function(value) {
1675 this._super.apply(this, arguments);
1676 var show_value = openerp.web.format_value(value, this, '');
1677 this.$element.find('textarea').val(show_value);
1678 if (!this.resized && this.view.options.resize_textareas) {
1679 this.do_resize(this.view.options.resize_textareas);
1680 this.resized = true;
1683 update_dom: function() {
1684 this._super.apply(this, arguments);
1685 this.$element.find('textarea').prop('readonly', this.readonly);
1687 set_value_from_ui: function() {
1688 this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1691 validate: function() {
1692 this.invalid = false;
1694 var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1695 this.invalid = this.required && value === '';
1697 this.invalid = true;
1700 focus: function($element) {
1701 this._super($element || this.$element.find('textarea:first'));
1703 do_resize: function(max_height) {
1704 max_height = parseInt(max_height, 10);
1705 var $input = this.$element.find('textarea'),
1706 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1708 $div.text($input.val());
1709 _.each('font-family,font-size,white-space'.split(','), function(style) {
1710 $div.css(style, $input.css(style));
1712 $div.appendTo($('body'));
1713 new_height = $div.height();
1714 if (new_height < 90) {
1717 if (!isNaN(max_height) && new_height > max_height) {
1718 new_height = max_height;
1721 $input.height(new_height);
1724 this.resized = false;
1728 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1729 template: 'FieldBoolean',
1732 this._super.apply(this, arguments);
1733 this.$element.find('input').click(self.on_ui_change);
1735 set_value: function(value) {
1736 this._super.apply(this, arguments);
1737 this.$element.find('input')[0].checked = value;
1739 set_value_from_ui: function() {
1740 this.value = this.$element.find('input').is(':checked');
1743 update_dom: function() {
1744 this._super.apply(this, arguments);
1745 this.$element.find('input').prop('disabled', this.readonly);
1747 focus: function($element) {
1748 this._super($element || this.$element.find('input:first'));
1752 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1753 template: 'FieldProgressBar',
1755 this._super.apply(this, arguments);
1756 this.$element.find('div').progressbar({
1758 disabled: this.readonly
1761 set_value: function(value) {
1762 this._super.apply(this, arguments);
1763 var show_value = Number(value);
1764 if (isNaN(show_value)) {
1767 var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1768 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1772 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1773 // to replace view editor
1776 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1777 template: 'FieldSelection',
1778 init: function(view, node) {
1780 this._super(view, node);
1781 this.values = _.clone(this.field.selection);
1782 _.each(this.values, function(v, i) {
1783 if (v[0] === false && v[1] === '') {
1784 self.values.splice(i, 1);
1787 this.values.unshift([false, '']);
1790 // Flag indicating whether we're in an event chain containing a change
1791 // event on the select, in order to know what to do on keyup[RETURN]:
1792 // * If the user presses [RETURN] as part of changing the value of a
1793 // selection, we should just let the value change and not let the
1794 // event broadcast further (e.g. to validating the current state of
1795 // the form in editable list view, which would lead to saving the
1796 // current row or switching to the next one)
1797 // * If the user presses [RETURN] with a select closed (side-effect:
1798 // also if the user opened the select and pressed [RETURN] without
1799 // changing the selected value), takes the action as validating the
1801 var ischanging = false;
1802 this._super.apply(this, arguments);
1803 this.$element.find('select')
1804 .change(this.on_ui_change)
1805 .change(function () { ischanging = true; })
1806 .click(function () { ischanging = false; })
1807 .keyup(function (e) {
1808 if (e.which !== 13 || !ischanging) { return; }
1809 e.stopPropagation();
1813 set_value: function(value) {
1814 value = value === null ? false : value;
1815 value = value instanceof Array ? value[0] : value;
1818 for (var i = 0, ii = this.values.length; i < ii; i++) {
1819 if (this.values[i][0] === value) index = i;
1821 this.$element.find('select')[0].selectedIndex = index;
1823 set_value_from_ui: function() {
1824 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1827 update_dom: function() {
1828 this._super.apply(this, arguments);
1829 this.$element.find('select').prop('disabled', this.readonly);
1831 validate: function() {
1832 var value = this.values[this.$element.find('select')[0].selectedIndex];
1833 this.invalid = !(value && !(this.required && value[0] === false));
1835 focus: function($element) {
1836 this._super($element || this.$element.find('select:first'));
1840 // jquery autocomplete tweak to allow html
1842 var proto = $.ui.autocomplete.prototype,
1843 initSource = proto._initSource;
1845 function filter( array, term ) {
1846 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1847 return $.grep( array, function(value) {
1848 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1853 _initSource: function() {
1854 if ( this.options.html && $.isArray(this.options.source) ) {
1855 this.source = function( request, response ) {
1856 response( filter( this.options.source, request.term ) );
1859 initSource.call( this );
1863 _renderItem: function( ul, item) {
1864 return $( "<li></li>" )
1865 .data( "item.autocomplete", item )
1866 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1872 openerp.web.form.dialog = function(content, options) {
1873 options = _.extend({
1878 var dialog = new openerp.web.Dialog(null, options, content).open();
1879 return dialog.$element;
1882 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1883 template: 'FieldMany2One',
1884 init: function(view, node) {
1885 this._super(view, node);
1888 this.cm_id = _.uniqueId('m2o_cm_');
1889 this.last_search = [];
1890 this.tmp_value = undefined;
1895 this.$input = this.$element.find("input");
1896 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1897 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1900 var init_context_menu_def = $.Deferred().then(function(e) {
1901 var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1902 rdataset.call("get", ['action', 'client_action_relate',
1903 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1904 .then(function(result) {
1905 self.related_entries = result;
1907 var $cmenu = $("#" + self.cm_id);
1908 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1910 bindings[self.cm_id + "_search"] = function() {
1911 self._search_create_popup("search");
1913 bindings[self.cm_id + "_create"] = function() {
1914 self._search_create_popup("form");
1916 bindings[self.cm_id + "_open"] = function() {
1920 var pop = new openerp.web.form.FormOpenPopup(self.view);
1922 self.field.relation,
1924 self.build_context(),
1926 title: _t("Open: ") + (self.string || self.name)
1929 pop.on_write_completed.add_last(function() {
1930 self.set_value(self.value[0]);
1933 _.each(_.range(self.related_entries.length), function(i) {
1934 bindings[self.cm_id + "_related_" + i] = function() {
1935 self.open_related(self.related_entries[i]);
1938 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1939 bindings: bindings, itemStyle: {"color": ""},
1940 onContextMenu: function() {
1942 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1944 $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1946 if (!self.readonly) {
1947 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1949 $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1952 }, menuStyle: {width: "200px"}
1954 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1957 var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1958 this.$menu_btn.click(ctx_callback);
1960 // some behavior for input
1961 this.$input.keyup(function() {
1962 if (self.$input.val() === "") {
1963 self._change_int_value(null);
1964 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1965 self._change_int_value(undefined);
1968 this.$drop_down.click(function() {
1971 if (self.$input.autocomplete("widget").is(":visible")) {
1972 self.$input.autocomplete("close");
1975 self.$input.autocomplete("search", "");
1977 self.$input.autocomplete("search");
1979 self.$input.focus();
1982 var anyoneLoosesFocus = function() {
1983 if (!self.$input.is(":focus") &&
1984 !self.$input.autocomplete("widget").is(":visible") &&
1986 if (self.value === undefined && self.last_search.length > 0) {
1987 self._change_int_ext_value(self.last_search[0]);
1989 self._change_int_ext_value(null);
1993 this.$input.focusout(anyoneLoosesFocus);
1995 var isSelecting = false;
1997 this.$input.autocomplete({
1998 source: function(req, resp) { self.get_search_result(req, resp); },
1999 select: function(event, ui) {
2003 self._change_int_value([item.id, item.name]);
2004 } else if (item.action) {
2005 self._change_int_value(undefined);
2010 focus: function(e, ui) {
2014 close: anyoneLoosesFocus,
2018 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2019 this.$input.keyup(function(e) {
2020 if (e.which === 13) {
2022 e.stopPropagation();
2024 isSelecting = false;
2027 // autocomplete component content handling
2028 get_search_result: function(request, response) {
2029 var search_val = request.term;
2032 if (this.abort_last) {
2034 delete this.abort_last;
2036 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2038 dataset.name_search(search_val, self.build_domain(), 'ilike',
2039 this.limit + 1, function(data) {
2040 self.last_search = data;
2041 // possible selections for the m2o
2042 var values = _.map(data, function(x) {
2044 label: _.str.escapeHTML(x[1]),
2051 // search more... if more results that max
2052 if (values.length > self.limit) {
2053 values = values.slice(0, self.limit);
2054 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2055 dataset.name_search(search_val, self.build_domain(), 'ilike'
2056 , false, function(data) {
2057 self._change_int_value(null);
2058 self._search_create_popup("search", data);
2063 var raw_result = _(data.result).map(function(x) {return x[1];});
2064 if (search_val.length > 0 &&
2065 !_.include(raw_result, search_val) &&
2066 (!self.value || search_val !== self.value[1])) {
2067 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2068 $('<span />').text(search_val).html()), action: function() {
2069 self._quick_create(search_val);
2073 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2074 self._change_int_value(null);
2075 self._search_create_popup("form", undefined, {"default_name": search_val});
2080 this.abort_last = dataset.abort_last;
2082 _quick_create: function(name) {
2084 var slow_create = function () {
2085 self._change_int_value(null);
2086 self._search_create_popup("form", undefined, {"default_name": name});
2088 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2089 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2090 dataset.name_create(name, function(data) {
2091 self._change_int_ext_value(data);
2092 }).fail(function(error, event) {
2093 event.preventDefault();
2099 // all search/create popup handling
2100 _search_create_popup: function(view, ids, context) {
2102 var pop = new openerp.web.form.SelectCreatePopup(this);
2104 self.field.relation,
2106 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2107 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2109 disable_multiple_selection: true
2111 self.build_domain(),
2112 new openerp.web.CompoundContext(self.build_context(), context || {})
2114 pop.on_select_elements.add(function(element_ids) {
2115 var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2116 dataset.name_get([element_ids[0]], function(data) {
2117 self._change_int_ext_value(data[0]);
2121 _change_int_ext_value: function(value) {
2122 this._change_int_value(value);
2123 this.$input.val(this.value ? this.value[1] : "");
2125 _change_int_value: function(value) {
2127 var back_orig_value = this.original_value;
2128 if (this.value === null || this.value) {
2129 this.original_value = this.value;
2131 if (back_orig_value === undefined) { // first use after a set_value()
2134 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2135 !== (this.value ? this.value[0] : null))) {
2136 this.on_ui_change();
2139 set_value: function(value) {
2140 value = value || null;
2141 this.invalid = false;
2143 this.tmp_value = value;
2145 self.on_value_changed();
2146 var real_set_value = function(rval) {
2147 self.tmp_value = undefined;
2149 self.original_value = undefined;
2150 self._change_int_ext_value(rval);
2152 if (value && !(value instanceof Array)) {
2153 // name_get in a m2o does not use the context of the field
2154 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2155 dataset.name_get([value], function(data) {
2156 real_set_value(data[0]);
2157 }).fail(function() {self.tmp_value = undefined;});
2159 $.async_when().then(function() {real_set_value(value);});
2162 get_value: function() {
2163 if (this.tmp_value !== undefined) {
2164 if (this.tmp_value instanceof Array) {
2165 return this.tmp_value[0];
2167 return this.tmp_value ? this.tmp_value : false;
2169 if (this.value === undefined)
2170 return this.original_value ? this.original_value[0] : false;
2171 return this.value ? this.value[0] : false;
2173 validate: function() {
2174 this.invalid = false;
2175 var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2177 this.invalid = this.required;
2180 open_related: function(related) {
2184 var additional_context = {
2185 active_id: self.value[0],
2186 active_ids: [self.value[0]],
2187 active_model: self.field.relation
2189 self.rpc("/web/action/load", {
2190 action_id: related[2].id,
2191 context: additional_context
2192 }, function(result) {
2193 result.result.context = _.extend(result.result.context || {}, additional_context);
2194 self.do_action(result.result);
2197 focus: function ($element) {
2198 this._super($element || this.$input);
2200 update_dom: function() {
2201 this._super.apply(this, arguments);
2202 this.$input.prop('readonly', this.readonly);
2207 # Values: (0, 0, { fields }) create
2208 # (1, ID, { fields }) update
2209 # (2, ID) remove (delete)
2210 # (3, ID) unlink one (target id or target of relation)
2212 # (5) unlink all (only valid for one2many)
2217 'create': function (values) {
2218 return [commands.CREATE, false, values];
2220 // (1, id, {values})
2222 'update': function (id, values) {
2223 return [commands.UPDATE, id, values];
2227 'delete': function (id) {
2228 return [commands.DELETE, id, false];
2230 // (3, id[, _]) removes relation, but not linked record itself
2232 'forget': function (id) {
2233 return [commands.FORGET, id, false];
2237 'link_to': function (id) {
2238 return [commands.LINK_TO, id, false];
2242 'delete_all': function () {
2243 return [5, false, false];
2245 // (6, _, ids) replaces all linked records with provided ids
2247 'replace_with': function (ids) {
2248 return [6, false, ids];
2251 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2252 template: 'FieldOne2Many',
2253 multi_selection: false,
2254 init: function(view, node) {
2255 this._super(view, node);
2256 this.is_loaded = $.Deferred();
2257 this.initial_is_loaded = this.is_loaded;
2258 this.is_setted = $.Deferred();
2259 this.form_last_update = $.Deferred();
2260 this.init_form_last_update = this.form_last_update;
2261 this.disable_utility_classes = true;
2264 this._super.apply(this, arguments);
2268 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2269 this.dataset.o2m = this;
2270 this.dataset.parent_view = this.view;
2271 this.dataset.child_name = this.name;
2272 //this.dataset.child_name =
2273 this.dataset.on_change.add_last(function() {
2274 self.trigger_on_change();
2277 this.is_setted.then(function() {
2281 trigger_on_change: function() {
2282 var tmp = this.doing_on_change;
2283 this.doing_on_change = true;
2284 this.on_ui_change();
2285 this.doing_on_change = tmp;
2287 is_readonly: function() {
2288 return this.readonly || this.force_readonly;
2290 load_views: function() {
2293 var modes = this.node.attrs.mode;
2294 modes = !!modes ? modes.split(",") : ["tree"];
2296 _.each(modes, function(mode) {
2299 view_type: mode == "tree" ? "list" : mode,
2300 options: { sidebar : false }
2302 if (self.field.views && self.field.views[mode]) {
2303 view.embedded_view = self.field.views[mode];
2305 if(view.view_type === "list") {
2306 view.options.selectable = self.multi_selection;
2307 if (self.is_readonly()) {
2308 view.options.addable = null;
2309 view.options.deletable = null;
2310 view.options.isClarkGable = false;
2312 } else if (view.view_type === "form") {
2313 if (self.is_readonly()) {
2314 view.view_type = 'page';
2316 view.options.not_interactible_on_create = true;
2322 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2323 this.viewmanager.template = 'One2Many.viewmanager';
2324 this.viewmanager.registry = openerp.web.views.extend({
2325 list: 'openerp.web.form.One2ManyListView',
2326 form: 'openerp.web.form.One2ManyFormView',
2327 page: 'openerp.web.PageView'
2329 var once = $.Deferred().then(function() {
2330 self.init_form_last_update.resolve();
2332 var def = $.Deferred().then(function() {
2333 self.initial_is_loaded.resolve();
2335 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2336 if (view_type == "list") {
2337 controller.o2m = self;
2338 if (self.is_readonly())
2339 controller.set_editable(false);
2340 } else if (view_type == "form" || view_type == 'page') {
2341 if (view_type == 'page' || self.is_readonly()) {
2342 $(".oe_form_buttons", controller.$element).children().remove();
2344 controller.on_record_loaded.add_last(function() {
2347 controller.on_pager_action.add_first(function() {
2348 self.save_any_view();
2350 } else if (view_type == "graph") {
2351 self.reload_current_view()
2355 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2356 $.when(self.save_any_view()).then(function() {
2357 if(n_mode === "list")
2358 $.async_when().then(function() {self.reload_current_view();});
2361 this.is_setted.then(function() {
2362 $.async_when().then(function () {
2363 self.viewmanager.appendTo(self.$element);
2368 reload_current_view: function() {
2370 return self.is_loaded = self.is_loaded.pipe(function() {
2371 var active_view = self.viewmanager.active_view;
2372 var view = self.viewmanager.views[active_view].controller;
2373 if(active_view === "list") {
2374 return view.reload_content();
2375 } else if (active_view === "form" || active_view === 'page') {
2376 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2377 self.dataset.index = 0;
2379 var act = function() {
2380 return view.do_show();
2382 self.form_last_update = self.form_last_update.pipe(act, act);
2383 return self.form_last_update;
2384 } else if (active_view === "graph") {
2385 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2389 set_value: function(value) {
2390 value = value || [];
2392 this.dataset.reset_ids([]);
2393 if(value.length >= 1 && value[0] instanceof Array) {
2395 _.each(value, function(command) {
2396 var obj = {values: command[2]};
2397 switch (command[0]) {
2398 case commands.CREATE:
2399 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2401 self.dataset.to_create.push(obj);
2402 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2405 case commands.UPDATE:
2406 obj['id'] = command[1];
2407 self.dataset.to_write.push(obj);
2408 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2411 case commands.DELETE:
2412 self.dataset.to_delete.push({id: command[1]});
2414 case commands.LINK_TO:
2415 ids.push(command[1]);
2417 case commands.DELETE_ALL:
2418 self.dataset.delete_all = true;
2423 this.dataset.set_ids(ids);
2424 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2426 this.dataset.delete_all = true;
2427 _.each(value, function(command) {
2428 var obj = {values: command};
2429 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2431 self.dataset.to_create.push(obj);
2432 self.dataset.cache.push(_.clone(obj));
2436 this.dataset.set_ids(ids);
2439 this.dataset.reset_ids(value);
2441 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2442 this.dataset.index = 0;
2444 self.is_setted.resolve();
2445 return self.reload_current_view();
2447 get_value: function() {
2451 this.save_any_view();
2452 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2453 val = val.concat(_.map(this.dataset.ids, function(id) {
2454 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2456 return commands.create(alter_order.values);
2458 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2460 return commands.update(alter_order.id, alter_order.values);
2462 return commands.link_to(id);
2464 return val.concat(_.map(
2465 this.dataset.to_delete, function(x) {
2466 return commands['delete'](x.id);}));
2468 save_any_view: function() {
2469 if (this.doing_on_change)
2471 return this.session.synchronized_mode(_.bind(function() {
2472 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2473 this.viewmanager.views[this.viewmanager.active_view] &&
2474 this.viewmanager.views[this.viewmanager.active_view].controller) {
2475 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2476 if (this.viewmanager.active_view === "form") {
2477 if (!view.is_initialized.isResolved()) {
2480 var res = $.when(view.do_save());
2481 if (!res.isResolved() && !res.isRejected()) {
2482 console.warn("Asynchronous get_value() is not supported in form view.");
2485 } else if (this.viewmanager.active_view === "list") {
2486 var res = $.when(view.ensure_saved());
2487 if (!res.isResolved() && !res.isRejected()) {
2488 console.warn("Asynchronous get_value() is not supported in list view.");
2496 is_valid: function() {
2498 return this._super();
2500 validate: function() {
2501 this.invalid = false;
2502 if (!this.viewmanager.views[this.viewmanager.active_view])
2504 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2505 if (this.viewmanager.active_view === "form") {
2506 for (var f in view.fields) {
2508 if (!f.is_valid()) {
2509 this.invalid = true;
2515 is_dirty: function() {
2516 this.save_any_view();
2517 return this._super();
2519 update_dom: function() {
2520 this._super.apply(this, arguments);
2522 if (this.previous_readonly !== this.readonly) {
2523 this.previous_readonly = this.readonly;
2524 if (this.viewmanager) {
2525 this.is_loaded = this.is_loaded.pipe(function() {
2526 self.viewmanager.stop();
2527 return $.when(self.load_views()).then(function() {
2528 self.reload_current_view();
2536 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2537 get_context: function() {
2538 this.context = this.o2m.build_context([this.o2m.name]);
2539 return this.context;
2543 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2544 _template: 'One2Many.listview',
2545 do_add_record: function () {
2546 if (this.options.editable) {
2547 this._super.apply(this, arguments);
2550 var pop = new openerp.web.form.SelectCreatePopup(this);
2551 pop.on_default_get.add(self.dataset.on_default_get);
2553 self.o2m.field.relation,
2555 title: _t("Create: ") + self.name,
2556 initial_view: "form",
2557 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2558 create_function: function(data, callback, error_callback) {
2559 return self.o2m.dataset.create(data).then(function(r) {
2560 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2561 self.o2m.dataset.on_change();
2562 }).then(callback, error_callback);
2564 read_function: function() {
2565 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2567 parent_view: self.o2m.view,
2568 child_name: self.o2m.name,
2569 form_view_options: {'not_interactible_on_create':true}
2571 self.o2m.build_domain(),
2572 self.o2m.build_context()
2574 pop.on_select_elements.add_last(function() {
2575 self.o2m.reload_current_view();
2579 do_activate_record: function(index, id) {
2581 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2582 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2583 title: _t("Open: ") + self.name,
2585 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2586 parent_view: self.o2m.view,
2587 child_name: self.o2m.name,
2588 read_function: function() {
2589 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2591 form_view_options: {'not_interactible_on_create':true},
2592 readonly: self.o2m.is_readonly()
2594 pop.on_write.add(function(id, data) {
2595 self.o2m.dataset.write(id, data, {}, function(r) {
2596 self.o2m.reload_current_view();
2600 do_button_action: function (name, id, callback) {
2602 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2603 return this._super(name, id, _.bind(def.resolve, def));
2607 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2608 form_template: 'One2Many.formview',
2609 on_loaded: function(data) {
2612 this.$form_header.find('button.oe_form_button_create').click(function() {
2613 self.do_save().then(self.on_button_new);
2618 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2619 template: 'FieldMany2Many',
2620 multi_selection: false,
2621 init: function(view, node) {
2622 this._super(view, node);
2623 this.list_id = _.uniqueId("many2many");
2624 this.is_loaded = $.Deferred();
2625 this.initial_is_loaded = this.is_loaded;
2626 this.is_setted = $.Deferred();
2629 this._super.apply(this, arguments);
2633 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2634 this.dataset.m2m = this;
2635 this.dataset.on_unlink.add_last(function(ids) {
2636 self.on_ui_change();
2639 this.is_setted.then(function() {
2643 set_value: function(value) {
2644 value = value || [];
2645 if (value.length >= 1 && value[0] instanceof Array) {
2646 value = value[0][2];
2649 this.dataset.set_ids(value);
2651 self.reload_content();
2652 this.is_setted.resolve();
2654 get_value: function() {
2655 return [commands.replace_with(this.dataset.ids)];
2657 validate: function() {
2658 this.invalid = false;
2660 is_readonly: function() {
2661 return this.readonly || this.force_readonly;
2663 load_view: function() {
2665 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2666 'addable': self.is_readonly() ? null : _t("Add"),
2667 'deletable': self.is_readonly() ? false : true,
2668 'selectable': self.multi_selection,
2669 'isClarkGable': self.is_readonly() ? false : true
2671 var embedded = (this.field.views || {}).tree;
2673 this.list_view.set_embedded_view(embedded);
2675 this.list_view.m2m_field = this;
2676 var loaded = $.Deferred();
2677 this.list_view.on_loaded.add_last(function() {
2678 self.initial_is_loaded.resolve();
2681 $.async_when().then(function () {
2682 self.list_view.appendTo($("#" + self.list_id));
2686 reload_content: function() {
2688 this.is_loaded = this.is_loaded.pipe(function() {
2689 return self.list_view.reload_content();
2692 update_dom: function() {
2693 this._super.apply(this, arguments);
2695 if (this.previous_readonly !== this.readonly) {
2696 this.previous_readonly = this.readonly;
2697 if (this.list_view) {
2698 this.is_loaded = this.is_loaded.pipe(function() {
2699 self.list_view.stop();
2700 return $.when(self.load_view()).then(function() {
2701 self.reload_content();
2709 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2710 get_context: function() {
2711 this.context = this.m2m.build_context();
2712 return this.context;
2718 * @extends openerp.web.ListView
2720 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2721 do_add_record: function () {
2722 var pop = new openerp.web.form.SelectCreatePopup(this);
2726 title: _t("Add: ") + this.name
2728 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2729 this.m2m_field.build_context()
2732 pop.on_select_elements.add(function(element_ids) {
2733 _.each(element_ids, function(element_id) {
2734 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2735 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2736 self.m2m_field.on_ui_change();
2737 self.reload_content();
2742 do_activate_record: function(index, id) {
2744 var pop = new openerp.web.form.FormOpenPopup(this);
2745 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2746 title: _t("Open: ") + this.name,
2747 readonly: this.widget_parent.is_readonly()
2749 pop.on_write_completed.add_last(function() {
2750 self.reload_content();
2757 * @extends openerp.web.OldWidget
2759 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2760 template: "SelectCreatePopup",
2764 * - initial_view: form or search (default search)
2765 * - disable_multiple_selection
2766 * - alternative_form_view
2767 * - create_function (defaults to a naive saving behavior)
2770 * - form_view_options
2771 * - list_view_options
2774 select_element: function(model, options, domain, context) {
2777 this.domain = domain || [];
2778 this.context = context || {};
2779 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2780 return self.create_row.apply(self, arguments);
2781 }, read_function: null});
2782 this.initial_ids = this.options.initial_ids;
2783 this.created_elements = [];
2784 this.render_element();
2785 openerp.web.form.dialog(this.$element, {
2789 title: options.title || ""
2796 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2798 this.dataset.create_function = function() {
2799 return self.options.create_function.apply(null, arguments).then(function(r) {
2800 self.created_elements.push(r.result);
2803 this.dataset.write_function = function() {
2804 return self.write_row.apply(self, arguments);
2806 this.dataset.read_function = this.options.read_function;
2807 this.dataset.parent_view = this.options.parent_view;
2808 this.dataset.child_name = this.options.child_name;
2809 this.dataset.on_default_get.add(this.on_default_get);
2810 if (this.options.initial_view == "search") {
2811 self.rpc('/web/session/eval_domain_and_context', {
2813 contexts: [this.context]
2814 }, function (results) {
2815 var search_defaults = {};
2816 _.each(results.context, function (value, key) {
2817 var match = /^search_default_(.*)$/.exec(key);
2819 search_defaults[match[1]] = value;
2822 self.setup_search_view(search_defaults);
2828 setup_search_view: function(search_defaults) {
2830 if (this.searchview) {
2831 this.searchview.stop();
2833 this.searchview = new openerp.web.SearchView(this,
2834 this.dataset, false, search_defaults);
2835 this.searchview.on_search.add(function(domains, contexts, groupbys) {
2836 if (self.initial_ids) {
2837 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2838 contexts, groupbys);
2839 self.initial_ids = undefined;
2841 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2844 this.searchview.on_loaded.add_last(function () {
2845 self.view_list = new openerp.web.form.SelectCreateListView(self,
2846 self.dataset, false,
2847 _.extend({'deletable': false,
2848 'selectable': !self.options.disable_multiple_selection
2849 }, self.options.list_view_options || {}));
2850 self.view_list.popup = self;
2851 self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2852 self.view_list.do_show();
2853 }).pipe(function() {
2854 self.searchview.do_search();
2856 self.view_list.on_loaded.add_last(function() {
2857 var $buttons = self.view_list.$element.find(".oe-actions");
2858 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2859 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2860 $cbutton.click(function() {
2863 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2864 if(self.options.disable_multiple_selection) {
2867 $sbutton.click(function() {
2868 self.on_select_elements(self.selected_ids);
2873 this.searchview.appendTo($("#" + this.element_id + "_search"));
2875 do_search: function(domains, contexts, groupbys) {
2877 this.rpc('/web/session/eval_domain_and_context', {
2878 domains: domains || [],
2879 contexts: contexts || [],
2880 group_by_seq: groupbys || []
2881 }, function (results) {
2882 self.view_list.do_search(results.domain, results.context, results.group_by);
2885 create_row: function() {
2887 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2888 wdataset.parent_view = this.options.parent_view;
2889 wdataset.child_name = this.options.child_name;
2890 return wdataset.create.apply(wdataset, arguments);
2892 write_row: function() {
2894 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2895 wdataset.parent_view = this.options.parent_view;
2896 wdataset.child_name = this.options.child_name;
2897 return wdataset.write.apply(wdataset, arguments);
2899 on_select_elements: function(element_ids) {
2901 on_click_element: function(ids) {
2902 this.selected_ids = ids || [];
2903 if(this.selected_ids.length > 0) {
2904 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2906 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2909 new_object: function() {
2911 if (this.searchview) {
2912 this.searchview.hide();
2914 if (this.view_list) {
2915 this.view_list.$element.hide();
2917 this.dataset.index = null;
2918 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2919 if (this.options.alternative_form_view) {
2920 this.view_form.set_embedded_view(this.options.alternative_form_view);
2922 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2923 this.view_form.on_loaded.add_last(function() {
2924 var $buttons = self.view_form.$element.find(".oe_form_buttons");
2925 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2926 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2927 $nbutton.click(function() {
2928 $.when(self.view_form.do_save()).then(function() {
2929 self.view_form.reload_mutex.exec(function() {
2930 self.view_form.on_button_new();
2934 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2935 $nbutton.click(function() {
2936 $.when(self.view_form.do_save()).then(function() {
2937 self.view_form.reload_mutex.exec(function() {
2942 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2943 $cbutton.click(function() {
2947 this.view_form.do_show();
2949 check_exit: function() {
2950 if (this.created_elements.length > 0) {
2951 this.on_select_elements(this.created_elements);
2955 on_default_get: function(res) {}
2958 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2959 do_add_record: function () {
2960 this.popup.new_object();
2962 select_record: function(index) {
2963 this.popup.on_select_elements([this.dataset.ids[index]]);
2966 do_select: function(ids, records) {
2967 this._super(ids, records);
2968 this.popup.on_click_element(ids);
2974 * @extends openerp.web.OldWidget
2976 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2977 template: "FormOpenPopup",
2980 * - alternative_form_view
2981 * - auto_write (default true)
2985 * - form_view_options
2988 show_element: function(model, row_id, context, options) {
2990 this.row_id = row_id;
2991 this.context = context || {};
2992 this.options = _.defaults(options || {}, {"auto_write": true});
2993 this.render_element();
2994 this.$element.dialog({
2995 title: options.title || '',
3004 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3005 this.dataset.fop = this;
3006 this.dataset.ids = [this.row_id];
3007 this.dataset.index = 0;
3008 this.dataset.parent_view = this.options.parent_view;
3009 this.dataset.child_name = this.options.child_name;
3010 this.setup_form_view();
3012 on_write: function(id, data) {
3013 if (!this.options.auto_write)
3016 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3017 wdataset.parent_view = this.options.parent_view;
3018 wdataset.child_name = this.options.child_name;
3019 wdataset.write(id, data, {}, function(r) {
3020 self.on_write_completed();
3023 on_write_completed: function() {},
3024 setup_form_view: function() {
3026 var FormClass = this.options.readonly
3027 ? openerp.web.views.get_object('page')
3028 : openerp.web.views.get_object('form');
3029 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3030 if (this.options.alternative_form_view) {
3031 this.view_form.set_embedded_view(this.options.alternative_form_view);
3033 this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3034 this.view_form.on_loaded.add_last(function() {
3035 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3036 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3037 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3038 $nbutton.click(function() {
3039 self.view_form.do_save().then(function() {
3043 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3044 $cbutton.click(function() {
3047 if (self.options.readonly) {
3049 $cbutton.text(_t("Close"));
3051 self.view_form.do_show();
3053 this.dataset.on_write.add(this.on_write);
3057 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3058 read_ids: function() {
3059 if (this.fop.options.read_function) {
3060 return this.fop.options.read_function.apply(null, arguments);
3062 return this._super.apply(this, arguments);
3067 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3068 template: 'FieldReference',
3069 init: function(view, node) {
3070 this._super(view, node);
3071 this.fields_view = {
3074 selection: view.fields_view.fields[this.name].selection
3081 this.get_fields_values = view.get_fields_values;
3082 this.get_selected_ids = view.get_selected_ids;
3083 this.do_onchange = this.on_form_changed = this.on_nop;
3084 this.dataset = this.view.dataset;
3085 this.widgets_counter = 0;
3086 this.view_id = 'reference_' + _.uniqueId();
3089 this.fields_order = [];
3090 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3094 this.reference_ready = true;
3095 this.selection.on_value_changed.add_last(this.on_selection_changed);
3096 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3100 this.m2o.on_ui_change.add_last(this.on_ui_change);
3102 on_nop: function() {
3104 on_selection_changed: function() {
3105 if (this.reference_ready) {
3106 var sel = this.selection.get_value();
3107 this.m2o.field.relation = sel;
3108 this.m2o.set_value(null);
3109 this.m2o.$element.toggle(sel !== false);
3114 this.selection.start();
3117 is_valid: function() {
3118 return this.required === false || typeof(this.get_value()) === 'string';
3120 is_dirty: function() {
3121 return this.selection.is_dirty() || this.m2o.is_dirty();
3123 set_value: function(value) {
3125 this.reference_ready = false;
3126 var vals = [], sel_val, m2o_val;
3127 if (typeof(value) === 'string') {
3128 vals = value.split(',');
3130 sel_val = vals[0] || false;
3131 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3132 this.selection.set_value(sel_val);
3133 this.m2o.field.relation = sel_val;
3134 this.m2o.set_value(m2o_val);
3135 this.m2o.$element.toggle(sel_val !== false);
3136 this.reference_ready = true;
3138 get_value: function() {
3139 var model = this.selection.get_value(),
3140 id = this.m2o.get_value();
3141 if (typeof(model) === 'string' && typeof(id) === 'number') {
3142 return model + ',' + id;
3149 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3150 init: function(view, node) {
3151 this._super(view, node);
3152 this.iframe = this.element_id + '_iframe';
3153 this.binary_value = false;
3156 this._super.apply(this, arguments);
3157 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3158 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3159 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3161 human_filesize : function(size) {
3162 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3164 while (size >= 1024) {
3168 return size.toFixed(2) + ' ' + units[i];
3170 on_file_change: function(e) {
3171 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3172 // http://www.html5rocks.com/tutorials/file/dndfiles/
3173 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3174 window[this.iframe] = this.on_file_uploaded;
3175 if ($(e.target).val() != '') {
3176 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3177 this.$element.find('form.oe-binary-form').submit();
3178 this.$element.find('.oe-binary-progress').show();
3179 this.$element.find('.oe-binary').hide();
3182 on_file_uploaded: function(size, name, content_type, file_base64) {
3183 delete(window[this.iframe]);
3184 if (size === false) {
3185 this.do_warn("File Upload", "There was a problem while uploading your file");
3186 // TODO: use openerp web crashmanager
3187 console.warn("Error while uploading file : ", name);
3189 this.on_file_uploaded_and_valid.apply(this, arguments);
3190 this.on_ui_change();
3192 this.$element.find('.oe-binary-progress').hide();
3193 this.$element.find('.oe-binary').show();
3195 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3197 on_save_as: function() {
3199 this.session.get_file({
3200 url: '/web/binary/saveas_ajax',
3201 data: {data: JSON.stringify({
3202 model: this.view.dataset.model,
3203 id: (this.view.datarecord.id || ''),
3205 filename_field: (this.node.attrs.filename || ''),
3206 context: this.view.dataset.get_context()
3208 complete: $.unblockUI,
3209 error: openerp.webclient.crashmanager.on_rpc_error
3212 on_clear: function() {
3213 if (this.value !== false) {
3215 this.binary_value = false;
3216 this.on_ui_change();
3222 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3223 template: 'FieldBinaryFile',
3224 update_dom: function() {
3225 this._super.apply(this, arguments);
3226 this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3227 this.$element.find('input[type=text]').prop('readonly', this.readonly);
3229 set_value: function(value) {
3230 this._super.apply(this, arguments);
3232 if (this.node.attrs.filename) {
3233 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3235 show_value = (value != null && value !== false) ? value : '';
3237 this.$element.find('input').eq(0).val(show_value);
3239 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3240 this.value = file_base64;
3241 this.binary_value = true;
3242 var show_value = name + " (" + this.human_filesize(size) + ")";
3243 this.$element.find('input').eq(0).val(show_value);
3244 this.set_filename(name);
3246 set_filename: function(value) {
3247 var filename = this.node.attrs.filename;
3248 if (this.view.fields[filename]) {
3249 this.view.fields[filename].set_value(value);
3250 this.view.fields[filename].on_ui_change();
3253 on_clear: function() {
3254 this._super.apply(this, arguments);
3255 this.$element.find('input').eq(0).val('');
3256 this.set_filename('');
3260 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3261 template: 'FieldBinaryImage',
3263 this._super.apply(this, arguments);
3264 this.$image = this.$element.find('img.oe-binary-image');
3266 update_dom: function() {
3267 this._super.apply(this, arguments);
3268 this.$element.find('.oe-binary').toggle(!this.readonly);
3270 set_value: function(value) {
3271 this._super.apply(this, arguments);
3272 this.set_image_maxwidth();
3273 var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3274 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3275 this.$image.attr('src', url);
3277 set_image_maxwidth: function() {
3278 this.$image.css('max-width', this.$element.width());
3280 on_file_change: function() {
3281 this.set_image_maxwidth();
3282 this._super.apply(this, arguments);
3284 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3285 this.value = file_base64;
3286 this.binary_value = true;
3287 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3289 on_clear: function() {
3290 this._super.apply(this, arguments);
3291 this.$image.attr('src', '/web/static/src/img/placeholder.png');
3295 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3296 template: "EmptyComponent",
3299 this.selected_value = null;
3303 set_value: function(value) {
3305 this.selected_value = value;
3309 render_list: function() {
3311 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3312 function(x) { return _.str.trim(x); });
3313 shown = _.select(shown, function(x) { return x.length > 0; });
3315 if (shown.length == 0) {
3316 this.to_show = this.field.selection;
3318 this.to_show = _.select(this.field.selection, function(x) {
3319 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3323 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3324 this.$element.html(content);
3326 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3327 var color = colors[this.selected_value];
3329 var elem = this.$element.find("li.oe-arrow-list-selected span");
3330 elem.css("border-color", color);
3331 if (this.check_white(color))
3332 elem.css("color", "white");
3333 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3334 elem.css("border-left-color", "rgba(0,0,0,0)");
3335 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3336 elem.css("border-color", "rgba(0,0,0,0)");
3337 elem.css("border-left-color", color);
3340 check_white: function(color) {
3341 var div = $("<div></div>");
3342 div.css("display", "none");
3343 div.css("color", color);
3344 div.appendTo($("body"));
3345 var ncolor = div.css("color");
3347 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3351 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3352 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3360 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3361 render: function () {
3362 var $root = $('<div class="oe_form_html_view">');
3363 this.render_children(this, $root);
3364 return $root.html();
3366 render_children: function (object, $into) {
3368 fields = this.view.fields_view.fields;
3369 _(object.children).each(function (child) {
3370 if (typeof child === 'string') {
3372 } else if (child.tag === 'field') {
3374 new (self.view.registry.get_object('frame'))(
3375 self.view, {tag: 'ueule', attrs: {}, children: [child] })
3378 var $child = $(document.createElement(child.tag))
3381 self.render_children(child, $child);
3389 * Registry of form widgets, called by :js:`openerp.web.FormView`
3391 openerp.web.form.widgets = new openerp.web.Registry({
3392 'frame' : 'openerp.web.form.WidgetFrame',
3393 'group' : 'openerp.web.form.WidgetGroup',
3394 'notebook' : 'openerp.web.form.WidgetNotebook',
3395 'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3396 'separator' : 'openerp.web.form.WidgetSeparator',
3397 'label' : 'openerp.web.form.WidgetLabel',
3398 'button' : 'openerp.web.form.WidgetButton',
3399 'char' : 'openerp.web.form.FieldChar',
3400 'id' : 'openerp.web.form.FieldID',
3401 'email' : 'openerp.web.form.FieldEmail',
3402 'url' : 'openerp.web.form.FieldUrl',
3403 'text' : 'openerp.web.form.FieldText',
3404 'date' : 'openerp.web.form.FieldDate',
3405 'datetime' : 'openerp.web.form.FieldDatetime',
3406 'selection' : 'openerp.web.form.FieldSelection',
3407 'many2one' : 'openerp.web.form.FieldMany2One',
3408 'many2many' : 'openerp.web.form.FieldMany2Many',
3409 'one2many' : 'openerp.web.form.FieldOne2Many',
3410 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3411 'reference' : 'openerp.web.form.FieldReference',
3412 'boolean' : 'openerp.web.form.FieldBoolean',
3413 'float' : 'openerp.web.form.FieldFloat',
3414 'integer': 'openerp.web.form.FieldFloat',
3415 'float_time': 'openerp.web.form.FieldFloat',
3416 'progressbar': 'openerp.web.form.FieldProgressBar',
3417 'image': 'openerp.web.form.FieldBinaryImage',
3418 'binary': 'openerp.web.form.FieldBinaryFile',
3419 'statusbar': 'openerp.web.form.FieldStatus',
3420 'html': 'openerp.web.form.WidgetHtml'
3426 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: