1 openerp.web.form = function (instance) {
2 var _t = instance.web._t,
3 _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
7 instance.web.form = {};
10 * Interface implemented by the form view or any other object
11 * able to provide the features necessary for the fields to work.
14 * - display_invalid_fields : if true, all fields where is_valid() return true should
15 * be displayed as invalid.
17 * - view_content_has_changed : when the values of the fields have changed. When
18 * this event is triggered all fields should reprocess their modifiers.
20 instance.web.form.FieldManagerMixin = {
22 * Must return the asked field as in fields_get.
24 get_field: function(field_name) {},
26 * Called by the field when the translate button is clicked.
28 open_translate_dialog: function(field) {},
30 * Returns true when the view is in create mode.
32 is_create_mode: function() {},
35 instance.web.views.add('form', 'instance.web.FormView');
36 instance.web.FormView = instance.web.View.extend(_.extend({}, instance.web.form.FieldManagerMixin, {
38 * Indicates that this view is not searchable, and thus that no search
39 * view should be displayed (if there is one active).
43 display_name: _lt('Form'),
46 * @constructs instance.web.FormView
47 * @extends instance.web.View
49 * @param {instance.web.Session} session the current openerp session
50 * @param {instance.web.DataSet} dataset the dataset this view will work with
51 * @param {String} view_id the identifier of the OpenERP view object
52 * @param {Object} options
53 * - resize_textareas : [true|false|max_height]
55 * @property {instance.web.Registry} registry=instance.web.form.widgets widgets registry for this form view instance
57 init: function(parent, dataset, view_id, options) {
59 this.set_default_options(options);
60 this.dataset = dataset;
61 this.model = dataset.model;
62 this.view_id = view_id || false;
63 this.fields_view = {};
65 this.fields_order = [];
67 this.default_focus_field = null;
68 this.default_focus_button = null;
69 this.fields_registry = instance.web.form.widgets;
70 this.tags_registry = instance.web.form.tags;
71 this.has_been_loaded = $.Deferred();
72 this.translatable_fields = [];
73 _.defaults(this.options, {
74 "not_interactible_on_create": false,
75 "initial_mode": "view",
77 this.is_initialized = $.Deferred();
78 this.mutating_mutex = new $.Mutex();
79 this.on_change_mutex = new $.Mutex();
80 this.reload_mutex = new $.Mutex();
81 this.rendering_engine = new instance.web.form.FormRenderingEngineReadonly(this);
82 this.qweb = null; // A QWeb instance will be created if the view is a QWeb template
85 _.each(this.get_widgets(), function(w) {
90 on_loaded: function(data) {
93 throw new Error("No data provided.");
96 throw "Form view does not support multiple calls to on_loaded";
98 this.fields_order = [];
99 this.fields_view = data;
101 this.rendering_engine.set_fields_registry(this.fields_registry);
102 this.rendering_engine.set_tags_registry(this.tags_registry);
103 if (!this.extract_qweb_template(data)) {
104 this.rendering_engine.set_fields_view(data);
105 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
106 this.rendering_engine.render_to($dest);
110 this.$buttons = $(QWeb.render("FormView.buttons", {'widget':self}));
111 if (this.options.$buttons) {
112 this.$buttons.appendTo(this.options.$buttons);
114 this.$element.find('.oe_form_buttons').replaceWith(this.$buttons);
116 this.$buttons.on('click','.oe_form_button_create',this.on_button_create);
117 this.$buttons.on('click','.oe_form_button_edit',this.on_button_edit);
118 this.$buttons.on('click','.oe_form_button_save',this.on_button_save);
119 this.$buttons.on('click','.oe_form_button_cancel',this.on_button_cancel);
121 this.$pager = $(QWeb.render("FormView.pager", {'widget':self}));
122 if (this.options.$pager) {
123 this.$pager.appendTo(this.options.$pager);
125 this.$element.find('.oe_form_pager').replaceWith(this.$pager);
127 this.$pager.on('click','a[data-pager-action]',function() {
128 var action = $(this).data('pager-action');
129 self.on_pager_action(action);
132 this.$sidebar = this.options.$sidebar || this.$element.find('.oe_form_sidebar');
133 if (!this.sidebar && this.options.$sidebar) {
134 this.sidebar = new instance.web.Sidebar(this);
135 this.sidebar.appendTo(this.$sidebar);
136 if(this.fields_view.toolbar) {
137 this.sidebar.add_toolbar(this.fields_view.toolbar);
139 this.sidebar.add_items('other', [
140 { label: _t('Delete'), callback: self.on_button_delete },
141 { label: _t('Duplicate'), callback: self.on_button_duplicate },
142 { label: _t('Set Default'), callback: function (item) { self.open_defaults_dialog(); } },
145 this.on("change:mode", this, this.switch_mode);
146 this.set({mode: this.options.initial_mode});
147 this.has_been_loaded.resolve();
150 extract_qweb_template: function(fvg) {
151 for (var i=0, ii=fvg.arch.children.length; i < ii; i++) {
152 var child = fvg.arch.children[i];
153 if (child.tag === "templates") {
154 this.qweb = new QWeb2.Engine();
155 this.qweb.add_template(instance.web.json_node_to_xml(child));
156 if (!this.qweb.has_template('form')) {
157 throw new Error("No QWeb template found for form view");
165 get_fvg_from_qweb: function(record) {
166 var view = this.qweb.render('form', this.get_qweb_context(record));
167 var fvg = _.clone(this.fields_view);
168 fvg.arch = instance.web.xml_to_json(instance.web.str_to_xml(view).firstChild);
171 get_qweb_context: function(record) {
174 _.each(record, function(value_, name) {
175 var r = _.clone(self.fields_view.fields[name] || {});
176 if ((r.type === 'date' || r.type === 'datetime') && value_) {
177 r.raw_value = instance.web.auto_str_to_date(value_);
179 r.raw_value = value_;
181 r.value = instance.web.format_value(value_, r);
182 new_record[name] = r;
186 new_record : !record.id
189 kill_current_form: function() {
190 _.each(this.getChildren(), function(el) {
194 this.fields_order = [];
195 this.default_focus_field = null;
196 this.default_focus_button = null;
197 this.translatable_fields = [];
198 this.$element.find('.oe_form_container').empty();
200 do_load_state: function(state, warm) {
201 if (state.id && this.datarecord.id != state.id) {
202 if (!this.dataset.get_id_index(state.id)) {
203 this.dataset.ids.push(state.id);
205 this.dataset.select_id(state.id);
211 do_show: function () {
214 this.sidebar.$element.show();
217 this.$buttons.show();
218 this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
223 this.$element.show().css('visibility', 'hidden');
224 this.$element.removeClass('oe_form_dirty');
225 return this.has_been_loaded.pipe(function() {
227 if (self.dataset.index === null) {
228 // null index means we should start a new record
229 result = self.on_button_new();
231 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
232 context : { 'bin_size' : true }
233 }).pipe(self.on_record_loaded);
235 result.pipe(function() {
236 self.$element.css('visibility', 'visible');
241 do_hide: function () {
243 this.sidebar.$element.hide();
246 this.$buttons.hide();
253 on_record_loaded: function(record) {
254 var self = this, set_values = [];
256 this.do_warn("Form", "The record could not be found in the database.", true);
257 return $.Deferred().reject();
259 this.datarecord = record;
262 this.kill_current_form();
263 this.rendering_engine.set_fields_view(this.get_fvg_from_qweb(record));
264 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
265 this.rendering_engine.render_to($dest);
268 _(this.fields).each(function (field, f) {
269 field._dirty_flag = false;
270 var result = field.set_value(self.datarecord[f] || false);
271 set_values.push(result);
273 return $.when.apply(null, set_values).pipe(function() {
275 // New record: Second pass in order to trigger the onchanges
276 // respecting the fields order defined in the view
277 _.each(self.fields_order, function(field_name) {
278 if (record[field_name] !== undefined) {
279 var field = self.fields[field_name];
280 field._dirty_flag = true;
281 self.do_onchange(field);
285 self.on_form_changed();
286 self.is_initialized.resolve();
287 self.do_update_pager(record.id == null);
289 self.sidebar.do_attachement_update(self.dataset, self.datarecord.id);
291 if (self.default_focus_field) {
292 self.default_focus_field.focus();
295 self.do_push_state({id:record.id});
297 self.$element.removeClass('oe_form_dirty');
298 self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
301 on_form_changed: function() {
302 this.trigger("view_content_has_changed");
304 do_notify_change: function() {
305 this.$element.addClass('oe_form_dirty');
306 this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
308 on_pager_action: function(action) {
309 if (this.can_be_discarded()) {
312 this.dataset.index = 0;
315 this.dataset.previous();
321 this.dataset.index = this.dataset.ids.length - 1;
327 do_update_pager: function(hide_index) {
328 var index = hide_index ? '-' : this.dataset.index + 1;
329 this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
330 .find('span.oe_pager_index').html(index).end()
331 .find('span.oe_pager_count').html(this.dataset.ids.length);
333 parse_on_change: function (on_change, widget) {
335 var onchange = _.str.trim(on_change);
336 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
341 var method = call[1];
342 if (!_.str.trim(call[2])) {
343 return {method: method, args: [], context_index: null}
346 var argument_replacement = {
347 'False': function () {return false;},
348 'True': function () {return true;},
349 'None': function () {return null;},
350 'context': function (i) {
352 var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
356 var parent_fields = null, context_index = null;
357 var args = _.map(call[2].split(','), function (a, i) {
358 var field = _.str.trim(a);
360 // literal constant or context
361 if (field in argument_replacement) {
362 return argument_replacement[field](i);
365 if (/^-?\d+(\.\d+)?$/.test(field)) {
366 return Number(field);
369 if (self.fields[field]) {
370 var value_ = self.fields[field].get_value();
371 return value_ == null ? false : value_;
374 var splitted = field.split('.');
375 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
376 if (parent_fields === null) {
377 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
379 var p_val = parent_fields[_.str.trim(splitted[1])];
380 if (p_val !== undefined) {
381 return p_val == null ? false : p_val;
385 var first_char = field[0], last_char = field[field.length-1];
386 if ((first_char === '"' && last_char === '"')
387 || (first_char === "'" && last_char === "'")) {
388 return field.slice(1, -1);
391 throw new Error("Could not get field with name '" + field +
392 "' for onchange '" + onchange + "'");
398 context_index: context_index
401 do_onchange: function(widget, processed) {
403 return this.on_change_mutex.exec(function() {
405 var response = {}, can_process_onchange = $.Deferred();
406 processed = processed || [];
407 processed.push(widget.name);
408 var on_change = widget.node.attrs.on_change;
410 var change_spec = self.parse_on_change(on_change, widget);
413 url: '/web/dataset/onchange',
416 can_process_onchange = self.rpc(ajax, {
417 model: self.dataset.model,
418 method: change_spec.method,
419 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
420 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
421 }).then(function(r) {
422 _.extend(response, r);
425 console.warn("Wrong on_change format", on_change);
428 // fail if onchange failed
429 if (can_process_onchange.isRejected()) {
430 return can_process_onchange;
433 if (widget.field['change_default']) {
434 var fieldname = widget.name, value_;
435 if (response.value && (fieldname in response.value)) {
436 // Use value from onchange if onchange executed
437 value_ = response.value[fieldname];
439 // otherwise get form value for field
440 value_ = self.fields[fieldname].get_value();
442 var condition = fieldname + '=' + value_;
445 can_process_onchange = self.rpc({
446 url: '/web/dataset/call',
450 method: 'get_defaults',
451 args: [self.model, condition]
452 }).then(function (results) {
453 if (!results.length) { return; }
454 if (!response.value) {
457 for(var i=0; i<results.length; ++i) {
458 // [whatever, key, value]
459 var triplet = results[i];
460 response.value[triplet[1]] = triplet[2];
465 if (can_process_onchange.isRejected()) {
466 return can_process_onchange;
469 return self.on_processed_onchange(response, processed);
472 return $.Deferred().reject();
476 on_processed_onchange: function(response, processed) {
478 var result = response;
480 for (var f in result.value) {
481 if (!result.value.hasOwnProperty(f)) { continue; }
482 var field = this.fields[f];
483 // If field is not defined in the view, just ignore it
485 var value_ = result.value[f];
486 if (field.get_value() != value_) {
487 field.set_value(value_);
488 field._dirty_flag = true;
489 if (!_.contains(processed, field.name)) {
490 this.do_onchange(field, processed);
495 this.on_form_changed();
497 if (!_.isEmpty(result.warning)) {
498 instance.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
501 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
506 function edit_domain(node) {
507 var new_domain = result.domain[node.attrs.name];
509 node.attrs.domain = new_domain;
511 _(node.children).each(edit_domain);
513 edit_domain(this.fields_view.arch);
515 return $.Deferred().resolve();
518 return $.Deferred().reject();
521 switch_mode: function() {
523 if(this.get("mode") == "view") {
524 self.$buttons.find('.oe_form_buttons_edit').hide();
525 self.$buttons.find('.oe_form_buttons_view').show();
526 self.$sidebar.show();
527 _.each(this.fields,function(field){
528 field.set({"force_readonly": true});
531 self.$buttons.find('.oe_form_buttons_edit').show();
532 self.$buttons.find('.oe_form_buttons_view').hide();
533 self.$sidebar.hide();
534 _.each(this.fields,function(field){
535 field.set({"force_readonly": false});
539 on_button_save: function() {
541 return this.do_save().then(function(result) {
542 self.set({mode: "view"});
545 on_button_cancel: function(event) {
546 if (this.can_be_discarded()) {
547 this.set({mode: "view"});
551 on_button_new: function() {
553 this.set({mode: "edit"});
554 var def = $.Deferred();
555 $.when(this.has_been_loaded).then(function() {
556 if (self.can_be_discarded()) {
557 var keys = _.keys(self.fields_view.fields);
559 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
563 self.on_record_loaded({}).then(function() {
569 return def.promise();
571 on_button_edit: function() {
572 return this.set({mode: "edit"});
574 on_button_create: function() {
575 this.dataset.index = null;
578 on_button_duplicate: function() {
580 var def = $.Deferred();
581 $.when(this.has_been_loaded).then(function() {
582 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
583 return self.on_created({ result : new_id });
585 return self.set({mode: "edit"});
590 return def.promise();
592 on_button_delete: function() {
594 var def = $.Deferred();
595 $.when(this.has_been_loaded).then(function() {
596 if (self.datarecord.id && confirm(_t("Do you really want to delete this record?"))) {
597 self.dataset.unlink([self.datarecord.id]).then(function() {
598 self.on_pager_action('next');
602 $.async_when().then(function () {
607 return def.promise();
609 can_be_discarded: function() {
610 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
613 * Triggers saving the form's record. Chooses between creating a new
614 * record or saving an existing one depending on whether the record
615 * already has an id property.
617 * @param {Function} success callback on save success
618 * @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)
620 do_save: function(success, prepend_on_create) {
622 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
624 var form_invalid = false,
626 first_invalid_field = null;
627 for (var f in self.fields) {
631 if (!first_invalid_field) {
632 first_invalid_field = f;
634 } else if (f.name !== 'id' && !f.get("readonly") && (!self.datarecord.id || f._dirty_flag)) {
635 // Special case 'id' field, do not save this field
636 // on 'create' : save all non readonly fields
637 // on 'edit' : save non readonly modified fields
638 values[f.name] = f.get_value();
642 self.set({'display_invalid_fields': true});
643 first_invalid_field.focus();
645 return $.Deferred().reject();
647 self.set({'display_invalid_fields': false});
649 if (!self.datarecord.id) {
650 //console.log("FormView(", self, ") : About to create", values);
651 save_deferral = self.dataset.create(values).pipe(function(r) {
652 return self.on_created(r, undefined, prepend_on_create);
654 } else if (_.isEmpty(values) && ! self.force_dirty) {
655 //console.log("FormView(", self, ") : Nothing to save");
656 save_deferral = $.Deferred().resolve({}).promise();
658 self.force_dirty = false;
659 //console.log("FormView(", self, ") : About to save", values);
660 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
661 return self.on_saved(r);
664 return save_deferral.then(success);
668 return $.Deferred().reject();
672 on_invalid: function() {
674 _.each(this.fields, function(f) {
676 msg += "<li>" + f.node.attrs.string + "</li>";
680 this.do_warn("The following fields are invalid :", msg);
682 on_saved: function(r, success) {
684 // should not happen in the server, but may happen for internal purpose
685 return $.Deferred().reject();
687 return $.when(this.reload()).pipe(function () {
688 return $.when(r).then(success); }, null);
692 * Updates the form' dataset to contain the new record:
694 * * Adds the newly created record to the current dataset (at the end by
696 * * Selects that record (sets the dataset's index to point to the new
698 * * Updates the pager and sidebar displays
701 * @param {Function} success callback to execute after having updated the dataset
702 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
704 on_created: function(r, success, prepend_on_create) {
706 // should not happen in the server, but may happen for internal purpose
707 return $.Deferred().reject();
709 this.datarecord.id = r.result;
710 if (!prepend_on_create) {
711 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
712 this.dataset.index = this.dataset.ids.length - 1;
714 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
715 this.dataset.index = 0;
717 this.do_update_pager();
719 this.sidebar.do_attachement_update(this.dataset, this.datarecord.id);
721 //instance.log("The record has been created with id #" + this.datarecord.id);
723 return $.when(_.extend(r, {created: true})).then(success);
726 on_action: function (action) {
727 console.debug('Executing action', action);
731 return this.reload_mutex.exec(function() {
732 if (self.dataset.index == null) {
734 return $.Deferred().reject().promise();
736 if (self.dataset.index == null || self.dataset.index < 0) {
737 return $.when(self.on_button_new());
739 return self.dataset.read_index(_.keys(self.fields_view.fields), {
740 context : { 'bin_size' : true }
741 }).pipe(self.on_record_loaded);
745 get_widgets: function() {
746 return _.filter(this.getChildren(), function(obj) {
747 return obj instanceof instance.web.form.FormWidget;
750 get_fields_values: function(blacklist) {
751 blacklist = blacklist || [];
753 var ids = this.get_selected_ids();
754 values["id"] = ids.length > 0 ? ids[0] : false;
755 _.each(this.fields, function(value_, key) {
756 if (_.include(blacklist, key))
758 var val = value_.get_value();
763 get_selected_ids: function() {
764 var id = this.dataset.ids[this.dataset.index];
765 return id ? [id] : [];
767 recursive_save: function() {
769 return $.when(this.do_save()).pipe(function(res) {
770 if (self.dataset.parent_view)
771 return self.dataset.parent_view.recursive_save();
774 is_dirty: function() {
775 return _.any(this.fields, function (value_) {
776 return value_._dirty_flag;
779 is_interactible_record: function() {
780 var id = this.datarecord.id;
782 if (this.options.not_interactible_on_create)
784 } else if (typeof(id) === "string") {
785 if(instance.web.BufferedDataSet.virtual_id_regex.test(id))
790 sidebar_context: function () {
791 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
793 open_defaults_dialog: function () {
795 var fields = _.chain(this.fields)
796 .map(function (field, name) {
797 var value = field.get_value();
798 // ignore fields which are empty, invisible, readonly, o2m
801 || field.get('invisible')
802 || field.get("readonly")
803 || field.field.type === 'one2many'
804 || field.field.type === 'many2many') {
807 var displayed = value;
808 switch (field.field.type) {
810 displayed = _(field.values).find(function (option) {
811 return option[0] === value;
818 string: field.node.attrs.string || field.field.string,
820 displayed: displayed,
821 // convert undefined to false
822 change_default: !!field.field.change_default
826 .sortBy(function (field) { return field.string; })
828 var conditions = _.chain(fields)
829 .filter(function (field) { return field.change_default; })
832 var d = new instance.web.Dialog(this, {
833 title: _t("Set Default"),
836 conditions: conditions
839 {text: _t("Close"), click: function () { d.close(); }},
840 {text: _t("Save default"), click: function () {
841 var $defaults = d.$element.find('#formview_default_fields');
842 var field_to_set = $defaults.val();
844 $defaults.parent().addClass('oe_form_invalid');
847 var condition = d.$element.find('#formview_default_conditions').val(),
848 all_users = d.$element.find('#formview_default_all').is(':checked');
849 new instance.web.DataSet(self, 'ir.values').call(
853 self.fields[field_to_set].get_value(),
857 ]).then(function () { d.close(); });
861 d.template = 'FormView.set_default';
864 register_field: function(field, name) {
865 this.fields[name] = field;
866 this.fields_order.push(name);
867 if (this.get_field(name).translate) {
868 this.translatable_fields.push(field);
870 field.on('changed_value', this, function() {
871 field._dirty_flag = true;
872 if (field.is_syntax_valid()) {
873 this.do_onchange(field);
874 this.on_form_changed(true);
875 this.do_notify_change();
879 get_field: function(field_name) {
880 return this.fields_view.fields[field_name];
882 is_create_mode: function() {
883 return !this.datarecord.id;
888 * Interface to be implemented by rendering engines for the form view.
890 instance.web.form.FormRenderingEngineInterface = instance.web.Class.extend({
891 set_fields_view: function(fields_view) {},
892 set_fields_registry: function(fields_registry) {},
893 render_to: function($element) {},
897 * Default rendering engine for the form view.
899 * It is necessary to set the view using set_view() before usage.
901 instance.web.form.FormRenderingEngine = instance.web.form.FormRenderingEngineInterface.extend({
902 init: function(view) {
905 set_fields_view: function(fvg) {
908 set_tags_registry: function(tags_registry) {
909 this.tags_registry = tags_registry;
911 set_fields_registry: function(fields_registry) {
912 this.fields_registry = fields_registry;
914 render_to: function($target) {
916 this.$target = $target;
918 // TODO: I know this will save the world and all the kitten for a moment,
919 // but one day, we will have to get rid of xml2json
920 var xml = instance.web.json_node_to_xml(this.fvg.arch);
921 this.$form = $('<div class="oe_form">' + xml + '</div>');
922 if (this.fvg.arch.attrs && this.fvg.arch.attrs['layout'] !== 'manual') {
923 this.$form.attr('layout', 'auto');
926 this.fields_to_init = [];
927 this.tags_to_init = [];
929 this.process(this.$form);
931 this.$form.appendTo(this.$target);
933 _.each(this.fields_to_init, function($elem) {
934 var name = $elem.attr("name");
935 if (!self.fvg.fields[name]) {
936 throw new Error("Field '" + name + "' specified in view could not be found.");
938 var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
940 throw new Error("Widget type '"+ key + "' is not implemented");
942 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
943 var $label = self.labels[$elem.attr("name")];
945 w.set_input_id($label.attr("for"));
948 self.view.register_field(w, $elem.attr("name"));
951 _.each(this.tags_to_init, function($elem) {
952 var tag_name = $elem[0].tagName.toLowerCase();
953 var obj = self.tags_registry.get_object(tag_name);
954 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
957 // TODO: return a deferred
959 render_element: function(template, layout/* dictionaries */) {
960 var dicts = [].slice.call(arguments).slice(2);
961 dicts.unshift({ 'layout' : layout });
962 var dict = _.extend.apply(_, dicts);
963 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
964 var alt_template = template + '.' + layout;
965 template = QWeb.has_template(alt_template) ? alt_template : template;
966 return $(QWeb.render(template, dict));
968 alter_field: function(field) {
970 toggle_layout_debugging: function() {
971 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
972 this.$target.find('[title]').removeAttr('title');
973 this.$target.find('.oe_form_group_cell').each(function() {
974 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
975 $(this).attr('title', text);
978 this.$target.toggleClass('oe_layout_debugging');
980 process: function($tag, layout) {
982 layout = $tag.attr('layout') || layout || 'auto';
983 $tag.removeAttr('layout');
984 var tagname = $tag[0].nodeName.toLowerCase();
985 if (this.tags_registry.contains(tagname)) {
986 this.tags_to_init.push($tag);
989 var fn = self['process_' + tagname];
991 var args = [].slice.call(arguments);
994 return fn.apply(self, args);
996 // generic tag handling, just process children
997 $tag.children().each(function() {
998 self.process($(this), layout);
1000 self.handle_common_properties($tag, $tag);
1001 $tag.removeAttr("modifiers");
1005 process_sheet: function($sheet, layout) {
1006 var $new_sheet = this.render_element('FormRenderingSheet', layout, $sheet.getAttributes());
1007 this.handle_common_properties($new_sheet, $sheet);
1008 var $dst = (layout === 'auto') ? $new_sheet.find('group:first') : $new_sheet.find('.oe_form_sheet');
1009 $sheet.children().appendTo($dst);
1010 $sheet.before($new_sheet).remove();
1011 this.process($new_sheet, layout);
1013 process_form: function($form, layout) {
1014 var $new_form = this.render_element('FormRenderingForm', layout, $form.getAttributes());
1015 this.handle_common_properties($new_form, $form);
1016 var $dst = (layout === 'auto') ? $new_form.find('group:first') : $new_form;
1017 $form.children().appendTo($dst);
1018 if ($form[0] === this.$form[0]) {
1019 // If root element, replace it
1020 this.$form = $new_form;
1022 $form.before($new_form).remove();
1024 this.process($new_form, layout);
1026 preprocess_field: function($field) {
1028 var name = $field.attr('name'),
1029 field_colspan = parseInt($field.attr('colspan'), 10),
1030 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1032 if ($field.attr('nolabel') === '1')
1034 $field.attr('nolabel', '1');
1036 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1037 $(el).parents().each(function(unused, tag) {
1038 var name = tag.tagName.toLowerCase();
1039 if (name === "field" || name in self.tags_registry.map)
1046 $label = $('<label/>').attr({
1048 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1049 "string": $field.attr('string'),
1050 "help": $field.attr('help'),
1052 $label.insertBefore($field);
1053 if (field_colspan > 1) {
1054 $field.attr('colspan', field_colspan - 1);
1058 process_field: function($field, layout) {
1059 var $label = this.preprocess_field($field);
1061 this.process($label, layout);
1062 this.fields_to_init.push($field);
1065 process_group: function($group, layout) {
1067 if ($group.parent().is('.oe_form_group_cell')) {
1068 $group.parent().addClass('oe_form_group_nested');
1070 $group.children('field').each(function() {
1071 self.preprocess_field($(this));
1073 var $new_group = this.render_element('FormRenderingGroup', layout, $group.getAttributes()),
1075 if ($new_group.is('table')) {
1076 $table = $new_group;
1078 $table = $new_group.find('table:first');
1080 $table.addClass('oe_form_group');
1082 cols = parseInt($group.attr('col') || 4, 10),
1086 $group.children().each(function(a,b,c) {
1087 var $child = $(this);
1088 var colspan = parseInt($child.attr('colspan') || 1, 10);
1089 var tagName = $child[0].tagName.toLowerCase();
1090 var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1091 var newline = tagName === 'newline';
1092 if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1093 $tr.addClass('oe_form_group_row_incomplete');
1095 $tr.addClass('oe_form_group_row_newline');
1102 if (!$tr || row_cols < colspan) {
1103 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1106 row_cols -= colspan;
1108 // invisibility transfer
1109 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1110 var invisible = field_modifiers.invisible;
1111 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1113 $tr.append($td.append($child));
1114 children.push($child[0]);
1116 if (row_cols && $td) {
1117 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1119 $group.before($new_group).remove();
1121 // Now compute width of cells
1122 $table.find('> tbody > tr').each(function() {
1123 var to_compute = [],
1126 $(this).children().each(function() {
1128 $child = $td.children(':first');
1129 switch ($child[0].tagName.toLowerCase()) {
1131 if ($child.attr('orientation') === 'vertical') {
1132 $td.addClass('oe_vertical_separator').attr('width', '1');
1138 if ($child.attr('for')) {
1139 $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1145 var width = _.str.trim($child.attr('width') || ''),
1146 iwidth = parseInt(width, 10);
1148 if (width.substr(-1) === '%') {
1150 width = iwidth + '%';
1153 $td.css('min-width', width + 'px');
1155 $td.attr('width', width);
1156 $child.removeAttr('width');
1159 to_compute.push($td);
1164 var unit = Math.floor(total / row_cols);
1165 if (!$(this).is('.oe_form_group_row_incomplete')) {
1166 _.each(to_compute, function($td, i) {
1167 var width = parseInt($td.attr('colspan'), 10) * unit;
1168 $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
1173 _.each(children, function(el) {
1174 self.process($(el));
1176 this.handle_common_properties($new_group, $group);
1179 process_notebook: function($notebook, layout) {
1182 $notebook.find('> page').each(function() {
1183 var $page = $(this);
1184 var page_attrs = $page.getAttributes();
1185 page_attrs.id = _.uniqueId('notebook_page_');
1186 pages.push(page_attrs);
1187 var $new_page = self.render_element('FormRenderingNotebookPage', layout, page_attrs);
1188 var $dst = (layout === 'auto') ? $new_page.find('group:first') : $new_page;
1189 $page.children().appendTo($dst);
1190 $page.before($new_page).remove();
1191 self.handle_common_properties($new_page, $page);
1193 var $new_notebook = this.render_element('FormRenderingNotebook', layout, { pages : pages });
1194 $notebook.children().appendTo($new_notebook);
1195 $notebook.before($new_notebook).remove();
1196 $new_notebook.children().each(function() {
1197 self.process($(this));
1199 $new_notebook.tabs();
1200 this.handle_common_properties($new_notebook, $notebook);
1201 return $new_notebook;
1203 process_separator: function($separator, layout) {
1204 var $new_separator = this.render_element('FormRenderingSeparator', layout, $separator.getAttributes());
1205 $separator.before($new_separator).remove();
1206 this.handle_common_properties($new_separator, $separator);
1207 return $new_separator;
1209 process_label: function($label, layout) {
1210 var name = $label.attr("for"),
1211 field_orm = this.fvg.fields[name];
1213 string: $label.attr('string') || (field_orm || {}).string || '',
1214 help: $label.attr('help') || (field_orm || {}).help || '',
1215 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1217 var align = parseFloat(dict.align);
1218 if (isNaN(align) || align === 1) {
1220 } else if (align === 0) {
1226 var $new_label = this.render_element('FormRenderingLabel', layout, dict);
1227 $label.before($new_label).remove();
1228 this.handle_common_properties($new_label, $label);
1230 this.labels[name] = $new_label;
1234 handle_common_properties: function($new_element, $node) {
1235 var str_modifiers = $node.attr("modifiers") || "{}"
1236 var modifiers = JSON.parse(str_modifiers);
1237 if (modifiers.invisible !== undefined)
1238 new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1239 $new_element.addClass($node.attr("class") || "");
1240 $new_element.attr('style', $node.attr('style'));
1244 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1245 alter_field: function(field) {
1246 field.set({"force_readonly": true});
1250 instance.web.form.FormDialog = instance.web.Dialog.extend({
1251 init: function(parent, options, view_id, dataset) {
1252 this._super(parent, options);
1253 this.dataset = dataset;
1254 this.view_id = view_id;
1259 this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1262 this.form.appendTo(this.$element);
1263 this.form.on_created.add_last(this.on_form_dialog_saved);
1264 this.form.on_saved.add_last(this.on_form_dialog_saved);
1267 select_id: function(id) {
1268 if (this.form.dataset.select_id(id)) {
1269 return this.form.do_show();
1271 this.do_warn("Could not find id in dataset");
1272 return $.Deferred().reject();
1275 on_form_dialog_saved: function(r) {
1280 instance.web.form.compute_domain = function(expr, fields) {
1282 for (var i = expr.length - 1; i >= 0; i--) {
1284 if (ex.length == 1) {
1285 var top = stack.pop();
1288 stack.push(stack.pop() || top);
1291 stack.push(stack.pop() && top);
1297 throw new Error(_.str.sprintf(
1298 _t("Unknown operator %s in domain %s"),
1299 ex, JSON.stringify(expr)));
1303 var field = fields[ex[0]];
1305 throw new Error(_.str.sprintf(
1306 _t("Unknown field %s in domain %s"),
1307 ex[0], JSON.stringify(expr)));
1309 var field_value = field.get_value ? field.get_value() : field.value;
1313 switch (op.toLowerCase()) {
1316 stack.push(field_value == val);
1320 stack.push(field_value != val);
1323 stack.push(field_value < val);
1326 stack.push(field_value > val);
1329 stack.push(field_value <= val);
1332 stack.push(field_value >= val);
1335 if (!_.isArray(val)) val = [val];
1336 stack.push(_(val).contains(field_value));
1339 if (!_.isArray(val)) val = [val];
1340 stack.push(!_(val).contains(field_value));
1344 _t("Unsupported operator %s in domain %s"),
1345 op, JSON.stringify(expr));
1348 return _.all(stack, _.identity);
1352 * Must be applied over an class already possessing the PropertiesMixin.
1354 * Apply the result of the "invisible" domain to this.$element.
1356 instance.web.form.InvisibilityChangerMixin = {
1357 init: function(field_manager, invisible_domain) {
1358 this._ic_field_manager = field_manager
1359 this._ic_invisible_modifier = invisible_domain;
1360 this._ic_field_manager.on("view_content_has_changed", this, function() {
1361 var result = this._ic_invisible_modifier === undefined ? false :
1362 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1363 this.set({"invisible": result});
1365 this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1366 var check = function() {
1367 if (this.get("invisible") || this.get('force_invisible')) {
1368 this.set({"effective_invisible": true});
1370 this.set({"effective_invisible": false});
1373 this.on('change:invisible', this, check);
1374 this.on('change:force_invisible', this, check);
1375 _.bind(check, this)();
1378 var check_visibility = function() {
1379 if (this.get("effective_invisible")) {
1380 this.$element.hide();
1382 this.$element.show();
1385 this.on("change:effective_invisible", this, check_visibility);
1386 _.bind(check_visibility, this)();
1390 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1391 init: function(parent, field_manager, invisible_domain, $element) {
1392 this.setParent(parent);
1393 instance.web.PropertiesMixin.init.call(this);
1394 instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1395 this.$element = $element;
1400 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1402 * @constructs instance.web.form.FormWidget
1403 * @extends instance.web.Widget
1408 init: function(view, node) {
1412 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1413 instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1415 this.view.on("view_content_has_changed", this, this.process_modifiers);
1417 renderElement: function() {
1419 this.$element.addClass(this.node.attrs["class"] || "");
1421 destroy: function() {
1423 this._super.apply(this, arguments);
1425 process_modifiers: function() {
1426 var compute_domain = instance.web.form.compute_domain;
1428 for (var a in this.modifiers) {
1429 if (!_.include(["invisible"], a)) {
1430 var val = compute_domain(this.modifiers[a], this.view.fields);
1436 do_attach_tooltip: function(widget, trigger, options) {
1437 widget = widget || this;
1438 trigger = trigger || this.$element;
1439 options = _.extend({
1444 var template = widget.template + '.tooltip';
1445 if (!QWeb.has_template(template)) {
1446 template = 'WidgetLabel.tooltip';
1448 return QWeb.render(template, {
1449 debug: instance.connection.debug,
1452 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1457 $(trigger).tipsy(options);
1459 _build_view_fields_values: function(blacklist) {
1460 var a_dataset = this.view.dataset;
1461 var fields_values = this.view.get_fields_values(blacklist);
1462 var active_id = a_dataset.ids[a_dataset.index];
1463 _.extend(fields_values, {
1464 active_id: active_id || false,
1465 active_ids: active_id ? [active_id] : [],
1466 active_model: a_dataset.model,
1469 if (a_dataset.parent_view) {
1470 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1472 return fields_values;
1474 _build_eval_context: function(blacklist) {
1475 var a_dataset = this.view.dataset;
1476 return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1479 * Builds a new context usable for operations related to fields by merging
1480 * the fields'context with the action's context.
1482 build_context: function(blacklist) {
1483 // only use the model's context if there is not context on the node
1484 var v_context = this.node.attrs.context;
1486 v_context = (this.field || {}).context || {};
1489 if (v_context.__ref || true) { //TODO: remove true
1490 var fields_values = this._build_eval_context(blacklist);
1491 v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1495 build_domain: function() {
1496 var f_domain = this.field.domain || [];
1497 var n_domain = this.node.attrs.domain || null;
1498 // if there is a domain on the node, overrides the model's domain
1499 var final_domain = n_domain !== null ? n_domain : f_domain;
1500 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1501 var fields_values = this._build_eval_context();
1502 final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1504 return final_domain;
1508 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1509 template: 'WidgetButton',
1510 init: function(view, node) {
1511 this._super(view, node);
1512 this.force_disabled = false;
1513 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1514 if (this.node.attrs.default_focus == '1') {
1515 // TODO fme: provide enter key binding to widgets
1516 this.view.default_focus_button = this;
1518 this.view.on('view_content_has_changed', this, this.check_disable);
1521 this._super.apply(this, arguments);
1522 this.$element.click(this.on_click);
1523 if (this.node.attrs.help || instance.connection.debug) {
1524 this.do_attach_tooltip();
1527 on_click: function() {
1529 this.force_disabled = true;
1530 this.check_disable();
1531 this.execute_action().always(function() {
1532 self.force_disabled = false;
1533 self.check_disable();
1536 execute_action: function() {
1538 var exec_action = function() {
1539 if (self.node.attrs.confirm) {
1540 var def = $.Deferred();
1541 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1542 title: _t('Confirm'),
1545 {text: _t("Cancel"), click: function() {
1547 $(this).dialog("close");
1550 {text: _t("Ok"), click: function() {
1551 self.on_confirmed().then(function() {
1554 $(this).dialog("close");
1559 return def.promise();
1561 return self.on_confirmed();
1564 if (!this.node.attrs.special) {
1565 this.view.force_dirty = true;
1566 return this.view.recursive_save().pipe(exec_action);
1568 return exec_action();
1571 on_confirmed: function() {
1574 var context = this.node.attrs.context;
1575 if (context && context.__ref) {
1576 context = new instance.web.CompoundContext(context);
1577 context.set_eval_context(this._build_eval_context());
1580 return this.view.do_execute_action(
1581 _.extend({}, this.node.attrs, {context: context}),
1582 this.view.dataset, this.view.datarecord.id, function () {
1586 check_disable: function() {
1587 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1588 this.$element.prop('disabled', disabled);
1589 this.$element.css('color', disabled ? 'grey' : '');
1594 * Interface to be implemented by fields.
1597 * - readonly: boolean. If set to true the field should appear in readonly mode.
1598 * - force_readonly: boolean, When it is true, the field should always appear
1599 * in read only mode, no matter what the value of the "readonly" property can be.
1601 * - changed_value: triggered to inform the view to check on_changes
1604 instance.web.form.FieldMixin = {
1606 * Constructor takes 2 arguments:
1607 * - field_manager: Implements FieldManagerMixin
1608 * - node: the "<field>" node in json form
1610 init: function(field_manager, node) {},
1612 * Called by the form view to indicate the value of the field.
1614 * set_value() may return an object that can be passed to $.when() that represents the moment when
1615 * the field has finished all operations necessary before the user can effectively use the widget.
1617 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1618 * regardless of any asynchronous operation currently running and the status of any promise that a
1619 * previous call to set_value() could have returned.
1621 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1622 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1623 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1624 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1625 * no information is ever given to know which format is used.
1627 set_value: function(value_) {},
1629 * Get the current value of the widget.
1631 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1632 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1633 * For example if the field is marqued as "required", a call to get_value() can return false.
1635 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1636 * return a defaut value according to the type of field.
1638 * This method is always assumed to perform synchronously, it can not return a promise.
1640 * If there was no user interaction to modify the value of the field, it is always assumed that
1641 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1642 * altough the syntax can be different. This can be the case for type of fields that have a different
1643 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1645 get_value: function() {},
1647 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1650 set_input_id: function(id) {},
1652 * Returns true if is_syntax_valid() returns true and the value is semantically
1653 * valid too according to the semantic restrictions applied to the field.
1655 is_valid: function() {},
1657 * Returns true if the field holds a value which is syntaxically correct, ignoring
1658 * the potential semantic restrictions applied to the field.
1660 is_syntax_valid: function() {},
1662 * Must set the focus on the field.
1664 focus: function() {},
1668 * Abstract class for classes implementing FieldMixin.
1671 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1672 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1673 * - value: useful property to hold the value of the field. By default, set_value() and get_value()
1674 * set and retrieve the value property. Changing the value property also triggers automatically
1675 * a 'changed_value' event that inform the view to trigger on_changes.
1678 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1680 * @constructs instance.web.form.AbstractField
1681 * @extends instance.web.form.FormWidget
1683 * @param field_manager
1686 init: function(field_manager, node) {
1687 this._super(field_manager, node);
1688 this.field_manager = field_manager;
1689 this.name = this.node.attrs.name;
1690 this.set({'value': false});
1691 this.field = this.field_manager.get_field(this.name);
1692 this.set({required: this.modifiers['required'] === true});
1694 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1696 this.set({"readonly": this.modifiers['readonly'] === true});
1697 var test_effective_readonly = function() {
1698 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1700 this.on("change:readonly", this, test_effective_readonly);
1701 this.on("change:force_readonly", this, test_effective_readonly);
1702 _.bind(test_effective_readonly, this)();
1704 this.on("change:value", this, function() {
1705 if (! this._inhibit_on_change)
1706 this.trigger('changed_value');
1707 this._check_css_flags();
1710 renderElement: function() {
1713 if (this.field.translate) {
1714 this.$element.addClass('oe_form_field_translatable');
1715 this.$element.find('.oe_field_translate').click(_.bind(function() {
1716 this.field_manager.open_translate_dialog(this);
1719 this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1720 if (instance.connection.debug) {
1721 this.do_attach_tooltip(this, this.$label[0] || this.$element);
1722 this.$label.off('dblclick').on('dblclick', function() {
1723 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1725 console.log("window.w =", window.w);
1728 if (!this.disable_utility_classes) {
1729 this.off("change:required", this, this._set_required);
1730 this.on("change:required", this, this._set_required);
1731 this._set_required();
1735 * Private. Do not use.
1737 _set_required: function() {
1738 this.$element.toggleClass('oe_form_required', this.get("required"));
1740 set_value: function(value_) {
1741 this._inhibit_on_change = true;
1742 this.set({'value': value_});
1743 this._inhibit_on_change = false;
1745 get_value: function() {
1746 return this.get('value');
1748 is_valid: function() {
1749 return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1751 is_syntax_valid: function() {
1755 * Method useful to implement to ease validity testing. Must return true if the current
1756 * value is similar to false in OpenERP.
1758 is_false: function() {
1759 return this.get('value') === false;
1761 _check_css_flags: function(show_invalid) {
1762 if (this.field.translate) {
1763 this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1765 if (!this.disable_utility_classes) {
1766 if (this.field_manager.get('display_invalid_fields')) {
1767 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1774 * Utility method to focus an element, but only after a small amount of time.
1776 delay_focus: function($elem) {
1777 setTimeout(function() {
1782 * Utility method to get the widget options defined in the field xml description.
1784 get_definition_options: function() {
1785 if (!this.definition_options) {
1786 var str = this.node.attrs.options || '{}';
1787 this.definition_options = JSON.parse(str);
1789 return this.definition_options;
1791 set_input_id: function(id) {
1792 this.id_for_label = id;
1797 * A mixin to apply on any field that has to completely re-render when its readonly state
1800 instance.web.form.ReinitializeFieldMixin = {
1802 * Default implementation of start(), use it or call explicitly initialize_field().
1806 this.initialize_field();
1808 initialize_field: function() {
1809 this.on("change:effective_readonly", this, function() {
1810 this.destroy_content();
1811 this.renderElement();
1812 this.initialize_content();
1813 this.render_value();
1815 this.initialize_content();
1816 this.render_value();
1819 * Called to destroy anything that could have been created previously, called before a
1820 * re-initialization.
1822 destroy_content: function() {},
1824 * Called to initialize the content.
1826 initialize_content: function() {},
1828 * Called to render the value. Should also be explicitly called at the end of a set_value().
1830 render_value: function() {},
1833 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1834 template: 'FieldChar',
1835 init: function (field_manager, node) {
1836 this._super(field_manager, node);
1837 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1839 initialize_content: function() {
1841 this.$element.find('input').change(function() {
1842 self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1845 set_value: function(value_) {
1846 this._super(value_);
1847 this.render_value();
1849 render_value: function() {
1850 var show_value = instance.web.format_value(this.get('value'), this, '');
1851 if (!this.get("effective_readonly")) {
1852 this.$element.find('input').val(show_value);
1854 if (this.password) {
1855 show_value = new Array(show_value.length + 1).join('*');
1857 this.$element.text(show_value);
1860 is_syntax_valid: function() {
1861 if (!this.get("effective_readonly")) {
1863 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1871 is_false: function() {
1872 return this.get('value') === '';
1875 this.delay_focus(this.$element.find('input:first'));
1879 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1883 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1884 template: 'FieldEmail',
1885 initialize_content: function() {
1887 this.$element.find('button').click(this.on_button_clicked);
1889 render_value: function() {
1890 if (!this.get("effective_readonly")) {
1893 this.$element.find('a')
1894 .attr('href', 'mailto:' + this.get('value'))
1895 .text(this.get('value'));
1898 on_button_clicked: function() {
1899 if (!this.get('value') || !this.is_syntax_valid()) {
1900 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1902 location.href = 'mailto:' + this.get('value');
1907 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1908 template: 'FieldUrl',
1909 initialize_content: function() {
1911 this.$element.find('button').click(this.on_button_clicked);
1913 render_value: function() {
1914 if (!this.get("effective_readonly")) {
1917 var tmp = this.get('value');
1918 var s = /(\w+):(.+)/.exec(tmp);
1920 tmp = "http://" + this.get('value');
1922 this.$element.find('a').attr('href', tmp).text(tmp);
1925 on_button_clicked: function() {
1926 if (!this.get('value')) {
1927 this.do_warn("Resource error", "This resource is empty");
1929 var url = $.trim(this.get('value'));
1930 if(/^www\./i.test(url))
1931 url = 'http://'+url;
1937 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1938 is_field_number: true,
1939 init: function (field_manager, node) {
1940 this._super(field_manager, node);
1941 this.set({'value': 0});
1942 if (this.node.attrs.digits) {
1943 this.digits = py.eval(node.attrs.digits);
1945 this.digits = this.field.digits;
1948 set_value: function(value_) {
1949 if (value_ === false || value_ === undefined) {
1950 // As in GTK client, floats default to 0
1953 this._super.apply(this, [value_]);
1957 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
1958 template: "web.datetimepicker",
1959 jqueryui_object: 'datetimepicker',
1960 type_of_date: "datetime",
1961 init: function(parent) {
1962 this._super(parent);
1963 this.name = parent.name;
1967 this.$input = this.$element.find('input.oe_datepicker_master');
1968 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1969 this.$input.change(this.on_change);
1971 onSelect: this.on_picker_select,
1975 showButtonPanel: true
1977 this.$element.find('img.oe_datepicker_trigger').click(function() {
1978 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1979 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
1980 self.$input_picker.show();
1981 self.picker('show');
1982 self.$input_picker.hide();
1985 this.set_readonly(false);
1986 this.set({'value': false});
1988 picker: function() {
1989 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1991 on_picker_select: function(text, instance_) {
1992 var date = this.picker('getDate');
1993 this.$input.val(date ? this.format_client(date) : '').change();
1995 set_value: function(value_) {
1996 this.set({'value': value_});
1997 this.$input.val(value_ ? this.format_client(value_) : '');
1999 get_value: function() {
2000 return this.get('value');
2002 set_value_from_ui_: function() {
2003 var value_ = this.$input.val() || false;
2004 this.set({'value': this.parse_client(value_)});
2006 set_readonly: function(readonly) {
2007 this.readonly = readonly;
2008 this.$input.prop('readonly', this.readonly);
2009 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2011 is_valid_: function() {
2012 var value_ = this.$input.val();
2013 if (value_ === "") {
2017 this.parse_client(value_);
2024 parse_client: function(v) {
2025 return instance.web.parse_value(v, {"widget": this.type_of_date});
2027 format_client: function(v) {
2028 return instance.web.format_value(v, {"widget": this.type_of_date});
2030 on_change: function() {
2031 if (this.is_valid_()) {
2032 this.set_value_from_ui_();
2037 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2038 jqueryui_object: 'datepicker',
2039 type_of_date: "date"
2042 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2043 template: "EmptyComponent",
2044 build_widget: function() {
2045 return new instance.web.DateTimeWidget(this);
2047 destroy_content: function() {
2048 if (this.datewidget) {
2049 this.datewidget.destroy();
2050 this.datewidget = undefined;
2053 initialize_content: function() {
2054 if (!this.get("effective_readonly")) {
2055 this.datewidget = this.build_widget();
2056 this.datewidget.on_change.add_last(_.bind(function() {
2057 this.set({'value': this.datewidget.get_value()});
2059 this.datewidget.appendTo(this.$element);
2062 set_value: function(value_) {
2063 this._super(value_);
2064 this.render_value();
2066 render_value: function() {
2067 if (!this.get("effective_readonly")) {
2068 this.datewidget.set_value(this.get('value'));
2070 this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2073 is_syntax_valid: function() {
2074 if (!this.get("effective_readonly")) {
2075 return this.datewidget.is_valid_();
2079 is_false: function() {
2080 return this.get('value') === '';
2083 if (this.datewidget && this.datewidget.$input)
2084 this.delay_focus(this.datewidget.$input);
2088 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2089 build_widget: function() {
2090 return new instance.web.DateWidget(this);
2094 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2095 template: 'FieldText',
2096 initialize_content: function() {
2097 this.$textarea = this.$element.find('textarea');
2098 if (!this.get("effective_readonly")) {
2099 this.$textarea.change(_.bind(function() {
2100 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2103 this.$textarea.attr('disabled', 'disabled');
2106 set_value: function(value_) {
2107 this._super.apply(this, arguments);
2108 this.render_value();
2110 render_value: function() {
2111 var show_value = instance.web.format_value(this.get('value'), this, '');
2112 this.$textarea.val(show_value);
2113 if (show_value && this.view.options.resize_textareas) {
2114 this.do_resize(this.view.options.resize_textareas);
2117 is_syntax_valid: function() {
2118 if (!this.get("effective_readonly")) {
2120 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2128 is_false: function() {
2129 return this.get('value') === '';
2131 focus: function($element) {
2132 this.delay_focus(this.$textarea);
2134 do_resize: function(max_height) {
2135 max_height = parseInt(max_height, 10);
2136 var $input = this.$textarea,
2137 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2139 $div.text($input.val());
2140 _.each('font-family,font-size,white-space'.split(','), function(style) {
2141 $div.css(style, $input.css(style));
2143 $div.appendTo($('body'));
2144 new_height = $div.height();
2145 if (new_height < 90) {
2148 if (!isNaN(max_height) && new_height > max_height) {
2149 new_height = max_height;
2152 $input.height(new_height);
2156 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2157 template: 'FieldBoolean',
2159 this._super.apply(this, arguments);
2160 this.$checkbox = $("input", this.$element);
2161 this.$element.click(_.bind(function() {
2162 this.set({'value': this.$checkbox.is(':checked')});
2164 var check_readonly = function() {
2165 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2167 this.on("change:effective_readonly", this, check_readonly);
2168 _.bind(check_readonly, this)();
2170 set_value: function(value_) {
2171 this._super.apply(this, arguments);
2172 this.$checkbox[0].checked = value_;
2175 this.delay_focus(this.$checkbox);
2179 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2180 template: 'FieldProgressBar',
2182 this._super.apply(this, arguments);
2183 this.$element.progressbar({
2184 value: this.get('value'),
2185 disabled: this.get("effective_readonly")
2188 set_value: function(value_) {
2189 this._super.apply(this, arguments);
2190 var show_value = Number(value_);
2191 if (isNaN(show_value)) {
2194 var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2195 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2199 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2200 // to replace view editor
2203 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2204 template: 'FieldSelection',
2205 init: function(field_manager, node) {
2207 this._super(field_manager, node);
2208 this.values = _.clone(this.field.selection);
2209 _.each(this.values, function(v, i) {
2210 if (v[0] === false && v[1] === '') {
2211 self.values.splice(i, 1);
2214 this.values.unshift([false, '']);
2216 initialize_content: function() {
2217 // Flag indicating whether we're in an event chain containing a change
2218 // event on the select, in order to know what to do on keyup[RETURN]:
2219 // * If the user presses [RETURN] as part of changing the value of a
2220 // selection, we should just let the value change and not let the
2221 // event broadcast further (e.g. to validating the current state of
2222 // the form in editable list view, which would lead to saving the
2223 // current row or switching to the next one)
2224 // * If the user presses [RETURN] with a select closed (side-effect:
2225 // also if the user opened the select and pressed [RETURN] without
2226 // changing the selected value), takes the action as validating the
2228 var ischanging = false;
2229 this.$element.find('select')
2230 .change(_.bind(function() {
2231 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2233 .change(function () { ischanging = true; })
2234 .click(function () { ischanging = false; })
2235 .keyup(function (e) {
2236 if (e.which !== 13 || !ischanging) { return; }
2237 e.stopPropagation();
2241 set_value: function(value_) {
2242 value_ = value_ === null ? false : value_;
2243 value_ = value_ instanceof Array ? value_[0] : value_;
2244 this._super(value_);
2245 this.render_value();
2247 render_value: function() {
2248 if (!this.get("effective_readonly")) {
2250 for (var i = 0, ii = this.values.length; i < ii; i++) {
2251 if (this.values[i][0] === this.get('value')) index = i;
2253 this.$element.find('select')[0].selectedIndex = index;
2256 var option = _(this.values)
2257 .detect(function (record) { return record[0] === self.get('value'); });
2258 this.$element.text(option ? option[1] : this.values[0][1]);
2261 is_syntax_valid: function() {
2262 if (this.get("effective_readonly")) {
2265 var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2269 this.delay_focus(this.$element.find('select:first'));
2273 // jquery autocomplete tweak to allow html
2275 var proto = $.ui.autocomplete.prototype,
2276 initSource = proto._initSource;
2278 function filter( array, term ) {
2279 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2280 return $.grep( array, function(value_) {
2281 return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2286 _initSource: function() {
2287 if ( this.options.html && $.isArray(this.options.source) ) {
2288 this.source = function( request, response ) {
2289 response( filter( this.options.source, request.term ) );
2292 initSource.call( this );
2296 _renderItem: function( ul, item) {
2297 return $( "<li></li>" )
2298 .data( "item.autocomplete", item )
2299 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2306 * A mixin containing some useful methods to handle completion inputs.
2308 instance.web.form.CompletionFieldMixin = {
2311 this.orderer = new instance.web.DropMisordered();
2314 * Call this method to search using a string.
2316 get_search_result: function(search_val) {
2319 var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2321 return this.orderer.add(dataset.name_search(
2322 search_val, self.build_domain(), 'ilike', this.limit + 1)).pipe(function(data) {
2323 self.last_search = data;
2324 // possible selections for the m2o
2325 var values = _.map(data, function(x) {
2327 label: _.str.escapeHTML(x[1]),
2334 // search more... if more results that max
2335 if (values.length > self.limit) {
2336 values = values.slice(0, self.limit);
2337 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2338 dataset.name_search(search_val, self.build_domain(), 'ilike'
2339 , false, function(data) {
2340 self._search_create_popup("search", data);
2345 var raw_result = _(data.result).map(function(x) {return x[1];});
2346 if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2347 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2348 $('<span />').text(search_val).html()), action: function() {
2349 self._quick_create(search_val);
2353 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2354 self._search_create_popup("form", undefined, {"default_name": search_val});
2360 _quick_create: function(name) {
2362 var slow_create = function () {
2363 self._search_create_popup("form", undefined, {"default_name": name});
2365 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2366 new instance.web.DataSet(this, this.field.relation, self.build_context())
2367 .name_create(name, function(data) {
2368 self.add_id(data[0]);
2369 }).fail(function(error, event) {
2370 event.preventDefault();
2376 // all search/create popup handling
2377 _search_create_popup: function(view, ids, context) {
2379 var pop = new instance.web.form.SelectCreatePopup(this);
2381 self.field.relation,
2383 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2384 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2386 disable_multiple_selection: true
2388 self.build_domain(),
2389 new instance.web.CompoundContext(self.build_context(), context || {})
2391 pop.on_select_elements.add(function(element_ids) {
2392 self.add_id(element_ids[0]);
2398 add_id: function(id) {},
2401 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2402 instance.web.form.CompletionFieldMixin, {
2403 template: "FieldMany2One",
2404 init: function(field_manager, node) {
2405 this._super(field_manager, node);
2406 instance.web.form.CompletionFieldMixin.init.call(this);
2407 this.set({'value': false});
2408 this.display_value = {};
2409 this.last_search = [];
2410 this.floating = false;
2411 this.inhibit_on_change = false;
2415 instance.web.form.ReinitializeFieldMixin.start.call(this);
2416 this.on("change:value", this, function() {
2417 this.floating = false;
2418 this.render_value();
2421 initialize_content: function() {
2422 if (!this.get("effective_readonly"))
2423 this.render_editable();
2424 this.render_value();
2426 render_editable: function() {
2428 this.$input = this.$element.find("input");
2432 return "No element was selected, you should create or select one from the dropdown list.";
2438 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2439 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2441 this.$follow_button.click(function() {
2442 if (!self.get('value')) {
2445 var pop = new instance.web.form.FormOpenPopup(self.view);
2447 self.field.relation,
2449 self.build_context(),
2451 title: _t("Open: ") + (self.string || self.name)
2454 pop.on_write_completed.add_last(function() {
2455 self.display_value = {};
2456 self.render_value();
2460 // some behavior for input
2461 this.$input.keyup(function() {
2462 if (self.$input.val() === "") {
2463 self.set({value: false});
2465 self.floating = true;
2468 this.$drop_down.click(function() {
2469 if (self.$input.autocomplete("widget").is(":visible")) {
2470 self.$input.autocomplete("close");
2472 if (self.get("value") && ! self.floating) {
2473 self.$input.autocomplete("search", "");
2475 self.$input.autocomplete("search");
2477 self.$input.focus();
2480 var tip_def = $.Deferred();
2481 var untip_def = $.Deferred();
2482 var tip_delay = 200;
2483 var tip_duration = 3000;
2484 var anyoneLoosesFocus = function() {
2485 if (self.floating) {
2486 if (self.last_search.length > 0) {
2487 if (self.last_search[0][0] != self.get("value")) {
2488 self.display_value = {};
2489 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2490 self.set({value: self.last_search[0][0]});
2492 self.render_value();
2495 self.set({value: false});
2498 if (! self.get("value")) {
2501 tip_def = $.Deferred();
2502 tip_def.then(function() {
2503 self.$input.tipsy("show");
2505 setTimeout(function() {
2508 untip_def = $.Deferred();
2509 untip_def.then(function() {
2510 self.$input.tipsy("hide");
2512 setTimeout(function() {untip_def.resolve();}, tip_duration);
2518 this.$input.focusout(anyoneLoosesFocus);
2520 var isSelecting = false;
2522 this.$input.autocomplete({
2523 source: function(req, resp) {
2524 self.get_search_result(req.term).then(function(result) {
2528 select: function(event, ui) {
2532 self.display_value = {};
2533 self.display_value["" + item.id] = item.name;
2534 self.set({value: item.id});
2535 } else if (item.action) {
2536 self.floating = true;
2541 focus: function(e, ui) {
2545 close: anyoneLoosesFocus,
2549 this.$input.autocomplete("widget").addClass("openerp");
2550 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2551 this.$input.keyup(function(e) {
2552 if (e.which === 13) {
2554 e.stopPropagation();
2556 isSelecting = false;
2560 render_value: function(no_recurse) {
2562 if (! this.get("value")) {
2563 this.display_string("");
2566 var display = this.display_value["" + this.get("value")];
2568 this.display_string(display);
2572 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2573 dataset.name_get([self.get("value")], function(data) {
2574 self.display_value["" + self.get("value")] = data[0][1];
2575 self.render_value(true);
2579 display_string: function(str) {
2581 if (!this.get("effective_readonly")) {
2582 this.$input.val(str);
2584 this.$element.find('a')
2587 .click(function () {
2589 type: 'ir.actions.act_window',
2590 res_model: self.field.relation,
2591 res_id: self.get("value"),
2592 context: self.build_context(),
2593 views: [[false, 'form']],
2600 set_value: function(value_) {
2602 if (value_ instanceof Array) {
2603 this.display_value = {};
2604 this.display_value["" + value_[0]] = value_[1];
2607 value_ = value_ || false;
2608 this.inhibit_on_change = true;
2609 this._super(value_);
2610 this.inhibit_on_change = false;
2612 add_id: function(id) {
2613 this.display_value = {};
2614 this.set({value: id});
2616 is_false: function() {
2617 return ! this.get("value");
2619 focus: function () {
2620 this.delay_focus(this.$input);
2625 # Values: (0, 0, { fields }) create
2626 # (1, ID, { fields }) update
2627 # (2, ID) remove (delete)
2628 # (3, ID) unlink one (target id or target of relation)
2630 # (5) unlink all (only valid for one2many)
2635 'create': function (values) {
2636 return [commands.CREATE, false, values];
2638 // (1, id, {values})
2640 'update': function (id, values) {
2641 return [commands.UPDATE, id, values];
2645 'delete': function (id) {
2646 return [commands.DELETE, id, false];
2648 // (3, id[, _]) removes relation, but not linked record itself
2650 'forget': function (id) {
2651 return [commands.FORGET, id, false];
2655 'link_to': function (id) {
2656 return [commands.LINK_TO, id, false];
2660 'delete_all': function () {
2661 return [5, false, false];
2663 // (6, _, ids) replaces all linked records with provided ids
2665 'replace_with': function (ids) {
2666 return [6, false, ids];
2669 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2670 multi_selection: false,
2671 disable_utility_classes: true,
2672 init: function(field_manager, node) {
2673 this._super(field_manager, node);
2674 lazy_build_o2m_kanban_view();
2675 this.is_loaded = $.Deferred();
2676 this.initial_is_loaded = this.is_loaded;
2677 this.is_setted = $.Deferred();
2678 this.form_last_update = $.Deferred();
2679 this.init_form_last_update = this.form_last_update;
2682 this._super.apply(this, arguments);
2686 this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2687 this.dataset.o2m = this;
2688 this.dataset.parent_view = this.view;
2689 this.dataset.child_name = this.name;
2690 //this.dataset.child_name =
2691 this.dataset.on_change.add_last(function() {
2692 self.trigger_on_change();
2695 this.is_setted.then(function() {
2698 this.is_loaded.then(function() {
2699 self.on("change:effective_readonly", self, function() {
2700 self.is_loaded = self.is_loaded.pipe(function() {
2701 self.viewmanager.destroy();
2702 return $.when(self.load_views()).then(function() {
2703 self.reload_current_view();
2709 trigger_on_change: function() {
2710 var tmp = this.doing_on_change;
2711 this.doing_on_change = true;
2712 this.trigger('changed_value');
2713 this.doing_on_change = tmp;
2715 load_views: function() {
2718 var modes = this.node.attrs.mode;
2719 modes = !!modes ? modes.split(",") : ["tree"];
2721 _.each(modes, function(mode) {
2724 view_type: mode == "tree" ? "list" : mode,
2727 if (self.field.views && self.field.views[mode]) {
2728 view.embedded_view = self.field.views[mode];
2730 if(view.view_type === "list") {
2731 view.options.selectable = self.multi_selection;
2732 if (self.get("effective_readonly")) {
2733 view.options.addable = null;
2734 view.options.deletable = null;
2736 } else if (view.view_type === "form") {
2737 if (self.get("effective_readonly")) {
2738 view.view_type = 'form';
2740 view.options.not_interactible_on_create = true;
2741 } else if (view.view_type === "kanban") {
2742 if (self.get("effective_readonly")) {
2743 view.options.action_buttons = false;
2744 view.options.quick_creatable = false;
2751 this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2752 this.viewmanager.o2m = self;
2753 var once = $.Deferred().then(function() {
2754 self.init_form_last_update.resolve();
2756 var def = $.Deferred().then(function() {
2757 self.initial_is_loaded.resolve();
2759 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2760 controller.o2m = self;
2761 if (view_type == "list") {
2762 if (self.get("effective_readonly"))
2763 controller.set_editable(false);
2764 } else if (view_type === "form") {
2765 if (self.get("effective_readonly")) {
2766 $(".oe_form_buttons", controller.$element).children().remove();
2768 controller.on_record_loaded.add_last(function() {
2771 controller.on_pager_action.add_first(function() {
2772 self.save_any_view();
2774 } else if (view_type == "graph") {
2775 self.reload_current_view()
2779 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2780 $.when(self.save_any_view()).then(function() {
2781 if(n_mode === "list")
2782 $.async_when().then(function() {self.reload_current_view();});
2785 this.is_setted.then(function() {
2786 $.async_when().then(function () {
2787 self.viewmanager.appendTo(self.$element);
2792 reload_current_view: function() {
2794 return self.is_loaded = self.is_loaded.pipe(function() {
2795 var active_view = self.viewmanager.active_view;
2796 var view = self.viewmanager.views[active_view].controller;
2797 if(active_view === "list") {
2798 return view.reload_content();
2799 } else if (active_view === "form") {
2800 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2801 self.dataset.index = 0;
2803 var act = function() {
2804 return view.do_show();
2806 self.form_last_update = self.form_last_update.pipe(act, act);
2807 return self.form_last_update;
2808 } else if (view.do_search) {
2809 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2813 set_value: function(value_) {
2814 value_ = value_ || [];
2816 this.dataset.reset_ids([]);
2817 if(value_.length >= 1 && value_[0] instanceof Array) {
2819 _.each(value_, function(command) {
2820 var obj = {values: command[2]};
2821 switch (command[0]) {
2822 case commands.CREATE:
2823 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2825 self.dataset.to_create.push(obj);
2826 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2829 case commands.UPDATE:
2830 obj['id'] = command[1];
2831 self.dataset.to_write.push(obj);
2832 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2835 case commands.DELETE:
2836 self.dataset.to_delete.push({id: command[1]});
2838 case commands.LINK_TO:
2839 ids.push(command[1]);
2841 case commands.DELETE_ALL:
2842 self.dataset.delete_all = true;
2847 this.dataset.set_ids(ids);
2848 } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2850 this.dataset.delete_all = true;
2851 _.each(value_, function(command) {
2852 var obj = {values: command};
2853 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2855 self.dataset.to_create.push(obj);
2856 self.dataset.cache.push(_.clone(obj));
2860 this.dataset.set_ids(ids);
2862 this._super(value_);
2863 this.dataset.reset_ids(value_);
2865 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2866 this.dataset.index = 0;
2868 self.is_setted.resolve();
2869 return self.reload_current_view();
2871 get_value: function() {
2875 this.save_any_view();
2876 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2877 val = val.concat(_.map(this.dataset.ids, function(id) {
2878 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2880 return commands.create(alter_order.values);
2882 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2884 return commands.update(alter_order.id, alter_order.values);
2886 return commands.link_to(id);
2888 return val.concat(_.map(
2889 this.dataset.to_delete, function(x) {
2890 return commands['delete'](x.id);}));
2892 save_any_view: function() {
2893 if (this.doing_on_change)
2895 return this.session.synchronized_mode(_.bind(function() {
2896 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2897 this.viewmanager.views[this.viewmanager.active_view] &&
2898 this.viewmanager.views[this.viewmanager.active_view].controller) {
2899 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2900 if (this.viewmanager.active_view === "form") {
2901 if (!view.is_initialized.isResolved()) {
2904 var res = $.when(view.do_save());
2905 if (!res.isResolved() && !res.isRejected()) {
2906 console.warn("Asynchronous get_value() is not supported in form view.");
2909 } else if (this.viewmanager.active_view === "list") {
2910 var res = $.when(view.ensure_saved());
2911 if (!res.isResolved() && !res.isRejected()) {
2912 console.warn("Asynchronous get_value() is not supported in list view.");
2920 is_syntax_valid: function() {
2921 if (!this.viewmanager.views[this.viewmanager.active_view])
2923 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2924 if (this.viewmanager.active_view === "form") {
2925 for (var f in view.fields) {
2927 if (!f.is_valid()) {
2936 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
2937 template: 'One2Many.viewmanager',
2938 init: function(parent, dataset, views, flags) {
2939 this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
2940 this.registry = this.registry.extend({
2941 list: 'instance.web.form.One2ManyListView',
2942 form: 'instance.web.form.One2ManyFormView',
2943 kanban: 'instance.web.form.One2ManyKanbanView',
2946 switch_view: function(mode, unused) {
2947 if (mode !== 'form') {
2948 return this._super(mode, unused);
2951 var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
2952 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
2953 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2954 title: _t("Open: ") + self.name,
2955 create_function: function(data) {
2956 return self.o2m.dataset.create(data).then(function(r) {
2957 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2958 self.o2m.dataset.on_change();
2961 write_function: function(id, data, options) {
2962 return self.o2m.dataset.write(id, data, {}).then(function() {
2963 self.o2m.reload_current_view();
2966 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2967 parent_view: self.o2m.view,
2968 child_name: self.o2m.name,
2969 read_function: function() {
2970 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2972 form_view_options: {'not_interactible_on_create':true},
2973 readonly: self.o2m.get("effective_readonly")
2975 pop.on_select_elements.add_last(function() {
2976 self.o2m.reload_current_view();
2981 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
2982 get_context: function() {
2983 this.context = this.o2m.build_context([this.o2m.name]);
2984 return this.context;
2988 instance.web.form.One2ManyListView = instance.web.ListView.extend({
2989 _template: 'One2Many.listview',
2990 do_add_record: function () {
2991 if (this.options.editable) {
2992 this._super.apply(this, arguments);
2995 var pop = new instance.web.form.SelectCreatePopup(this);
2997 self.o2m.field.relation,
2999 title: _t("Create: ") + self.name,
3000 initial_view: "form",
3001 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3002 create_function: function(data, callback, error_callback) {
3003 return self.o2m.dataset.create(data).then(function(r) {
3004 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3005 self.o2m.dataset.on_change();
3006 }).then(callback, error_callback);
3008 read_function: function() {
3009 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3011 parent_view: self.o2m.view,
3012 child_name: self.o2m.name,
3013 form_view_options: {'not_interactible_on_create':true}
3015 self.o2m.build_domain(),
3016 self.o2m.build_context()
3018 pop.on_select_elements.add_last(function() {
3019 self.o2m.reload_current_view();
3023 do_activate_record: function(index, id) {
3025 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3026 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3027 title: _t("Open: ") + self.name,
3028 write_function: function(id, data) {
3029 return self.o2m.dataset.write(id, data, {}, function(r) {
3030 self.o2m.reload_current_view();
3033 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3034 parent_view: self.o2m.view,
3035 child_name: self.o2m.name,
3036 read_function: function() {
3037 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3039 form_view_options: {'not_interactible_on_create':true},
3040 readonly: self.o2m.get("effective_readonly")
3043 do_button_action: function (name, id, callback) {
3045 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3046 return this._super(name, id, _.bind(def.resolve, def));
3050 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3051 form_template: 'One2Many.formview',
3052 on_loaded: function(data) {
3055 this.$buttons.find('button.oe_form_button_create').click(function() {
3056 self.do_save().then(self.on_button_new);
3059 do_notify_change: function() {
3060 if (this.dataset.parent_view) {
3061 this.dataset.parent_view.do_notify_change();
3063 this._super.apply(this, arguments);
3068 var lazy_build_o2m_kanban_view = function() {
3069 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3071 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3075 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3076 instance.web.form.ReinitializeFieldMixin, {
3077 template: "FieldMany2ManyTags",
3079 this._super.apply(this, arguments);
3080 instance.web.form.CompletionFieldMixin.init.call(this);
3081 this.set({"value": []});
3082 this._display_orderer = new instance.web.DropMisordered();
3083 this._drop_shown = false;
3087 instance.web.form.ReinitializeFieldMixin.start.call(this);
3088 this.on("change:value", this, this.render_value);
3090 initialize_content: function() {
3091 if (this.get("effective_readonly"))
3094 self. $text = $("textarea", this.$element);
3095 self.$text.textext({
3096 plugins : 'tags arrow autocomplete',
3098 render: function(suggestion) {
3099 return $('<span class="text-label"/>').
3100 data('index', suggestion['index']).html(suggestion['label']);
3105 selectFromDropdown: function() {
3106 $(this).trigger('hideDropdown');
3107 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3108 var data = self.search_result[index];
3110 self.add_id(data.id);
3117 isTagAllowed: function(tag) {
3122 removeTag: function(tag) {
3123 var id = tag.data("id");
3124 self.set({"value": _.without(self.get("value"), id)});
3126 renderTag: function(stuff) {
3127 return $.fn.textext.TextExtTags.prototype.renderTag.
3128 call(this, stuff).data("id", stuff.id);
3132 itemToString: function(item) {
3137 }).bind('getSuggestions', function(e, data) {
3139 var str = !!data ? data.query || '' : '';
3140 self.get_search_result(str).then(function(result) {
3141 self.search_result = result;
3142 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3143 return _.extend(el, {index:i});
3146 }).bind('tagClick', function(e, tag, value, callback) {
3147 var pop = new instance.web.form.FormOpenPopup(self.view);
3149 self.field.relation,
3151 self.build_context(),
3153 title: _t("Open: ") + (self.string || self.name)
3156 pop.on_write_completed.add_last(function() {
3157 self.render_value();
3159 }).bind('hideDropdown', function() {
3160 self._drop_shown = false;
3161 }).bind('showDropdown', function() {
3162 self._drop_shown = true;
3164 self.tags = self.$text.textext()[0].tags();
3165 $("textarea", this.$element).focusout(function() {
3166 $("textarea", this.$element).val("");
3167 }).keydown(function(e) {
3168 if (event.keyCode === 9 && self._drop_shown) {
3169 self.$text.textext()[0].autocomplete().selectFromDropdown();
3173 set_value: function(value_) {
3174 value_ = value_ || [];
3175 if (value_.length >= 1 && value_[0] instanceof Array) {
3176 value_ = value_[0][2];
3178 this._super(value_);
3180 get_value: function() {
3181 var tmp = [commands.replace_with(this.get("value"))];
3184 render_value: function() {
3186 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3187 var handle_names = function(data) {
3189 _.each(data, function(el) {
3190 indexed[el[0]] = el;
3192 data = _.map(self.get("value"), function(el) { return indexed[el]; });
3193 if (! self.get("effective_readonly")) {
3194 self.tags.containerElement().children().remove();
3195 $("textarea", self.$element).css("padding-left", "3px");
3196 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3198 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3199 $(".oe_form_field_many2manytags_box", self.$element).click(function() {
3200 var index = Number($(this).data("index"));
3202 type: 'ir.actions.act_window',
3203 res_model: self.field.relation,
3204 res_id: self.get("value")[index],
3205 context: self.build_context(),
3206 views: [[false, 'form']],
3212 if (! self.get('values') || self.get('values').length > 0) {
3213 this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3218 add_id: function(id) {
3219 this.set({'value': _.uniq(this.get('value').concat([id]))});
3224 * TODO niv: clean those deferred stuff, it could be better
3226 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3227 multi_selection: false,
3228 disable_utility_classes: true,
3229 init: function(field_manager, node) {
3230 this._super(field_manager, node);
3231 this.is_loaded = $.Deferred();
3232 this.initial_is_loaded = this.is_loaded;
3233 this.is_setted = $.Deferred();
3236 this._super.apply(this, arguments);
3240 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3241 this.dataset.m2m = this;
3242 this.dataset.on_unlink.add_last(function(ids) {
3243 self.dataset_changed();
3246 this.is_setted.then(function() {
3249 this.is_loaded.then(function() {
3250 self.on("change:effective_readonly", self, function() {
3251 self.is_loaded = self.is_loaded.pipe(function() {
3252 self.list_view.destroy();
3253 return $.when(self.load_view()).then(function() {
3254 self.reload_content();
3260 set_value: function(value_) {
3261 value_ = value_ || [];
3262 if (value_.length >= 1 && value_[0] instanceof Array) {
3263 value_ = value_[0][2];
3265 this._super(value_);
3266 this.dataset.set_ids(value_);
3268 self.reload_content();
3269 this.is_setted.resolve();
3271 load_view: function() {
3273 this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3274 'addable': self.get("effective_readonly") ? null : _t("Add"),
3275 'deletable': self.get("effective_readonly") ? false : true,
3276 'selectable': self.multi_selection,
3278 var embedded = (this.field.views || {}).tree;
3280 this.list_view.set_embedded_view(embedded);
3282 this.list_view.m2m_field = this;
3283 var loaded = $.Deferred();
3284 this.list_view.on_loaded.add_last(function() {
3285 self.initial_is_loaded.resolve();
3288 $.async_when().then(function () {
3289 self.list_view.appendTo(self.$element);
3293 reload_content: function() {
3295 this.is_loaded = this.is_loaded.pipe(function() {
3296 return self.list_view.reload_content();
3299 dataset_changed: function() {
3300 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3304 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3305 get_context: function() {
3306 this.context = this.m2m.build_context();
3307 return this.context;
3313 * @extends instance.web.ListView
3315 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3316 do_add_record: function () {
3317 var pop = new instance.web.form.SelectCreatePopup(this);
3321 title: _t("Add: ") + this.name
3323 new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3324 this.m2m_field.build_context()
3327 pop.on_select_elements.add(function(element_ids) {
3328 _.each(element_ids, function(one_id) {
3329 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3330 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3331 self.m2m_field.dataset_changed();
3332 self.reload_content();
3337 do_activate_record: function(index, id) {
3339 var pop = new instance.web.form.FormOpenPopup(this);
3340 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3341 title: _t("Open: ") + this.name,
3342 readonly: this.getParent().get("effective_readonly")
3344 pop.on_write_completed.add_last(function() {
3345 self.reload_content();
3350 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3351 disable_utility_classes: true,
3352 init: function(field_manager, node) {
3353 this._super(field_manager, node);
3354 instance.web.form.CompletionFieldMixin.init.call(this);
3355 m2m_kanban_lazy_init();
3356 this.is_loaded = $.Deferred();
3357 this.initial_is_loaded = this.is_loaded;
3358 this.is_setted = $.Deferred();
3361 this._super.apply(this, arguments);
3365 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3366 this.dataset.m2m = this;
3367 this.dataset.on_unlink.add_last(function(ids) {
3368 self.dataset_changed();
3371 this.is_setted.then(function() {
3374 this.is_loaded.then(function() {
3375 self.on("change:effective_readonly", self, function() {
3376 self.is_loaded = self.is_loaded.pipe(function() {
3377 self.kanban_view.destroy();
3378 return $.when(self.load_view()).then(function() {
3379 self.reload_content();
3385 set_value: function(value_) {
3386 value_ = value_ || [];
3387 if (value_.length >= 1 && value_[0] instanceof Array) {
3388 value_ = value_[0][2];
3390 this._super(value_);
3391 this.dataset.set_ids(value_);
3393 self.reload_content();
3394 this.is_setted.resolve();
3396 load_view: function() {
3398 this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3399 'create_text': _t("Add"),
3400 'creatable': self.get("effective_readonly") ? false : true,
3401 'quick_creatable': self.get("effective_readonly") ? false : true,
3403 var embedded = (this.field.views || {}).kanban;
3405 this.kanban_view.set_embedded_view(embedded);
3407 this.kanban_view.m2m = this;
3408 var loaded = $.Deferred();
3409 this.kanban_view.on_loaded.add_last(function() {
3410 self.initial_is_loaded.resolve();
3413 this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3414 $.async_when().then(function () {
3415 self.kanban_view.appendTo(self.$element);
3419 reload_content: function() {
3421 this.is_loaded = this.is_loaded.pipe(function() {
3422 return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3425 dataset_changed: function() {
3426 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3428 open_popup: function(type, unused) {
3429 if (type !== "form")
3432 if (this.dataset.index === null) {
3433 var pop = new instance.web.form.SelectCreatePopup(this);
3435 this.field.relation,
3437 title: _t("Add: ") + this.name
3439 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3440 this.build_context()
3442 pop.on_select_elements.add(function(element_ids) {
3443 _.each(element_ids, function(one_id) {
3444 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3445 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3446 self.dataset_changed();
3447 self.reload_content();
3452 var id = self.dataset.ids[self.dataset.index];
3453 var pop = new instance.web.form.FormOpenPopup(self.view);
3454 pop.show_element(self.field.relation, id, self.build_context(), {
3455 title: _t("Open: ") + self.name,
3456 write_function: function(id, data, options) {
3457 return self.dataset.write(id, data, {}).then(function() {
3458 self.reload_content();
3461 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3462 parent_view: self.view,
3463 child_name: self.name,
3464 readonly: self.get("effective_readonly")
3468 add_id: function(id) {
3469 this.quick_create.add_id(id);
3473 function m2m_kanban_lazy_init() {
3474 if (instance.web.form.Many2ManyKanbanView)
3476 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3477 quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3478 _is_quick_create_enabled: function() {
3479 return this._super() && ! this.group_by;
3482 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3483 template: 'Many2ManyKanban.quick_create',
3486 * close_btn: If true, the widget will display a "Close" button able to trigger
3489 init: function(parent, dataset, context, buttons) {
3490 this._super(parent);
3491 this.m2m = this.getParent().view.m2m;
3492 this.m2m.quick_create = this;
3493 this._dataset = dataset;
3494 this._buttons = buttons || false;
3495 this._context = context || {};
3497 start: function () {
3499 self.$text = this.$element.find('input').css("width", "200px");
3500 self.$text.textext({
3501 plugins : 'arrow autocomplete',
3503 render: function(suggestion) {
3504 return $('<span class="text-label"/>').
3505 data('index', suggestion['index']).html(suggestion['label']);
3510 selectFromDropdown: function() {
3511 $(this).trigger('hideDropdown');
3512 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3513 var data = self.search_result[index];
3515 self.add_id(data.id);
3522 itemToString: function(item) {
3527 }).bind('getSuggestions', function(e, data) {
3529 var str = !!data ? data.query || '' : '';
3530 self.m2m.get_search_result(str).then(function(result) {
3531 self.search_result = result;
3532 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3533 return _.extend(el, {index:i});
3537 self.$text.focusout(function() {
3544 add_id: function(id) {
3547 self.trigger('added', id);
3553 * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3555 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3556 template: "AbstractFormPopup.render",
3559 * -readonly: only applicable when not in creation mode, default to false
3560 * - alternative_form_view
3566 * - form_view_options
3568 init_popup: function(model, row_id, domain, context, options) {
3569 this.row_id = row_id;
3571 this.domain = domain || [];
3572 this.context = context || {};
3573 this.options = options;
3574 _.defaults(this.options, {
3577 init_dataset: function() {
3579 this.created_elements = [];
3580 this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3581 this.dataset.read_function = this.options.read_function;
3582 this.dataset.create_function = function(data, sup) {
3583 var fct = self.options.create_function || sup;
3584 return fct.call(this, data).then(function(r) {
3585 self.created_elements.push(r.result);
3588 this.dataset.write_function = function(id, data, options, sup) {
3589 var fct = self.options.write_function || sup;
3590 return fct.call(this, id, data, options).then(self.on_write_completed);
3592 this.dataset.parent_view = this.options.parent_view;
3593 this.dataset.child_name = this.options.child_name;
3595 display_popup: function() {
3597 this.renderElement();
3598 new instance.web.Dialog(this, {
3604 title: this.options.title || "",
3605 }, this.$element).open();
3608 on_write_completed: function() {},
3609 setup_form_view: function() {
3612 this.dataset.ids = [this.row_id];
3613 this.dataset.index = 0;
3615 this.dataset.index = null;
3617 var options = _.clone(self.options.form_view_options) || {};
3618 if (this.row_id !== null) {
3619 options.initial_mode = this.options.readonly ? "view" : "edit";
3621 this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3622 if (this.options.alternative_form_view) {
3623 this.view_form.set_embedded_view(this.options.alternative_form_view);
3625 this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3626 this.view_form.on_loaded.add_last(function() {
3627 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3628 var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3629 $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3630 var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3631 $snbutton.click(function() {
3632 $.when(self.view_form.do_save()).then(function() {
3633 self.view_form.reload_mutex.exec(function() {
3634 self.view_form.on_button_new();
3638 var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3639 $sbutton.click(function() {
3640 $.when(self.view_form.do_save()).then(function() {
3641 self.view_form.reload_mutex.exec(function() {
3646 var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3647 $cbutton.click(function() {
3650 if (self.row_id !== null && self.options.readonly) {
3653 $cbutton.text(_t("Close"));
3655 self.view_form.do_show();
3658 on_select_elements: function(element_ids) {
3660 check_exit: function() {
3661 if (this.created_elements.length > 0) {
3662 this.on_select_elements(this.created_elements);
3666 destroy: function () {
3667 this.$element.dialog('close');
3673 * Class to display a popup containing a form view.
3675 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3676 show_element: function(model, row_id, context, options) {
3677 this.init_popup(model, row_id, [], context, options);
3678 _.defaults(this.options, {
3680 this.display_popup();
3684 this.init_dataset();
3685 this.setup_form_view();
3690 * Class to display a popup to display a list to search a row. It also allows
3691 * to switch to a form view to create a new row.
3693 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3697 * - initial_view: form or search (default search)
3698 * - disable_multiple_selection
3699 * - list_view_options
3701 select_element: function(model, options, domain, context) {
3702 this.init_popup(model, null, domain, context, options);
3704 _.defaults(this.options, {
3705 initial_view: "search",
3707 this.initial_ids = this.options.initial_ids;
3708 this.display_popup();
3712 this.init_dataset();
3713 if (this.options.initial_view == "search") {
3714 self.rpc('/web/session/eval_domain_and_context', {
3716 contexts: [this.context]
3717 }, function (results) {
3718 var search_defaults = {};
3719 _.each(results.context, function (value_, key) {
3720 var match = /^search_default_(.*)$/.exec(key);
3722 search_defaults[match[1]] = value_;
3725 self.setup_search_view(search_defaults);
3731 setup_search_view: function(search_defaults) {
3733 if (this.searchview) {
3734 this.searchview.destroy();
3736 this.searchview = new instance.web.SearchView(this,
3737 this.dataset, false, search_defaults);
3738 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3739 if (self.initial_ids) {
3740 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3741 contexts, groupbys);
3742 self.initial_ids = undefined;
3744 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3747 this.searchview.on_loaded.add_last(function () {
3748 self.view_list = new instance.web.form.SelectCreateListView(self,
3749 self.dataset, false,
3750 _.extend({'deletable': false,
3751 'selectable': !self.options.disable_multiple_selection
3752 }, self.options.list_view_options || {}));
3753 self.view_list.popup = self;
3754 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3755 self.view_list.do_show();
3756 }).pipe(function() {
3757 self.searchview.do_search();
3759 self.view_list.on_loaded.add_last(function() {
3760 var $buttons = self.view_list.$element.find(".oe-actions");
3761 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3762 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3763 $cbutton.click(function() {
3766 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3767 if(self.options.disable_multiple_selection) {
3770 $sbutton.click(function() {
3771 self.on_select_elements(self.selected_ids);
3776 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3778 do_search: function(domains, contexts, groupbys) {
3780 this.rpc('/web/session/eval_domain_and_context', {
3781 domains: domains || [],
3782 contexts: contexts || [],
3783 group_by_seq: groupbys || []
3784 }, function (results) {
3785 self.view_list.do_search(results.domain, results.context, results.group_by);
3788 on_click_element: function(ids) {
3789 this.selected_ids = ids || [];
3790 if(this.selected_ids.length > 0) {
3791 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3793 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3796 new_object: function() {
3797 if (this.searchview) {
3798 this.searchview.hide();
3800 if (this.view_list) {
3801 this.view_list.$element.hide();
3803 this.setup_form_view();
3807 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3808 do_add_record: function () {
3809 this.popup.new_object();
3811 select_record: function(index) {
3812 this.popup.on_select_elements([this.dataset.ids[index]]);
3813 this.popup.destroy();
3815 do_select: function(ids, records) {
3816 this._super(ids, records);
3817 this.popup.on_click_element(ids);
3821 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3822 template: 'FieldReference',
3823 init: function(field_manager, node) {
3824 this._super(field_manager, node);
3825 this.reference_ready = true;
3827 on_nop: function() {
3829 on_selection_changed: function() {
3830 if (this.reference_ready) {
3831 var sel = this.selection.get_value();
3832 this.m2o.field.relation = sel;
3833 this.m2o.set_value(false);
3834 this.m2o.$element.toggle(sel !== false);
3837 destroy_content: function() {
3838 if (this.selection) {
3839 this.selection.destroy();
3840 this.selection = undefined;
3844 this.m2o = undefined;
3847 initialize_content: function() {
3848 this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3851 this.selection.view = this.view;
3852 this.selection.set({force_readonly: this.get('effective_readonly')});
3853 this.selection.on("change:value", this, this.on_selection_changed);
3854 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3855 this.selection.renderElement();
3856 this.selection.start();
3858 this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3861 this.m2o.view = this.view;
3862 this.m2o.set({force_readonly: this.get("effective_readonly")});
3863 this.m2o.on("change:value", this, this.data_changed);
3864 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3865 this.m2o.renderElement();
3868 is_false: function() {
3869 return typeof(this.get_value()) !== 'string';
3871 set_value: function(value_) {
3872 this._super(value_);
3873 this.render_value();
3875 render_value: function() {
3876 this.reference_ready = false;
3877 var vals = [], sel_val, m2o_val;
3878 if (typeof(this.get('value')) === 'string') {
3879 vals = this.get('value').split(',');
3881 sel_val = vals[0] || false;
3882 m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3883 if (!this.get("effective_readonly")) {
3884 this.selection.set_value(sel_val);
3886 this.m2o.field.relation = sel_val;
3887 this.m2o.set_value(m2o_val);
3888 this.reference_ready = true;
3890 data_changed: function() {
3891 var model = this.selection.get_value(),
3892 id = this.m2o.get_value();
3893 if (typeof(model) === 'string' && typeof(id) === 'number') {
3894 this.set({'value': model + ',' + id});
3896 this.set({'value': false});
3899 get_field: function(name) {
3900 if (name === "selection") {
3902 selection: this.view.fields_view.fields[this.name].selection,
3905 } else if (name === "m2o") {
3911 throw Exception("Should not happen");
3915 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3916 init: function(field_manager, node) {
3917 this._super(field_manager, node);
3918 this.iframe = this.element_id + '_iframe';
3919 this.binary_value = false;
3921 initialize_content: function() {
3922 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3923 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3924 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3926 human_filesize : function(size) {
3927 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3929 while (size >= 1024) {
3933 return size.toFixed(2) + ' ' + units[i];
3935 on_file_change: function(e) {
3936 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3937 // http://www.html5rocks.com/tutorials/file/dndfiles/
3938 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3939 window[this.iframe] = this.on_file_uploaded;
3940 if ($(e.target).val() != '') {
3941 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3942 this.$element.find('form.oe-binary-form').submit();
3943 this.$element.find('.oe-binary-progress').show();
3944 this.$element.find('.oe-binary').hide();
3947 on_file_uploaded: function(size, name, content_type, file_base64) {
3948 delete(window[this.iframe]);
3949 if (size === false) {
3950 this.do_warn("File Upload", "There was a problem while uploading your file");
3951 // TODO: use openerp web crashmanager
3952 console.warn("Error while uploading file : ", name);
3954 this.on_file_uploaded_and_valid.apply(this, arguments);
3956 this.$element.find('.oe-binary-progress').hide();
3957 this.$element.find('.oe-binary').show();
3959 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3961 on_save_as: function() {
3963 this.session.get_file({
3964 url: '/web/binary/saveas_ajax',
3965 data: {data: JSON.stringify({
3966 model: this.view.dataset.model,
3967 id: (this.view.datarecord.id || ''),
3969 filename_field: (this.node.attrs.filename || ''),
3970 context: this.view.dataset.get_context()
3972 complete: $.unblockUI,
3973 error: instance.webclient.crashmanager.on_rpc_error
3976 on_clear: function() {
3977 if (this.get('value') !== false) {
3978 this.binary_value = false;
3979 this.set({'value': false});
3985 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
3986 template: 'FieldBinaryFile',
3987 initialize_content: function() {
3989 if (this.get("effective_readonly")) {
3991 this.$element.find('a').click(function() {
3992 if (self.get('value')) {
3999 set_value: function(value_) {
4000 this._super.apply(this, arguments);
4001 this.render_value();
4003 render_value: function() {
4004 if (!this.get("effective_readonly")) {
4006 if (this.node.attrs.filename) {
4007 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4009 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4011 this.$element.find('input').eq(0).val(show_value);
4013 this.$element.find('a').show(!!this.get('value'));
4014 if (this.get('value')) {
4015 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4016 this.$element.find('a').text(show_value);
4020 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4021 this.binary_value = true;
4022 this.set({'value': file_base64});
4023 var show_value = name + " (" + this.human_filesize(size) + ")";
4024 this.$element.find('input').eq(0).val(show_value);
4025 this.set_filename(name);
4027 set_filename: function(value_) {
4028 var filename = this.node.attrs.filename;
4029 if (this.view.fields[filename]) {
4030 this.view.fields[filename].set({value: value_});
4033 on_clear: function() {
4034 this._super.apply(this, arguments);
4035 this.$element.find('input').eq(0).val('');
4036 this.set_filename('');
4040 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4041 template: 'FieldBinaryImage',
4042 initialize_content: function() {
4044 this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
4045 if (!this.get("effective_readonly"))
4046 this.$element.find('.oe-binary').show();
4048 this.$element.find('.oe-binary').hide();
4050 set_value: function(value_) {
4051 this._super.apply(this, arguments);
4052 this.render_value();
4054 render_value: function() {
4056 if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4057 url = 'data:image/png;base64,' + this.get('value');
4058 } else if (this.get('value')) {
4059 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4060 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4062 url = "/web/static/src/img/placeholder.png";
4064 var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
4065 this.$placeholder.html(rendered);
4067 on_file_change: function() {
4068 this.render_value();
4069 this._super.apply(this, arguments);
4071 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4072 this.set({'value': file_base64});
4073 this.binary_value = true;
4074 this.render_value();
4076 on_clear: function() {
4077 this._super.apply(this, arguments);
4078 this.render_value();
4082 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4083 template: "EmptyComponent",
4086 this.selected_value = null;
4090 set_value: function(value_) {
4091 this._super(value_);
4092 this.selected_value = value_;
4096 render_list: function() {
4098 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4099 function(x) { return _.str.trim(x); });
4100 shown = _.select(shown, function(x) { return x.length > 0; });
4102 if (shown.length == 0) {
4103 this.to_show = this.field.selection;
4105 this.to_show = _.select(this.field.selection, function(x) {
4106 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4110 var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4111 this.$element.html(content);
4113 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4114 var color = colors[this.selected_value];
4116 var elem = this.$element.find("li.oe-arrow-list-selected span");
4117 elem.css("border-color", color);
4118 if (this.check_white(color))
4119 elem.css("color", "white");
4120 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
4121 elem.css("border-left-color", "rgba(0,0,0,0)");
4122 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
4123 elem.css("border-color", "rgba(0,0,0,0)");
4124 elem.css("border-left-color", color);
4127 check_white: function(color) {
4128 var div = $("<div></div>");
4129 div.css("display", "none");
4130 div.css("color", color);
4131 div.appendTo($("body"));
4132 var ncolor = div.css("color");
4134 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
4138 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
4139 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
4148 * Registry of form fields, called by :js:`instance.web.FormView`.
4150 * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4151 * will substitute to the <field> tags as defined in OpenERP's views.
4153 instance.web.form.widgets = new instance.web.Registry({
4154 'char' : 'instance.web.form.FieldChar',
4155 'id' : 'instance.web.form.FieldID',
4156 'email' : 'instance.web.form.FieldEmail',
4157 'url' : 'instance.web.form.FieldUrl',
4158 'text' : 'instance.web.form.FieldText',
4159 'date' : 'instance.web.form.FieldDate',
4160 'datetime' : 'instance.web.form.FieldDatetime',
4161 'selection' : 'instance.web.form.FieldSelection',
4162 'many2one' : 'instance.web.form.FieldMany2One',
4163 'many2many' : 'instance.web.form.FieldMany2Many',
4164 'many2manytags' : 'instance.web.form.FieldMany2ManyTags',
4165 'many2manykanban' : 'instance.web.form.FieldMany2ManyKanban',
4166 'one2many' : 'instance.web.form.FieldOne2Many',
4167 'one2many_list' : 'instance.web.form.FieldOne2Many',
4168 'reference' : 'instance.web.form.FieldReference',
4169 'boolean' : 'instance.web.form.FieldBoolean',
4170 'float' : 'instance.web.form.FieldFloat',
4171 'integer': 'instance.web.form.FieldFloat',
4172 'float_time': 'instance.web.form.FieldFloat',
4173 'progressbar': 'instance.web.form.FieldProgressBar',
4174 'image': 'instance.web.form.FieldBinaryImage',
4175 'binary': 'instance.web.form.FieldBinaryFile',
4176 'statusbar': 'instance.web.form.FieldStatus'
4180 * Registry of widgets usable in the form view that can substitute to any possible
4181 * tags defined in OpenERP's form views.
4183 * Every referenced class should extend FormWidget.
4185 instance.web.form.tags = new instance.web.Registry({
4186 'button' : 'instance.web.form.WidgetButton',
4191 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: