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 (options) {
213 options = options || {};
215 this.sidebar.$element.show();
218 this.$buttons.show();
219 this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
224 this.$element.show().css('visibility', 'hidden');
225 this.$element.removeClass('oe_form_dirty');
226 return this.has_been_loaded.pipe(function() {
228 if (self.dataset.index === null) {
229 // null index means we should start a new record
230 result = self.on_button_new();
232 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
233 context : { 'bin_size' : true }
234 }).pipe(self.on_record_loaded);
236 result.pipe(function() {
237 if (options.editable) {
238 self.set({mode: "edit"});
240 self.$element.css('visibility', 'visible');
245 do_hide: function () {
247 this.sidebar.$element.hide();
250 this.$buttons.hide();
257 on_record_loaded: function(record) {
258 var self = this, set_values = [];
260 this.do_warn("Form", "The record could not be found in the database.", true);
261 return $.Deferred().reject();
263 this.datarecord = record;
266 this.kill_current_form();
267 this.rendering_engine.set_fields_view(this.get_fvg_from_qweb(record));
268 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
269 this.rendering_engine.render_to($dest);
272 _(this.fields).each(function (field, f) {
273 field._dirty_flag = false;
274 var result = field.set_value(self.datarecord[f] || false);
275 set_values.push(result);
277 return $.when.apply(null, set_values).pipe(function() {
279 // New record: Second pass in order to trigger the onchanges
280 // respecting the fields order defined in the view
281 _.each(self.fields_order, function(field_name) {
282 if (record[field_name] !== undefined) {
283 var field = self.fields[field_name];
284 field._dirty_flag = true;
285 self.do_onchange(field);
289 self.on_form_changed();
290 self.is_initialized.resolve();
291 self.do_update_pager(record.id == null);
293 self.sidebar.do_attachement_update(self.dataset, self.datarecord.id);
295 if (self.default_focus_field) {
296 self.default_focus_field.focus();
299 self.do_push_state({id:record.id});
301 self.$element.removeClass('oe_form_dirty');
302 self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
305 on_form_changed: function() {
306 this.trigger("view_content_has_changed");
308 do_notify_change: function() {
309 this.$element.addClass('oe_form_dirty');
310 this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
312 on_pager_action: function(action) {
313 if (this.can_be_discarded()) {
316 this.dataset.index = 0;
319 this.dataset.previous();
325 this.dataset.index = this.dataset.ids.length - 1;
331 do_update_pager: function(hide_index) {
332 var index = hide_index ? '-' : this.dataset.index + 1;
333 this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
334 .find('span.oe_pager_index').html(index).end()
335 .find('span.oe_pager_count').html(this.dataset.ids.length);
337 parse_on_change: function (on_change, widget) {
339 var onchange = _.str.trim(on_change);
340 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
345 var method = call[1];
346 if (!_.str.trim(call[2])) {
347 return {method: method, args: [], context_index: null}
350 var argument_replacement = {
351 'False': function () {return false;},
352 'True': function () {return true;},
353 'None': function () {return null;},
354 'context': function (i) {
356 var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
360 var parent_fields = null, context_index = null;
361 var args = _.map(call[2].split(','), function (a, i) {
362 var field = _.str.trim(a);
364 // literal constant or context
365 if (field in argument_replacement) {
366 return argument_replacement[field](i);
369 if (/^-?\d+(\.\d+)?$/.test(field)) {
370 return Number(field);
373 if (self.fields[field]) {
374 var value_ = self.fields[field].get_value();
375 return value_ == null ? false : value_;
378 var splitted = field.split('.');
379 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
380 if (parent_fields === null) {
381 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
383 var p_val = parent_fields[_.str.trim(splitted[1])];
384 if (p_val !== undefined) {
385 return p_val == null ? false : p_val;
389 var first_char = field[0], last_char = field[field.length-1];
390 if ((first_char === '"' && last_char === '"')
391 || (first_char === "'" && last_char === "'")) {
392 return field.slice(1, -1);
395 throw new Error("Could not get field with name '" + field +
396 "' for onchange '" + onchange + "'");
402 context_index: context_index
405 do_onchange: function(widget, processed) {
407 return this.on_change_mutex.exec(function() {
409 var response = {}, can_process_onchange = $.Deferred();
410 processed = processed || [];
411 processed.push(widget.name);
412 var on_change = widget.node.attrs.on_change;
414 var change_spec = self.parse_on_change(on_change, widget);
417 url: '/web/dataset/onchange',
420 can_process_onchange = self.rpc(ajax, {
421 model: self.dataset.model,
422 method: change_spec.method,
423 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
424 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
425 }).then(function(r) {
426 _.extend(response, r);
429 console.warn("Wrong on_change format", on_change);
432 // fail if onchange failed
433 if (can_process_onchange.isRejected()) {
434 return can_process_onchange;
437 if (widget.field['change_default']) {
438 var fieldname = widget.name, value_;
439 if (response.value && (fieldname in response.value)) {
440 // Use value from onchange if onchange executed
441 value_ = response.value[fieldname];
443 // otherwise get form value for field
444 value_ = self.fields[fieldname].get_value();
446 var condition = fieldname + '=' + value_;
449 can_process_onchange = self.rpc({
450 url: '/web/dataset/call',
454 method: 'get_defaults',
455 args: [self.model, condition]
456 }).then(function (results) {
457 if (!results.length) { return; }
458 if (!response.value) {
461 for(var i=0; i<results.length; ++i) {
462 // [whatever, key, value]
463 var triplet = results[i];
464 response.value[triplet[1]] = triplet[2];
469 if (can_process_onchange.isRejected()) {
470 return can_process_onchange;
473 return self.on_processed_onchange(response, processed);
476 return $.Deferred().reject();
480 on_processed_onchange: function(response, processed) {
482 var result = response;
484 for (var f in result.value) {
485 if (!result.value.hasOwnProperty(f)) { continue; }
486 var field = this.fields[f];
487 // If field is not defined in the view, just ignore it
489 var value_ = result.value[f];
490 if (field.get_value() != value_) {
491 field.set_value(value_);
492 field._dirty_flag = true;
493 if (!_.contains(processed, field.name)) {
494 this.do_onchange(field, processed);
499 this.on_form_changed();
501 if (!_.isEmpty(result.warning)) {
502 instance.web.dialog($(QWeb.render("CrashManager.warning", result.warning)), {
503 title:result.warning.title,
506 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
511 function edit_domain(node) {
512 var new_domain = result.domain[node.attrs.name];
514 node.attrs.domain = new_domain;
516 _(node.children).each(edit_domain);
518 edit_domain(this.fields_view.arch);
520 return $.Deferred().resolve();
523 return $.Deferred().reject();
526 switch_mode: function() {
528 if(this.get("mode") == "view") {
529 self.$element.removeClass('oe_form_editable').addClass('oe_form_readonly');
530 self.$buttons.find('.oe_form_buttons_edit').hide();
531 self.$buttons.find('.oe_form_buttons_view').show();
532 self.$sidebar.show();
533 _.each(this.fields,function(field){
534 field.set({"force_readonly": true});
537 self.$element.removeClass('oe_form_readonly').addClass('oe_form_editable');
538 self.$buttons.find('.oe_form_buttons_edit').show();
539 self.$buttons.find('.oe_form_buttons_view').hide();
540 self.$sidebar.hide();
541 _.each(this.fields,function(field){
542 field.set({"force_readonly": false});
546 on_button_save: function() {
548 return this.do_save().then(function(result) {
549 self.set({mode: "view"});
552 on_button_cancel: function(event) {
553 if (this.can_be_discarded()) {
554 this.set({mode: "view"});
558 on_button_new: function() {
560 this.set({mode: "edit"});
561 var def = $.Deferred();
562 $.when(this.has_been_loaded).then(function() {
563 if (self.can_be_discarded()) {
564 var keys = _.keys(self.fields_view.fields);
566 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
570 self.on_record_loaded({}).then(function() {
576 return def.promise();
578 on_button_edit: function() {
579 return this.set({mode: "edit"});
581 on_button_create: function() {
582 this.dataset.index = null;
585 on_button_duplicate: function() {
587 var def = $.Deferred();
588 $.when(this.has_been_loaded).then(function() {
589 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
590 return self.on_created({ result : new_id });
592 return self.set({mode: "edit"});
597 return def.promise();
599 on_button_delete: function() {
601 var def = $.Deferred();
602 $.when(this.has_been_loaded).then(function() {
603 if (self.datarecord.id && confirm(_t("Do you really want to delete this record?"))) {
604 self.dataset.unlink([self.datarecord.id]).then(function() {
605 self.on_pager_action('next');
609 $.async_when().then(function () {
614 return def.promise();
616 can_be_discarded: function() {
617 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
620 * Triggers saving the form's record. Chooses between creating a new
621 * record or saving an existing one depending on whether the record
622 * already has an id property.
624 * @param {Function} success callback on save success
625 * @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)
627 do_save: function(success, prepend_on_create) {
629 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
631 var form_invalid = false,
633 first_invalid_field = null;
634 for (var f in self.fields) {
638 if (!first_invalid_field) {
639 first_invalid_field = f;
641 } else if (f.name !== 'id' && !f.get("readonly") && (!self.datarecord.id || f._dirty_flag)) {
642 // Special case 'id' field, do not save this field
643 // on 'create' : save all non readonly fields
644 // on 'edit' : save non readonly modified fields
645 values[f.name] = f.get_value();
649 self.set({'display_invalid_fields': true});
650 for (var f in self.fields) {
651 self.fields[f]._check_css_flags();
653 first_invalid_field.focus();
655 return $.Deferred().reject();
657 self.set({'display_invalid_fields': false});
659 if (!self.datarecord.id) {
660 //console.log("FormView(", self, ") : About to create", values);
661 save_deferral = self.dataset.create(values).pipe(function(r) {
662 return self.on_created(r, undefined, prepend_on_create);
664 } else if (_.isEmpty(values) && ! self.force_dirty) {
665 //console.log("FormView(", self, ") : Nothing to save");
666 save_deferral = $.Deferred().resolve({}).promise();
668 self.force_dirty = false;
669 //console.log("FormView(", self, ") : About to save", values);
670 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
671 return self.on_saved(r);
674 return save_deferral.then(success);
678 return $.Deferred().reject();
682 on_invalid: function() {
684 _.each(this.fields, function(f) {
686 msg += "<li>" + (f.node.attrs.string || f.field.string) + "</li>";
690 this.do_warn("The following fields are invalid :", msg);
692 on_saved: function(r, success) {
694 // should not happen in the server, but may happen for internal purpose
695 return $.Deferred().reject();
697 return $.when(this.reload()).pipe(function () {
698 return $.when(r).then(success); }, null);
702 * Updates the form' dataset to contain the new record:
704 * * Adds the newly created record to the current dataset (at the end by
706 * * Selects that record (sets the dataset's index to point to the new
708 * * Updates the pager and sidebar displays
711 * @param {Function} success callback to execute after having updated the dataset
712 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
714 on_created: function(r, success, prepend_on_create) {
716 // should not happen in the server, but may happen for internal purpose
717 return $.Deferred().reject();
719 this.datarecord.id = r.result;
720 if (!prepend_on_create) {
721 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
722 this.dataset.index = this.dataset.ids.length - 1;
724 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
725 this.dataset.index = 0;
727 this.do_update_pager();
729 this.sidebar.do_attachement_update(this.dataset, this.datarecord.id);
732 return $.when(_.extend(r, {created: true})).then(success);
735 on_action: function (action) {
736 console.debug('Executing action', action);
740 return this.reload_mutex.exec(function() {
741 if (self.dataset.index == null) {
743 return $.Deferred().reject().promise();
745 if (self.dataset.index == null || self.dataset.index < 0) {
746 return $.when(self.on_button_new());
748 return self.dataset.read_index(_.keys(self.fields_view.fields), {
749 context : { 'bin_size' : true }
750 }).pipe(self.on_record_loaded);
754 get_widgets: function() {
755 return _.filter(this.getChildren(), function(obj) {
756 return obj instanceof instance.web.form.FormWidget;
759 get_fields_values: function(blacklist) {
760 blacklist = blacklist || [];
762 var ids = this.get_selected_ids();
763 values["id"] = ids.length > 0 ? ids[0] : false;
764 _.each(this.fields, function(value_, key) {
765 if (_.include(blacklist, key))
767 var val = value_.get_value();
772 get_selected_ids: function() {
773 var id = this.dataset.ids[this.dataset.index];
774 return id ? [id] : [];
776 recursive_save: function() {
778 return $.when(this.do_save()).pipe(function(res) {
779 if (self.dataset.parent_view)
780 return self.dataset.parent_view.recursive_save();
783 is_dirty: function() {
784 return _.any(this.fields, function (value_) {
785 return value_._dirty_flag;
788 is_interactible_record: function() {
789 var id = this.datarecord.id;
791 if (this.options.not_interactible_on_create)
793 } else if (typeof(id) === "string") {
794 if(instance.web.BufferedDataSet.virtual_id_regex.test(id))
799 sidebar_context: function () {
800 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
802 open_defaults_dialog: function () {
804 var fields = _.chain(this.fields)
805 .map(function (field, name) {
806 var value = field.get_value();
807 // ignore fields which are empty, invisible, readonly, o2m
810 || field.get('invisible')
811 || field.get("readonly")
812 || field.field.type === 'one2many'
813 || field.field.type === 'many2many') {
816 var displayed = value;
817 switch (field.field.type) {
819 displayed = _(field.values).find(function (option) {
820 return option[0] === value;
827 string: field.node.attrs.string || field.field.string,
829 displayed: displayed,
830 // convert undefined to false
831 change_default: !!field.field.change_default
835 .sortBy(function (field) { return field.string; })
837 var conditions = _.chain(fields)
838 .filter(function (field) { return field.change_default; })
841 var d = new instance.web.Dialog(this, {
842 title: _t("Set Default"),
845 conditions: conditions
848 {text: _t("Close"), click: function () { d.close(); }},
849 {text: _t("Save default"), click: function () {
850 var $defaults = d.$element.find('#formview_default_fields');
851 var field_to_set = $defaults.val();
853 $defaults.parent().addClass('oe_form_invalid');
856 var condition = d.$element.find('#formview_default_conditions').val(),
857 all_users = d.$element.find('#formview_default_all').is(':checked');
858 new instance.web.DataSet(self, 'ir.values').call(
862 self.fields[field_to_set].get_value(),
866 ]).then(function () { d.close(); });
870 d.template = 'FormView.set_default';
873 register_field: function(field, name) {
874 this.fields[name] = field;
875 this.fields_order.push(name);
876 if (this.get_field(name).translate) {
877 this.translatable_fields.push(field);
879 field.on('changed_value', this, function() {
880 field._dirty_flag = true;
881 if (field.is_syntax_valid()) {
882 this.do_onchange(field);
883 this.on_form_changed(true);
884 this.do_notify_change();
888 get_field: function(field_name) {
889 return this.fields_view.fields[field_name];
891 is_create_mode: function() {
892 return !this.datarecord.id;
897 * Interface to be implemented by rendering engines for the form view.
899 instance.web.form.FormRenderingEngineInterface = instance.web.Class.extend({
900 set_fields_view: function(fields_view) {},
901 set_fields_registry: function(fields_registry) {},
902 render_to: function($element) {},
906 * Default rendering engine for the form view.
908 * It is necessary to set the view using set_view() before usage.
910 instance.web.form.FormRenderingEngine = instance.web.form.FormRenderingEngineInterface.extend({
911 init: function(view) {
914 set_fields_view: function(fvg) {
916 this.version = parseFloat(this.fvg.arch.attrs.version);
917 if (isNaN(this.version)) {
921 set_tags_registry: function(tags_registry) {
922 this.tags_registry = tags_registry;
924 set_fields_registry: function(fields_registry) {
925 this.fields_registry = fields_registry;
927 // Backward compatibility tools, current default version: v6.1
928 process_version: function() {
929 if (this.version < 7.0) {
930 this.$form.find('form:first').wrapInner('<group col="4"/>');
931 this.$form.find('page').each(function() {
932 if (!$(this).parents('field').length) {
933 $(this).wrapInner('<group col="4"/>');
937 selector = 'form[version!="7.0"] page,form[version!="7.0"]';
939 render_to: function($target) {
941 this.$target = $target;
943 // TODO: I know this will save the world and all the kitten for a moment,
944 // but one day, we will have to get rid of xml2json
945 var xml = instance.web.json_node_to_xml(this.fvg.arch);
946 this.$form = $('<div class="oe_form">' + xml + '</div>');
948 this.process_version();
950 this.fields_to_init = [];
951 this.tags_to_init = [];
953 this.process(this.$form);
955 this.$form.appendTo(this.$target);
957 _.each(this.fields_to_init, function($elem) {
958 var name = $elem.attr("name");
959 if (!self.fvg.fields[name]) {
960 throw new Error("Field '" + name + "' specified in view could not be found.");
962 var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
964 throw new Error("Widget type '"+ $elem.attr('widget') + "' is not implemented");
966 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
967 var $label = self.labels[$elem.attr("name")];
969 w.set_input_id($label.attr("for"));
972 self.view.register_field(w, $elem.attr("name"));
975 _.each(this.tags_to_init, function($elem) {
976 var tag_name = $elem[0].tagName.toLowerCase();
977 var obj = self.tags_registry.get_object(tag_name);
978 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
981 // TODO: return a deferred
983 render_element: function(template /* dictionaries */) {
984 var dicts = [].slice.call(arguments).slice(1);
985 var dict = _.extend.apply(_, dicts);
986 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
987 return $(QWeb.render(template, dict));
989 alter_field: function(field) {
991 toggle_layout_debugging: function() {
992 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
993 this.$target.find('[title]').removeAttr('title');
994 this.$target.find('.oe_form_group_cell').each(function() {
995 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
996 $(this).attr('title', text);
999 this.$target.toggleClass('oe_layout_debugging');
1001 process: function($tag) {
1003 var tagname = $tag[0].nodeName.toLowerCase();
1004 if (this.tags_registry.contains(tagname)) {
1005 this.tags_to_init.push($tag);
1008 var fn = self['process_' + tagname];
1010 var args = [].slice.call(arguments);
1012 return fn.apply(self, args);
1014 // generic tag handling, just process children
1015 $tag.children().each(function() {
1016 self.process($(this));
1018 self.handle_common_properties($tag, $tag);
1019 $tag.removeAttr("modifiers");
1023 process_sheet: function($sheet) {
1024 var $new_sheet = this.render_element('FormRenderingSheet', $sheet.getAttributes());
1025 this.handle_common_properties($new_sheet, $sheet);
1026 var $dst = $new_sheet.find('.oe_form_sheet');
1027 $sheet.contents().appendTo($dst);
1028 $sheet.before($new_sheet).remove();
1029 this.process($new_sheet);
1031 process_form: function($form) {
1032 if ($form.find('> sheet').length === 0) {
1033 $form.addClass('oe_form_nosheet');
1035 var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
1036 this.handle_common_properties($new_form, $form);
1037 $form.contents().appendTo($new_form);
1038 if ($form[0] === this.$form[0]) {
1039 // If root element, replace it
1040 this.$form = $new_form;
1042 $form.before($new_form).remove();
1044 this.process($new_form);
1047 * Used by direct <field> children of a <group> tag only
1048 * This method will add the implicit <label...> for every field
1051 preprocess_field: function($field) {
1053 var name = $field.attr('name'),
1054 field_colspan = parseInt($field.attr('colspan'), 10),
1055 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1057 if ($field.attr('nolabel') === '1')
1059 $field.attr('nolabel', '1');
1061 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1062 $(el).parents().each(function(unused, tag) {
1063 var name = tag.tagName.toLowerCase();
1064 if (name === "field" || name in self.tags_registry.map)
1071 $label = $('<label/>').attr({
1073 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1074 "string": $field.attr('string'),
1075 "help": $field.attr('help'),
1076 "class": $field.attr('class'),
1078 $label.insertBefore($field);
1079 if (field_colspan > 1) {
1080 $field.attr('colspan', field_colspan - 1);
1084 process_field: function($field) {
1085 if ($field.parent().is('group')) {
1086 // No implicit labels for normal fields, only for <group> direct children
1087 var $label = this.preprocess_field($field);
1089 this.process($label);
1092 this.fields_to_init.push($field);
1095 process_group: function($group) {
1097 $group.children('field').each(function() {
1098 self.preprocess_field($(this));
1100 var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
1102 if ($new_group.first().is('table.oe_form_group')) {
1103 $table = $new_group;
1104 } else if ($new_group.filter('table.oe_form_group').length) {
1105 $table = $new_group.filter('table.oe_form_group').first();
1107 $table = $new_group.find('table.oe_form_group').first();
1111 cols = parseInt($group.attr('col') || 2, 10),
1115 $group.children().each(function(a,b,c) {
1116 var $child = $(this);
1117 var colspan = parseInt($child.attr('colspan') || 1, 10);
1118 var tagName = $child[0].tagName.toLowerCase();
1119 var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1120 var newline = tagName === 'newline';
1122 // Note FME: those classes are used in layout debug mode
1123 if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1124 $tr.addClass('oe_form_group_row_incomplete');
1126 $tr.addClass('oe_form_group_row_newline');
1133 if (!$tr || row_cols < colspan) {
1134 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1137 row_cols -= colspan;
1139 // invisibility transfer
1140 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1141 var invisible = field_modifiers.invisible;
1142 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1144 $tr.append($td.append($child));
1145 children.push($child[0]);
1147 if (row_cols && $td) {
1148 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1150 $group.before($new_group).remove();
1152 $table.find('> tbody > tr').each(function() {
1153 var to_compute = [],
1156 $(this).children().each(function() {
1158 $child = $td.children(':first');
1159 switch ($child[0].tagName.toLowerCase()) {
1161 if ($child.attr('orientation') === 'vertical') {
1162 $td.addClass('oe_vertical_separator').attr('width', '1');
1164 row_cols-= $td.attr('colspan') || 1;
1169 if ($child.attr('for')) {
1170 $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1171 row_cols-= $td.attr('colspan') || 1;
1176 var width = _.str.trim($child.attr('width') || ''),
1177 iwidth = parseInt(width, 10);
1179 if (width.substr(-1) === '%') {
1181 width = iwidth + '%';
1184 $td.css('min-width', width + 'px');
1186 $td.attr('width', width);
1187 $child.removeAttr('width');
1188 row_cols-= $td.attr('colspan') || 1;
1190 to_compute.push($td);
1196 var unit = Math.floor(total / row_cols);
1197 if (!$(this).is('.oe_form_group_row_incomplete')) {
1198 _.each(to_compute, function($td, i) {
1199 var width = parseInt($td.attr('colspan'), 10) * unit;
1200 $td.attr('width', width + '%');
1206 _.each(children, function(el) {
1207 self.process($(el));
1209 this.handle_common_properties($new_group, $group);
1212 process_notebook: function($notebook) {
1215 $notebook.find('> page').each(function() {
1216 var $page = $(this);
1217 var page_attrs = $page.getAttributes();
1218 page_attrs.id = _.uniqueId('notebook_page_');
1219 var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
1220 $page.contents().appendTo($new_page);
1221 $page.before($new_page).remove();
1222 var ic = self.handle_common_properties($new_page, $page).invisibility_changer;
1223 page_attrs.__page = $new_page;
1224 page_attrs.__ic = ic;
1225 pages.push(page_attrs);
1227 $new_page.children().each(function() {
1228 self.process($(this));
1231 var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
1232 $notebook.contents().appendTo($new_notebook);
1233 $notebook.before($new_notebook).remove();
1234 self.process($($new_notebook.children()[0]));
1235 //tabs and invisibility handling
1236 $new_notebook.tabs();
1237 _.each(pages, function(page, i) {
1240 page.__ic.on("change:effective_invisible", null, function() {
1241 var current = $new_notebook.tabs("option", "selected");
1242 if (! pages[current].__ic || ! pages[current].__ic.get("effective_invisible"))
1244 var first_visible = _.find(_.range(pages.length), function(i2) {
1245 return (! pages[i2].__ic) || (! pages[i2].__ic.get("effective_invisible"));
1247 if (first_visible !== undefined) {
1248 $new_notebook.tabs('select', first_visible);
1253 this.handle_common_properties($new_notebook, $notebook);
1254 return $new_notebook;
1256 process_separator: function($separator) {
1257 var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
1258 $separator.before($new_separator).remove();
1259 this.handle_common_properties($new_separator, $separator);
1260 return $new_separator;
1262 process_label: function($label) {
1263 var name = $label.attr("for"),
1264 field_orm = this.fvg.fields[name];
1266 string: $label.attr('string') || (field_orm || {}).string || '',
1267 help: $label.attr('help') || (field_orm || {}).help || '',
1268 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1270 var align = parseFloat(dict.align);
1271 if (isNaN(align) || align === 1) {
1273 } else if (align === 0) {
1279 var $new_label = this.render_element('FormRenderingLabel', dict);
1280 $label.before($new_label).remove();
1281 this.handle_common_properties($new_label, $label);
1283 this.labels[name] = $new_label;
1287 handle_common_properties: function($new_element, $node) {
1288 var str_modifiers = $node.attr("modifiers") || "{}"
1289 var modifiers = JSON.parse(str_modifiers);
1291 if (modifiers.invisible !== undefined)
1292 ic = new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1293 $new_element.addClass($node.attr("class") || "");
1294 $new_element.attr('style', $node.attr('style'));
1295 return {invisibility_changer: ic,};
1299 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1300 alter_field: function(field) {
1301 field.set({"force_readonly": true});
1305 instance.web.form.FormDialog = instance.web.Dialog.extend({
1306 init: function(parent, options, view_id, dataset) {
1307 this._super(parent, options);
1308 this.dataset = dataset;
1309 this.view_id = view_id;
1314 this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1317 this.form.appendTo(this.$element);
1318 this.form.on_created.add_last(this.on_form_dialog_saved);
1319 this.form.on_saved.add_last(this.on_form_dialog_saved);
1322 select_id: function(id) {
1323 if (this.form.dataset.select_id(id)) {
1324 return this.form.do_show();
1326 this.do_warn("Could not find id in dataset");
1327 return $.Deferred().reject();
1330 on_form_dialog_saved: function(r) {
1335 instance.web.form.compute_domain = function(expr, fields) {
1337 for (var i = expr.length - 1; i >= 0; i--) {
1339 if (ex.length == 1) {
1340 var top = stack.pop();
1343 stack.push(stack.pop() || top);
1346 stack.push(stack.pop() && top);
1352 throw new Error(_.str.sprintf(
1353 _t("Unknown operator %s in domain %s"),
1354 ex, JSON.stringify(expr)));
1358 var field = fields[ex[0]];
1360 throw new Error(_.str.sprintf(
1361 _t("Unknown field %s in domain %s"),
1362 ex[0], JSON.stringify(expr)));
1364 var field_value = field.get_value ? field.get_value() : field.value;
1368 switch (op.toLowerCase()) {
1371 stack.push(field_value == val);
1375 stack.push(field_value != val);
1378 stack.push(field_value < val);
1381 stack.push(field_value > val);
1384 stack.push(field_value <= val);
1387 stack.push(field_value >= val);
1390 if (!_.isArray(val)) val = [val];
1391 stack.push(_(val).contains(field_value));
1394 if (!_.isArray(val)) val = [val];
1395 stack.push(!_(val).contains(field_value));
1399 _t("Unsupported operator %s in domain %s"),
1400 op, JSON.stringify(expr));
1403 return _.all(stack, _.identity);
1407 * Must be applied over an class already possessing the PropertiesMixin.
1409 * Apply the result of the "invisible" domain to this.$element.
1411 instance.web.form.InvisibilityChangerMixin = {
1412 init: function(field_manager, invisible_domain) {
1413 this._ic_field_manager = field_manager
1414 this._ic_invisible_modifier = invisible_domain;
1415 this._ic_field_manager.on("view_content_has_changed", this, function() {
1416 var result = this._ic_invisible_modifier === undefined ? false :
1417 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1418 this.set({"invisible": result});
1420 this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1421 var check = function() {
1422 if (this.get("invisible") || this.get('force_invisible')) {
1423 this.set({"effective_invisible": true});
1425 this.set({"effective_invisible": false});
1428 this.on('change:invisible', this, check);
1429 this.on('change:force_invisible', this, check);
1430 _.bind(check, this)();
1433 this.on("change:effective_invisible", this, this._check_visibility);
1434 this._check_visibility();
1436 _check_visibility: function() {
1437 this.$element.toggleClass('oe_form_invisible', this.get("effective_invisible"));
1441 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1442 init: function(parent, field_manager, invisible_domain, $element) {
1443 this.setParent(parent);
1444 instance.web.PropertiesMixin.init.call(this);
1445 instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1446 this.$element = $element;
1451 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1453 * @constructs instance.web.form.FormWidget
1454 * @extends instance.web.Widget
1459 init: function(view, node) {
1463 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1464 instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1466 this.view.on("view_content_has_changed", this, this.process_modifiers);
1468 renderElement: function() {
1470 this.$element.addClass(this.node.attrs["class"] || "");
1472 destroy: function() {
1474 this._super.apply(this, arguments);
1476 process_modifiers: function() {
1477 var compute_domain = instance.web.form.compute_domain;
1479 for (var a in this.modifiers) {
1480 if (!_.include(["invisible"], a)) {
1481 var val = compute_domain(this.modifiers[a], this.view.fields);
1487 do_attach_tooltip: function(widget, trigger, options) {
1488 widget = widget || this;
1489 trigger = trigger || this.$element;
1490 options = _.extend({
1495 var template = widget.template + '.tooltip';
1496 if (!QWeb.has_template(template)) {
1497 template = 'WidgetLabel.tooltip';
1499 return QWeb.render(template, {
1500 debug: instance.connection.debug,
1503 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1508 $(trigger).tipsy(options);
1510 _build_view_fields_values: function(blacklist) {
1511 var a_dataset = this.view.dataset;
1512 var fields_values = this.view.get_fields_values(blacklist);
1513 var active_id = a_dataset.ids[a_dataset.index];
1514 _.extend(fields_values, {
1515 active_id: active_id || false,
1516 active_ids: active_id ? [active_id] : [],
1517 active_model: a_dataset.model,
1520 if (a_dataset.parent_view) {
1521 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1523 return fields_values;
1525 _build_eval_context: function(blacklist) {
1526 var a_dataset = this.view.dataset;
1527 return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1530 * Builds a new context usable for operations related to fields by merging
1531 * the fields'context with the action's context.
1533 build_context: function(blacklist) {
1534 // only use the model's context if there is not context on the node
1535 var v_context = this.node.attrs.context;
1537 v_context = (this.field || {}).context || {};
1540 if (v_context.__ref || true) { //TODO: remove true
1541 var fields_values = this._build_eval_context(blacklist);
1542 v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1546 build_domain: function() {
1547 var f_domain = this.field.domain || [];
1548 var n_domain = this.node.attrs.domain || null;
1549 // if there is a domain on the node, overrides the model's domain
1550 var final_domain = n_domain !== null ? n_domain : f_domain;
1551 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1552 var fields_values = this._build_eval_context();
1553 final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1555 return final_domain;
1559 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1560 template: 'WidgetButton',
1561 init: function(view, node) {
1562 this._super(view, node);
1563 this.force_disabled = false;
1564 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1565 if (this.node.attrs.default_focus == '1') {
1566 // TODO fme: provide enter key binding to widgets
1567 this.view.default_focus_button = this;
1569 this.view.on('view_content_has_changed', this, this.check_disable);
1572 this._super.apply(this, arguments);
1573 this.$element.click(this.on_click);
1574 if (this.node.attrs.help || instance.connection.debug) {
1575 this.do_attach_tooltip();
1578 on_click: function() {
1580 this.force_disabled = true;
1581 this.check_disable();
1582 this.execute_action().always(function() {
1583 self.force_disabled = false;
1584 self.check_disable();
1587 execute_action: function() {
1589 var exec_action = function() {
1590 if (self.node.attrs.confirm) {
1591 var def = $.Deferred();
1592 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1593 title: _t('Confirm'),
1596 {text: _t("Cancel"), click: function() {
1598 $(this).dialog("close");
1601 {text: _t("Ok"), click: function() {
1602 self.on_confirmed().then(function() {
1605 $(this).dialog("close");
1610 return def.promise();
1612 return self.on_confirmed();
1615 if (!this.node.attrs.special) {
1616 this.view.force_dirty = true;
1617 return this.view.recursive_save().pipe(exec_action);
1619 return exec_action();
1622 on_confirmed: function() {
1625 var context = this.node.attrs.context;
1626 if (context && context.__ref) {
1627 context = new instance.web.CompoundContext(context);
1628 context.set_eval_context(this._build_eval_context());
1631 return this.view.do_execute_action(
1632 _.extend({}, this.node.attrs, {context: context}),
1633 this.view.dataset, this.view.datarecord.id, function () {
1637 check_disable: function() {
1638 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1639 this.$element.prop('disabled', disabled);
1640 this.$element.css('color', disabled ? 'grey' : '');
1645 * Interface to be implemented by fields.
1648 * - readonly: boolean. If set to true the field should appear in readonly mode.
1649 * - force_readonly: boolean, When it is true, the field should always appear
1650 * in read only mode, no matter what the value of the "readonly" property can be.
1652 * - changed_value: triggered to inform the view to check on_changes
1655 instance.web.form.FieldMixin = {
1657 * Constructor takes 2 arguments:
1658 * - field_manager: Implements FieldManagerMixin
1659 * - node: the "<field>" node in json form
1661 init: function(field_manager, node) {},
1663 * Called by the form view to indicate the value of the field.
1665 * set_value() may return an object that can be passed to $.when() that represents the moment when
1666 * the field has finished all operations necessary before the user can effectively use the widget.
1668 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1669 * regardless of any asynchronous operation currently running and the status of any promise that a
1670 * previous call to set_value() could have returned.
1672 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1673 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1674 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1675 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1676 * no information is ever given to know which format is used.
1678 set_value: function(value_) {},
1680 * Get the current value of the widget.
1682 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1683 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1684 * For example if the field is marqued as "required", a call to get_value() can return false.
1686 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1687 * return a defaut value according to the type of field.
1689 * This method is always assumed to perform synchronously, it can not return a promise.
1691 * If there was no user interaction to modify the value of the field, it is always assumed that
1692 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1693 * altough the syntax can be different. This can be the case for type of fields that have a different
1694 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1696 get_value: function() {},
1698 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1701 set_input_id: function(id) {},
1703 * Returns true if is_syntax_valid() returns true and the value is semantically
1704 * valid too according to the semantic restrictions applied to the field.
1706 is_valid: function() {},
1708 * Returns true if the field holds a value which is syntaxically correct, ignoring
1709 * the potential semantic restrictions applied to the field.
1711 is_syntax_valid: function() {},
1713 * Must set the focus on the field.
1715 focus: function() {},
1719 * Abstract class for classes implementing FieldMixin.
1722 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1723 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1724 * - value: useful property to hold the value of the field. By default, set_value() and get_value()
1725 * set and retrieve the value property. Changing the value property also triggers automatically
1726 * a 'changed_value' event that inform the view to trigger on_changes.
1729 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1731 * @constructs instance.web.form.AbstractField
1732 * @extends instance.web.form.FormWidget
1734 * @param field_manager
1737 init: function(field_manager, node) {
1738 this._super(field_manager, node);
1739 this.field_manager = field_manager;
1740 this.name = this.node.attrs.name;
1741 this.set({'value': false});
1742 this.field = this.field_manager.get_field(this.name);
1743 this.set({required: this.modifiers['required'] === true});
1745 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1747 this.set({"readonly": this.modifiers['readonly'] === true});
1748 var test_effective_readonly = function() {
1749 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1751 this.on("change:readonly", this, test_effective_readonly);
1752 this.on("change:force_readonly", this, test_effective_readonly);
1753 _.bind(test_effective_readonly, this)();
1755 this.on("change:value", this, function() {
1756 if (! this._inhibit_on_change)
1757 this.trigger('changed_value');
1758 this._check_css_flags();
1761 renderElement: function() {
1764 if (this.field.translate) {
1765 this.$element.addClass('oe_form_field_translatable');
1766 this.$element.find('.oe_field_translate').click(_.bind(function() {
1767 this.field_manager.open_translate_dialog(this);
1770 this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1771 if (instance.connection.debug) {
1772 this.do_attach_tooltip(this, this.$label[0] || this.$element);
1773 this.$label.off('dblclick').on('dblclick', function() {
1774 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1776 console.log("window.w =", window.w);
1779 if (!this.disable_utility_classes) {
1780 this.off("change:required", this, this._set_required);
1781 this.on("change:required", this, this._set_required);
1782 this._set_required();
1784 this._check_visibility();
1785 this._check_css_flags();
1788 * Private. Do not use.
1790 _set_required: function() {
1791 this.$element.toggleClass('oe_form_required', this.get("required"));
1793 set_value: function(value_) {
1794 this._inhibit_on_change = true;
1795 this.set({'value': value_});
1796 this._inhibit_on_change = false;
1798 get_value: function() {
1799 return this.get('value');
1801 is_valid: function() {
1802 return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1804 is_syntax_valid: function() {
1808 * Method useful to implement to ease validity testing. Must return true if the current
1809 * value is similar to false in OpenERP.
1811 is_false: function() {
1812 return this.get('value') === false;
1814 _check_css_flags: function(show_invalid) {
1815 if (this.field.translate) {
1816 this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1818 if (!this.disable_utility_classes) {
1819 if (this.field_manager.get('display_invalid_fields')) {
1820 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1827 * Utility method to focus an element, but only after a small amount of time.
1829 delay_focus: function($elem) {
1830 setTimeout(function() {
1835 * Utility method to get the widget options defined in the field xml description.
1837 get_definition_options: function() {
1838 if (!this.definition_options) {
1839 var str = this.node.attrs.options || '{}';
1840 this.definition_options = JSON.parse(str);
1842 return this.definition_options;
1844 set_input_id: function(id) {
1845 this.id_for_label = id;
1850 * A mixin to apply on any field that has to completely re-render when its readonly state
1853 instance.web.form.ReinitializeFieldMixin = {
1855 * Default implementation of start(), use it or call explicitly initialize_field().
1859 this.initialize_field();
1861 initialize_field: function() {
1862 this.on("change:effective_readonly", this, function() {
1863 this.destroy_content();
1864 this.renderElement();
1865 this.initialize_content();
1866 this.render_value();
1868 this.initialize_content();
1869 this.render_value();
1872 * Called to destroy anything that could have been created previously, called before a
1873 * re-initialization.
1875 destroy_content: function() {},
1877 * Called to initialize the content.
1879 initialize_content: function() {},
1881 * Called to render the value. Should also be explicitly called at the end of a set_value().
1883 render_value: function() {},
1886 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1887 template: 'FieldChar',
1888 widget_class: 'oe_form_field_char',
1889 init: function (field_manager, node) {
1890 this._super(field_manager, node);
1891 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1893 initialize_content: function() {
1895 this.$element.find('input').change(function() {
1896 self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1899 set_value: function(value_) {
1900 this._super(value_);
1901 this.render_value();
1903 render_value: function() {
1904 var show_value = instance.web.format_value(this.get('value'), this, '');
1905 if (!this.get("effective_readonly")) {
1906 this.$element.find('input').val(show_value);
1908 if (this.password) {
1909 show_value = new Array(show_value.length + 1).join('*');
1911 this.$element.text(show_value);
1914 is_syntax_valid: function() {
1915 if (!this.get("effective_readonly")) {
1917 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1925 is_false: function() {
1926 return this.get('value') === '' || this._super();
1929 this.delay_focus(this.$element.find('input:first'));
1933 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1937 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1938 template: 'FieldEmail',
1939 initialize_content: function() {
1941 this.$element.find('button').click(this.on_button_clicked);
1943 render_value: function() {
1944 if (!this.get("effective_readonly")) {
1947 this.$element.find('a')
1948 .attr('href', 'mailto:' + this.get('value'))
1949 .text(this.get('value'));
1952 on_button_clicked: function() {
1953 if (!this.get('value') || !this.is_syntax_valid()) {
1954 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1956 location.href = 'mailto:' + this.get('value');
1961 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1962 template: 'FieldUrl',
1963 initialize_content: function() {
1965 this.$element.find('button').click(this.on_button_clicked);
1967 render_value: function() {
1968 if (!this.get("effective_readonly")) {
1971 var tmp = this.get('value');
1972 var s = /(\w+):(.+)/.exec(tmp);
1974 tmp = "http://" + this.get('value');
1976 this.$element.find('a').attr('href', tmp).text(tmp);
1979 on_button_clicked: function() {
1980 if (!this.get('value')) {
1981 this.do_warn("Resource error", "This resource is empty");
1983 var url = $.trim(this.get('value'));
1984 if(/^www\./i.test(url))
1985 url = 'http://'+url;
1991 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1992 is_field_number: true,
1993 widget_class: 'oe_form_field_float',
1994 init: function (field_manager, node) {
1995 this._super(field_manager, node);
1996 this.set({'value': 0});
1997 if (this.node.attrs.digits) {
1998 this.digits = py.eval(node.attrs.digits);
2000 this.digits = this.field.digits;
2003 set_value: function(value_) {
2004 if (value_ === false || value_ === undefined) {
2005 // As in GTK client, floats default to 0
2008 this._super.apply(this, [value_]);
2012 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
2013 template: "web.datepicker",
2014 jqueryui_object: 'datetimepicker',
2015 type_of_date: "datetime",
2016 init: function(parent) {
2017 this._super(parent);
2018 this.name = parent.name;
2022 this.$input = this.$element.find('input.oe_datepicker_master');
2023 this.$input_picker = this.$element.find('input.oe_datepicker_container');
2024 this.$input.change(this.on_change);
2026 onSelect: this.on_picker_select,
2030 showButtonPanel: true
2032 this.$element.find('img.oe_datepicker_trigger').click(function() {
2033 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
2034 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
2035 self.$input_picker.show();
2036 self.picker('show');
2037 self.$input_picker.hide();
2040 this.set_readonly(false);
2041 this.set({'value': false});
2043 picker: function() {
2044 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
2046 on_picker_select: function(text, instance_) {
2047 var date = this.picker('getDate');
2048 this.$input.val(date ? this.format_client(date) : '').change();
2050 set_value: function(value_) {
2051 this.set({'value': value_});
2052 this.$input.val(value_ ? this.format_client(value_) : '');
2054 get_value: function() {
2055 return this.get('value');
2057 set_value_from_ui_: function() {
2058 var value_ = this.$input.val() || false;
2059 this.set({'value': this.parse_client(value_)});
2061 set_readonly: function(readonly) {
2062 this.readonly = readonly;
2063 this.$input.prop('readonly', this.readonly);
2064 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2066 is_valid_: function() {
2067 var value_ = this.$input.val();
2068 if (value_ === "") {
2072 this.parse_client(value_);
2079 parse_client: function(v) {
2080 return instance.web.parse_value(v, {"widget": this.type_of_date});
2082 format_client: function(v) {
2083 return instance.web.format_value(v, {"widget": this.type_of_date});
2085 on_change: function() {
2086 if (this.is_valid_()) {
2087 this.set_value_from_ui_();
2092 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2093 jqueryui_object: 'datepicker',
2094 type_of_date: "date"
2097 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2098 template: "FieldDatetime",
2099 build_widget: function() {
2100 return new instance.web.DateTimeWidget(this);
2102 destroy_content: function() {
2103 if (this.datewidget) {
2104 this.datewidget.destroy();
2105 this.datewidget = undefined;
2108 initialize_content: function() {
2109 if (!this.get("effective_readonly")) {
2110 this.datewidget = this.build_widget();
2111 this.datewidget.on_change.add_last(_.bind(function() {
2112 this.set({'value': this.datewidget.get_value()});
2114 this.datewidget.appendTo(this.$element);
2117 set_value: function(value_) {
2118 this._super(value_);
2119 this.render_value();
2121 render_value: function() {
2122 if (!this.get("effective_readonly")) {
2123 this.datewidget.set_value(this.get('value'));
2125 this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2128 is_syntax_valid: function() {
2129 if (!this.get("effective_readonly")) {
2130 return this.datewidget.is_valid_();
2134 is_false: function() {
2135 return this.get('value') === '' || this._super();
2138 if (this.datewidget && this.datewidget.$input)
2139 this.delay_focus(this.datewidget.$input);
2143 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2144 template: "FieldDate",
2145 build_widget: function() {
2146 return new instance.web.DateWidget(this);
2150 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2151 template: 'FieldText',
2152 initialize_content: function() {
2153 this.$textarea = this.$element.find('textarea');
2154 if (!this.get("effective_readonly")) {
2155 this.$textarea.change(_.bind(function() {
2156 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2159 this.$textarea.attr('disabled', 'disabled');
2162 set_value: function(value_) {
2163 this._super.apply(this, arguments);
2164 this.render_value();
2166 render_value: function() {
2167 var show_value = instance.web.format_value(this.get('value'), this, '');
2168 this.$textarea.val(show_value);
2169 if (show_value && this.view.options.resize_textareas) {
2170 this.do_resize(this.view.options.resize_textareas);
2173 is_syntax_valid: function() {
2174 if (!this.get("effective_readonly")) {
2176 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2184 is_false: function() {
2185 return this.get('value') === '' || this._super();
2187 focus: function($element) {
2188 this.delay_focus(this.$textarea);
2190 do_resize: function(max_height) {
2191 max_height = parseInt(max_height, 10);
2192 var $input = this.$textarea,
2193 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2195 $div.text($input.val());
2196 _.each('font-family,font-size,white-space'.split(','), function(style) {
2197 $div.css(style, $input.css(style));
2199 $div.appendTo($('body'));
2200 new_height = $div.height();
2201 if (new_height < 90) {
2204 if (!isNaN(max_height) && new_height > max_height) {
2205 new_height = max_height;
2208 $input.height(new_height);
2212 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2213 template: 'FieldBoolean',
2215 this._super.apply(this, arguments);
2216 this.$checkbox = $("input", this.$element);
2217 this.$element.click(_.bind(function() {
2218 this.set({'value': this.$checkbox.is(':checked')});
2220 var check_readonly = function() {
2221 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2223 this.on("change:effective_readonly", this, check_readonly);
2224 _.bind(check_readonly, this)();
2226 set_value: function(value_) {
2227 this._super.apply(this, arguments);
2228 this.$checkbox[0].checked = value_;
2231 this.delay_focus(this.$checkbox);
2235 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2236 template: 'FieldProgressBar',
2238 this._super.apply(this, arguments);
2239 this.$element.progressbar({
2240 value: this.get('value'),
2241 disabled: this.get("effective_readonly")
2244 set_value: function(value_) {
2245 this._super.apply(this, arguments);
2246 var show_value = Number(value_);
2247 if (isNaN(show_value)) {
2250 var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2251 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2255 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2256 // to replace view editor
2259 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2260 template: 'FieldSelection',
2261 init: function(field_manager, node) {
2263 this._super(field_manager, node);
2264 this.values = _.clone(this.field.selection);
2265 _.each(this.values, function(v, i) {
2266 if (v[0] === false && v[1] === '') {
2267 self.values.splice(i, 1);
2270 this.values.unshift([false, '']);
2272 initialize_content: function() {
2273 // Flag indicating whether we're in an event chain containing a change
2274 // event on the select, in order to know what to do on keyup[RETURN]:
2275 // * If the user presses [RETURN] as part of changing the value of a
2276 // selection, we should just let the value change and not let the
2277 // event broadcast further (e.g. to validating the current state of
2278 // the form in editable list view, which would lead to saving the
2279 // current row or switching to the next one)
2280 // * If the user presses [RETURN] with a select closed (side-effect:
2281 // also if the user opened the select and pressed [RETURN] without
2282 // changing the selected value), takes the action as validating the
2284 var ischanging = false;
2285 this.$element.find('select')
2286 .change(_.bind(function() {
2287 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2289 .change(function () { ischanging = true; })
2290 .click(function () { ischanging = false; })
2291 .keyup(function (e) {
2292 if (e.which !== 13 || !ischanging) { return; }
2293 e.stopPropagation();
2297 set_value: function(value_) {
2298 value_ = value_ === null ? false : value_;
2299 value_ = value_ instanceof Array ? value_[0] : value_;
2300 this._super(value_);
2301 this.render_value();
2303 render_value: function() {
2304 if (!this.get("effective_readonly")) {
2306 for (var i = 0, ii = this.values.length; i < ii; i++) {
2307 if (this.values[i][0] === this.get('value')) index = i;
2309 this.$element.find('select')[0].selectedIndex = index;
2312 var option = _(this.values)
2313 .detect(function (record) { return record[0] === self.get('value'); });
2314 this.$element.text(option ? option[1] : this.values[0][1]);
2317 is_syntax_valid: function() {
2318 if (this.get("effective_readonly")) {
2321 var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2325 this.delay_focus(this.$element.find('select:first'));
2329 // jquery autocomplete tweak to allow html
2331 var proto = $.ui.autocomplete.prototype,
2332 initSource = proto._initSource;
2334 function filter( array, term ) {
2335 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2336 return $.grep( array, function(value_) {
2337 return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2342 _initSource: function() {
2343 if ( this.options.html && $.isArray(this.options.source) ) {
2344 this.source = function( request, response ) {
2345 response( filter( this.options.source, request.term ) );
2348 initSource.call( this );
2352 _renderItem: function( ul, item) {
2353 return $( "<li></li>" )
2354 .data( "item.autocomplete", item )
2355 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2362 * A mixin containing some useful methods to handle completion inputs.
2364 instance.web.form.CompletionFieldMixin = {
2367 this.orderer = new instance.web.DropMisordered();
2370 * Call this method to search using a string.
2372 get_search_result: function(search_val) {
2375 var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2376 var blacklist = this.get_search_blacklist();
2378 return this.orderer.add(dataset.name_search(
2379 search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
2380 'ilike', this.limit + 1)).pipe(function(data) {
2381 self.last_search = data;
2382 // possible selections for the m2o
2383 var values = _.map(data, function(x) {
2385 label: _.str.escapeHTML(x[1]),
2392 // search more... if more results that max
2393 if (values.length > self.limit) {
2394 values = values.slice(0, self.limit);
2395 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2396 dataset.name_search(search_val, self.build_domain(), 'ilike'
2397 , false, function(data) {
2398 self._search_create_popup("search", data);
2403 var raw_result = _(data.result).map(function(x) {return x[1];});
2404 if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2405 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2406 $('<span />').text(search_val).html()), action: function() {
2407 self._quick_create(search_val);
2411 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2412 self._search_create_popup("form", undefined, {"default_name": search_val});
2418 get_search_blacklist: function() {
2421 _quick_create: function(name) {
2423 var slow_create = function () {
2424 self._search_create_popup("form", undefined, {"default_name": name});
2426 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2427 new instance.web.DataSet(this, this.field.relation, self.build_context())
2428 .name_create(name, function(data) {
2429 self.add_id(data[0]);
2430 }).fail(function(error, event) {
2431 event.preventDefault();
2437 // all search/create popup handling
2438 _search_create_popup: function(view, ids, context) {
2440 var pop = new instance.web.form.SelectCreatePopup(this);
2442 self.field.relation,
2444 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2445 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2447 disable_multiple_selection: true
2449 self.build_domain(),
2450 new instance.web.CompoundContext(self.build_context(), context || {})
2452 pop.on_select_elements.add(function(element_ids) {
2453 self.add_id(element_ids[0]);
2459 add_id: function(id) {},
2462 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2463 instance.web.form.CompletionFieldMixin, {
2464 template: "FieldMany2One",
2465 init: function(field_manager, node) {
2466 this._super(field_manager, node);
2467 instance.web.form.CompletionFieldMixin.init.call(this);
2468 this.set({'value': false});
2469 this.display_value = {};
2470 this.last_search = [];
2471 this.floating = false;
2472 this.inhibit_on_change = false;
2476 instance.web.form.ReinitializeFieldMixin.start.call(this);
2477 this.on("change:value", this, function() {
2478 this.floating = false;
2479 this.render_value();
2482 initialize_content: function() {
2483 if (!this.get("effective_readonly"))
2484 this.render_editable();
2485 this.render_value();
2487 render_editable: function() {
2489 this.$input = this.$element.find("input");
2493 return "No element was selected, you should create or select one from the dropdown list.";
2499 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2500 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2502 this.$follow_button.click(function() {
2503 if (!self.get('value')) {
2506 var pop = new instance.web.form.FormOpenPopup(self.view);
2508 self.field.relation,
2510 self.build_context(),
2512 title: _t("Open: ") + (self.string || self.name)
2515 pop.on_write_completed.add_last(function() {
2516 self.display_value = {};
2517 self.render_value();
2521 // some behavior for input
2522 this.$input.keyup(function() {
2523 if (self.$input.val() === "") {
2524 self.set({value: false});
2526 self.floating = true;
2529 this.$drop_down.click(function() {
2530 if (self.$input.autocomplete("widget").is(":visible")) {
2531 self.$input.autocomplete("close");
2533 if (self.get("value") && ! self.floating) {
2534 self.$input.autocomplete("search", "");
2536 self.$input.autocomplete("search");
2538 self.$input.focus();
2541 var tip_def = $.Deferred();
2542 var untip_def = $.Deferred();
2543 var tip_delay = 200;
2544 var tip_duration = 3000;
2545 var anyoneLoosesFocus = function() {
2547 if (self.floating) {
2548 if (self.last_search.length > 0) {
2549 if (self.last_search[0][0] != self.get("value")) {
2550 self.display_value = {};
2551 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2552 self.set({value: self.last_search[0][0]});
2555 self.render_value();
2559 self.set({value: false});
2560 self.render_value();
2562 self.floating = false;
2567 tip_def = $.Deferred();
2568 tip_def.then(function() {
2569 self.$input.tipsy("show");
2571 setTimeout(function() {
2574 untip_def = $.Deferred();
2575 untip_def.then(function() {
2576 self.$input.tipsy("hide");
2578 setTimeout(function() {untip_def.resolve();}, tip_duration);
2584 this.$input.focusout(anyoneLoosesFocus);
2586 var isSelecting = false;
2588 this.$input.autocomplete({
2589 source: function(req, resp) {
2590 self.get_search_result(req.term).then(function(result) {
2594 select: function(event, ui) {
2598 self.display_value = {};
2599 self.display_value["" + item.id] = item.name;
2600 self.set({value: item.id});
2601 } else if (item.action) {
2602 self.floating = true;
2607 focus: function(e, ui) {
2611 // disabled to solve a bug, but may cause others
2612 //close: anyoneLoosesFocus,
2616 this.$input.autocomplete("widget").addClass("openerp");
2617 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2618 this.$input.keyup(function(e) {
2619 if (e.which === 13) {
2621 e.stopPropagation();
2623 isSelecting = false;
2627 render_value: function(no_recurse) {
2629 if (! this.get("value")) {
2630 this.display_string("");
2633 var display = this.display_value["" + this.get("value")];
2635 this.display_string(display);
2639 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2640 dataset.name_get([self.get("value")], function(data) {
2641 self.display_value["" + self.get("value")] = data[0][1];
2642 self.render_value(true);
2646 display_string: function(str) {
2648 if (!this.get("effective_readonly")) {
2649 this.$input.val(str);
2651 this.$element.find('a')
2654 .click(function () {
2656 type: 'ir.actions.act_window',
2657 res_model: self.field.relation,
2658 res_id: self.get("value"),
2659 context: self.build_context(),
2660 views: [[false, 'form']],
2667 set_value: function(value_) {
2669 if (value_ instanceof Array) {
2670 this.display_value = {};
2671 this.display_value["" + value_[0]] = value_[1];
2674 value_ = value_ || false;
2675 this.inhibit_on_change = true;
2676 this._super(value_);
2677 this.inhibit_on_change = false;
2679 add_id: function(id) {
2680 this.display_value = {};
2681 this.set({value: id});
2683 is_false: function() {
2684 return ! this.get("value");
2686 focus: function () {
2687 this.delay_focus(this.$input);
2692 # Values: (0, 0, { fields }) create
2693 # (1, ID, { fields }) update
2694 # (2, ID) remove (delete)
2695 # (3, ID) unlink one (target id or target of relation)
2697 # (5) unlink all (only valid for one2many)
2702 'create': function (values) {
2703 return [commands.CREATE, false, values];
2705 // (1, id, {values})
2707 'update': function (id, values) {
2708 return [commands.UPDATE, id, values];
2712 'delete': function (id) {
2713 return [commands.DELETE, id, false];
2715 // (3, id[, _]) removes relation, but not linked record itself
2717 'forget': function (id) {
2718 return [commands.FORGET, id, false];
2722 'link_to': function (id) {
2723 return [commands.LINK_TO, id, false];
2727 'delete_all': function () {
2728 return [5, false, false];
2730 // (6, _, ids) replaces all linked records with provided ids
2732 'replace_with': function (ids) {
2733 return [6, false, ids];
2736 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2737 multi_selection: false,
2738 disable_utility_classes: true,
2739 init: function(field_manager, node) {
2740 this._super(field_manager, node);
2741 lazy_build_o2m_kanban_view();
2742 this.is_loaded = $.Deferred();
2743 this.initial_is_loaded = this.is_loaded;
2744 this.is_setted = $.Deferred();
2745 this.form_last_update = $.Deferred();
2746 this.init_form_last_update = this.form_last_update;
2749 this._super.apply(this, arguments);
2750 this.$element.addClass('oe_form_field_one2many');
2754 this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2755 this.dataset.o2m = this;
2756 this.dataset.parent_view = this.view;
2757 this.dataset.child_name = this.name;
2758 this.dataset.on_change.add_last(function() {
2759 self.trigger_on_change();
2762 this.is_setted.then(function() {
2765 this.is_loaded.then(function() {
2766 self.on("change:effective_readonly", self, function() {
2767 self.is_loaded = self.is_loaded.pipe(function() {
2768 self.viewmanager.destroy();
2769 return $.when(self.load_views()).then(function() {
2770 self.reload_current_view();
2776 trigger_on_change: function() {
2777 var tmp = this.doing_on_change;
2778 this.doing_on_change = true;
2779 this.trigger('changed_value');
2780 this.doing_on_change = tmp;
2782 load_views: function() {
2785 var modes = this.node.attrs.mode;
2786 modes = !!modes ? modes.split(",") : ["tree"];
2788 _.each(modes, function(mode) {
2789 if (! _.include(["list", "tree", "graph", "kanban"], mode)) {
2790 throw new Error(_.str.sprintf("View type '%s' is not supported in One2Many.", mode));
2794 view_type: mode == "tree" ? "list" : mode,
2797 if (self.field.views && self.field.views[mode]) {
2798 view.embedded_view = self.field.views[mode];
2800 if(view.view_type === "list") {
2801 view.options.selectable = self.multi_selection;
2802 if (self.get("effective_readonly")) {
2803 view.options.addable = null;
2804 view.options.deletable = null;
2806 } else if (view.view_type === "form") {
2807 if (self.get("effective_readonly")) {
2808 view.view_type = 'form';
2810 view.options.not_interactible_on_create = true;
2811 } else if (view.view_type === "kanban") {
2812 view.options.confirm_on_delete = false;
2813 view.options.sortable = false;
2814 if (self.get("effective_readonly")) {
2815 view.options.action_buttons = false;
2816 view.options.quick_creatable = false;
2817 view.options.creatable = false;
2818 view.options.read_only_mode = true;
2825 this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2826 this.viewmanager.$element.addClass("oe_view_manager_one2many");
2827 this.viewmanager.o2m = self;
2828 var once = $.Deferred().then(function() {
2829 self.init_form_last_update.resolve();
2831 var def = $.Deferred().then(function() {
2832 self.initial_is_loaded.resolve();
2834 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2835 controller.o2m = self;
2836 if (view_type == "list") {
2837 if (self.get("effective_readonly"))
2838 controller.set_editable(false);
2839 } else if (view_type === "form") {
2840 if (self.get("effective_readonly")) {
2841 $(".oe_form_buttons", controller.$element).children().remove();
2843 controller.on_record_loaded.add_last(function() {
2846 controller.on_pager_action.add_first(function() {
2847 self.save_any_view();
2849 } else if (view_type == "graph") {
2850 self.reload_current_view()
2854 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2855 $.when(self.save_any_view()).then(function() {
2856 if(n_mode === "list")
2857 $.async_when().then(function() {self.reload_current_view();});
2860 this.is_setted.then(function() {
2861 $.async_when().then(function () {
2862 self.viewmanager.appendTo(self.$element);
2867 reload_current_view: function() {
2869 return self.is_loaded = self.is_loaded.pipe(function() {
2870 var active_view = self.viewmanager.active_view;
2871 var view = self.viewmanager.views[active_view].controller;
2872 if(active_view === "list") {
2873 return view.reload_content();
2874 } else if (active_view === "form") {
2875 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2876 self.dataset.index = 0;
2878 var act = function() {
2879 return view.do_show();
2881 self.form_last_update = self.form_last_update.pipe(act, act);
2882 return self.form_last_update;
2883 } else if (view.do_search) {
2884 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2888 set_value: function(value_) {
2889 value_ = value_ || [];
2891 this.dataset.reset_ids([]);
2892 if(value_.length >= 1 && value_[0] instanceof Array) {
2894 _.each(value_, function(command) {
2895 var obj = {values: command[2]};
2896 switch (command[0]) {
2897 case commands.CREATE:
2898 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2900 self.dataset.to_create.push(obj);
2901 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2904 case commands.UPDATE:
2905 obj['id'] = command[1];
2906 self.dataset.to_write.push(obj);
2907 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2910 case commands.DELETE:
2911 self.dataset.to_delete.push({id: command[1]});
2913 case commands.LINK_TO:
2914 ids.push(command[1]);
2916 case commands.DELETE_ALL:
2917 self.dataset.delete_all = true;
2922 this.dataset.set_ids(ids);
2923 } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2925 this.dataset.delete_all = true;
2926 _.each(value_, function(command) {
2927 var obj = {values: command};
2928 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2930 self.dataset.to_create.push(obj);
2931 self.dataset.cache.push(_.clone(obj));
2935 this.dataset.set_ids(ids);
2937 this._super(value_);
2938 this.dataset.reset_ids(value_);
2940 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2941 this.dataset.index = 0;
2943 self.is_setted.resolve();
2944 return self.reload_current_view();
2946 get_value: function() {
2950 this.save_any_view();
2951 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2952 val = val.concat(_.map(this.dataset.ids, function(id) {
2953 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2955 return commands.create(alter_order.values);
2957 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2959 return commands.update(alter_order.id, alter_order.values);
2961 return commands.link_to(id);
2963 return val.concat(_.map(
2964 this.dataset.to_delete, function(x) {
2965 return commands['delete'](x.id);}));
2967 save_any_view: function() {
2968 if (this.doing_on_change)
2970 return this.session.synchronized_mode(_.bind(function() {
2971 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2972 this.viewmanager.views[this.viewmanager.active_view] &&
2973 this.viewmanager.views[this.viewmanager.active_view].controller) {
2974 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2975 if (this.viewmanager.active_view === "form") {
2976 if (!view.is_initialized.isResolved()) {
2979 var res = $.when(view.do_save());
2980 if (!res.isResolved() && !res.isRejected()) {
2981 console.warn("Asynchronous get_value() is not supported in form view.");
2984 } else if (this.viewmanager.active_view === "list") {
2985 var res = $.when(view.ensure_saved());
2986 if (!res.isResolved() && !res.isRejected()) {
2987 console.warn("Asynchronous get_value() is not supported in list view.");
2995 is_syntax_valid: function() {
2996 if (!this.viewmanager.views[this.viewmanager.active_view])
2998 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2999 if (this.viewmanager.active_view === "form") {
3000 for (var f in view.fields) {
3002 if (!f.is_valid()) {
3011 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
3012 template: 'One2Many.viewmanager',
3013 init: function(parent, dataset, views, flags) {
3014 this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
3015 this.registry = this.registry.extend({
3016 list: 'instance.web.form.One2ManyListView',
3017 form: 'instance.web.form.One2ManyFormView',
3018 kanban: 'instance.web.form.One2ManyKanbanView',
3021 switch_view: function(mode, unused) {
3022 if (mode !== 'form') {
3023 return this._super(mode, unused);
3026 var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
3027 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3028 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3029 title: _t("Open: ") + self.name,
3030 create_function: function(data) {
3031 return self.o2m.dataset.create(data).then(function(r) {
3032 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3033 self.o2m.dataset.on_change();
3036 write_function: function(id, data, options) {
3037 return self.o2m.dataset.write(id, data, {}).then(function() {
3038 self.o2m.reload_current_view();
3041 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3042 parent_view: self.o2m.view,
3043 child_name: self.o2m.name,
3044 read_function: function() {
3045 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3047 form_view_options: {'not_interactible_on_create':true},
3048 readonly: self.o2m.get("effective_readonly")
3050 pop.on_select_elements.add_last(function() {
3051 self.o2m.reload_current_view();
3056 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
3057 get_context: function() {
3058 this.context = this.o2m.build_context([this.o2m.name]);
3059 return this.context;
3063 instance.web.form.One2ManyListView = instance.web.ListView.extend({
3064 _template: 'One2Many.listview',
3065 do_add_record: function () {
3066 if (this.options.editable) {
3067 this._super.apply(this, arguments);
3070 var pop = new instance.web.form.SelectCreatePopup(this);
3072 self.o2m.field.relation,
3074 title: _t("Create: ") + self.name,
3075 initial_view: "form",
3076 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3077 create_function: function(data, callback, error_callback) {
3078 return self.o2m.dataset.create(data).then(function(r) {
3079 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3080 self.o2m.dataset.on_change();
3081 }).then(callback, error_callback);
3083 read_function: function() {
3084 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3086 parent_view: self.o2m.view,
3087 child_name: self.o2m.name,
3088 form_view_options: {'not_interactible_on_create':true}
3090 self.o2m.build_domain(),
3091 self.o2m.build_context()
3093 pop.on_select_elements.add_last(function() {
3094 self.o2m.reload_current_view();
3098 do_activate_record: function(index, id) {
3100 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3101 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3102 title: _t("Open: ") + self.name,
3103 write_function: function(id, data) {
3104 return self.o2m.dataset.write(id, data, {}, function(r) {
3105 self.o2m.reload_current_view();
3108 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3109 parent_view: self.o2m.view,
3110 child_name: self.o2m.name,
3111 read_function: function() {
3112 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3114 form_view_options: {'not_interactible_on_create':true},
3115 readonly: self.o2m.get("effective_readonly")
3118 do_button_action: function (name, id, callback) {
3120 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3121 return this._super(name, id, _.bind(def.resolve, def));
3125 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3126 form_template: 'One2Many.formview',
3127 on_loaded: function(data) {
3130 this.$buttons.find('button.oe_form_button_create').click(function() {
3131 self.do_save().then(self.on_button_new);
3134 do_notify_change: function() {
3135 if (this.dataset.parent_view) {
3136 this.dataset.parent_view.do_notify_change();
3138 this._super.apply(this, arguments);
3143 var lazy_build_o2m_kanban_view = function() {
3144 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3146 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3150 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3151 instance.web.form.ReinitializeFieldMixin, {
3152 template: "FieldMany2ManyTags",
3154 this._super.apply(this, arguments);
3155 instance.web.form.CompletionFieldMixin.init.call(this);
3156 this.set({"value": []});
3157 this._display_orderer = new instance.web.DropMisordered();
3158 this._drop_shown = false;
3162 instance.web.form.ReinitializeFieldMixin.start.call(this);
3163 this.on("change:value", this, this.render_value);
3165 initialize_content: function() {
3166 if (this.get("effective_readonly"))
3169 self.$text = $("textarea", this.$element);
3170 self.$text.textext({
3171 plugins : 'tags arrow autocomplete',
3173 render: function(suggestion) {
3174 return $('<span class="text-label"/>').
3175 data('index', suggestion['index']).html(suggestion['label']);
3180 selectFromDropdown: function() {
3181 $(this).trigger('hideDropdown');
3182 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3183 var data = self.search_result[index];
3185 self.add_id(data.id);
3192 isTagAllowed: function(tag) {
3197 removeTag: function(tag) {
3198 var id = tag.data("id");
3199 self.set({"value": _.without(self.get("value"), id)});
3201 renderTag: function(stuff) {
3202 return $.fn.textext.TextExtTags.prototype.renderTag.
3203 call(this, stuff).data("id", stuff.id);
3207 itemToString: function(item) {
3212 }).bind('getSuggestions', function(e, data) {
3214 var str = !!data ? data.query || '' : '';
3215 self.get_search_result(str).then(function(result) {
3216 self.search_result = result;
3217 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3218 return _.extend(el, {index:i});
3221 }).bind('hideDropdown', function() {
3222 self._drop_shown = false;
3223 }).bind('showDropdown', function() {
3224 self._drop_shown = true;
3226 self.tags = self.$text.textext()[0].tags();
3227 $("textarea", this.$element).focusout(function() {
3228 self.$text.trigger("setInputData", "");
3229 }).keydown(function(e) {
3230 if (event.keyCode === 9 && self._drop_shown) {
3231 self.$text.textext()[0].autocomplete().selectFromDropdown();
3235 set_value: function(value_) {
3236 value_ = value_ || [];
3237 if (value_.length >= 1 && value_[0] instanceof Array) {
3238 value_ = value_[0][2];
3240 this._super(value_);
3242 get_value: function() {
3243 var tmp = [commands.replace_with(this.get("value"))];
3246 get_search_blacklist: function() {
3247 return this.get("value");
3249 render_value: function() {
3251 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3252 var handle_names = function(data) {
3254 _.each(data, function(el) {
3255 indexed[el[0]] = el;
3257 data = _.map(self.get("value"), function(el) { return indexed[el]; });
3258 if (! self.get("effective_readonly")) {
3259 self.tags.containerElement().children().remove();
3260 $("textarea", self.$element).css("padding-left", "3px");
3261 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3263 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3266 if (! self.get('values') || self.get('values').length > 0) {
3267 this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3272 add_id: function(id) {
3273 this.set({'value': _.uniq(this.get('value').concat([id]))});
3278 * TODO niv: clean those deferred stuff, it could be better
3280 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3281 multi_selection: false,
3282 disable_utility_classes: true,
3283 init: function(field_manager, node) {
3284 this._super(field_manager, node);
3285 this.is_loaded = $.Deferred();
3286 this.initial_is_loaded = this.is_loaded;
3287 this.is_setted = $.Deferred();
3290 this._super.apply(this, arguments);
3291 this.$element.addClass('oe_form_field_many2many');
3295 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3296 this.dataset.m2m = this;
3297 this.dataset.on_unlink.add_last(function(ids) {
3298 self.dataset_changed();
3301 this.is_setted.then(function() {
3304 this.is_loaded.then(function() {
3305 self.on("change:effective_readonly", self, function() {
3306 self.is_loaded = self.is_loaded.pipe(function() {
3307 self.list_view.destroy();
3308 return $.when(self.load_view()).then(function() {
3309 self.reload_content();
3315 set_value: function(value_) {
3316 value_ = value_ || [];
3317 if (value_.length >= 1 && value_[0] instanceof Array) {
3318 value_ = value_[0][2];
3320 this._super(value_);
3321 this.dataset.set_ids(value_);
3323 self.reload_content();
3324 this.is_setted.resolve();
3326 get_value: function() {
3327 return [commands.replace_with(this.get('value'))];
3329 load_view: function() {
3331 this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3332 'addable': self.get("effective_readonly") ? null : _t("Add"),
3333 'deletable': self.get("effective_readonly") ? false : true,
3334 'selectable': self.multi_selection,
3337 var embedded = (this.field.views || {}).tree;
3339 this.list_view.set_embedded_view(embedded);
3341 this.list_view.m2m_field = this;
3342 var loaded = $.Deferred();
3343 this.list_view.on_loaded.add_last(function() {
3344 self.initial_is_loaded.resolve();
3347 $.async_when().then(function () {
3348 self.list_view.appendTo(self.$element);
3352 reload_content: function() {
3354 this.is_loaded = this.is_loaded.pipe(function() {
3355 return self.list_view.reload_content();
3358 dataset_changed: function() {
3359 this.set({'value': this.dataset.ids});
3363 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3364 get_context: function() {
3365 this.context = this.m2m.build_context();
3366 return this.context;
3372 * @extends instance.web.ListView
3374 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3375 do_add_record: function () {
3376 var pop = new instance.web.form.SelectCreatePopup(this);
3380 title: _t("Add: ") + this.name
3382 new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3383 this.m2m_field.build_context()
3386 pop.on_select_elements.add(function(element_ids) {
3387 _.each(element_ids, function(one_id) {
3388 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3389 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3390 self.m2m_field.dataset_changed();
3391 self.reload_content();
3396 do_activate_record: function(index, id) {
3398 var pop = new instance.web.form.FormOpenPopup(this);
3399 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3400 title: _t("Open: ") + this.name,
3401 readonly: this.getParent().get("effective_readonly")
3403 pop.on_write_completed.add_last(function() {
3404 self.reload_content();
3409 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3410 disable_utility_classes: true,
3411 init: function(field_manager, node) {
3412 this._super(field_manager, node);
3413 instance.web.form.CompletionFieldMixin.init.call(this);
3414 m2m_kanban_lazy_init();
3415 this.is_loaded = $.Deferred();
3416 this.initial_is_loaded = this.is_loaded;
3417 this.is_setted = $.Deferred();
3420 this._super.apply(this, arguments);
3424 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3425 this.dataset.m2m = this;
3426 this.dataset.on_unlink.add_last(function(ids) {
3427 self.dataset_changed();
3430 this.is_setted.then(function() {
3433 this.is_loaded.then(function() {
3434 self.on("change:effective_readonly", self, function() {
3435 self.is_loaded = self.is_loaded.pipe(function() {
3436 self.kanban_view.destroy();
3437 return $.when(self.load_view()).then(function() {
3438 self.reload_content();
3444 set_value: function(value_) {
3445 value_ = value_ || [];
3446 if (value_.length >= 1 && value_[0] instanceof Array) {
3447 value_ = value_[0][2];
3449 this._super(value_);
3450 this.dataset.set_ids(value_);
3452 self.reload_content();
3453 this.is_setted.resolve();
3455 load_view: function() {
3457 this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3458 'create_text': _t("Add"),
3459 'creatable': self.get("effective_readonly") ? false : true,
3460 'quick_creatable': self.get("effective_readonly") ? false : true,
3461 'read_only_mode': self.get("effective_readonly") ? true : false,
3462 'confirm_on_delete': false,
3464 var embedded = (this.field.views || {}).kanban;
3466 this.kanban_view.set_embedded_view(embedded);
3468 this.kanban_view.m2m = this;
3469 var loaded = $.Deferred();
3470 this.kanban_view.on_loaded.add_last(function() {
3471 self.initial_is_loaded.resolve();
3474 this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3475 $.async_when().then(function () {
3476 self.kanban_view.appendTo(self.$element);
3480 reload_content: function() {
3482 this.is_loaded = this.is_loaded.pipe(function() {
3483 return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3486 dataset_changed: function() {
3487 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3489 open_popup: function(type, unused) {
3490 if (type !== "form")
3493 if (this.dataset.index === null) {
3494 var pop = new instance.web.form.SelectCreatePopup(this);
3496 this.field.relation,
3498 title: _t("Add: ") + this.name
3500 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3501 this.build_context()
3503 pop.on_select_elements.add(function(element_ids) {
3504 _.each(element_ids, function(one_id) {
3505 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3506 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3507 self.dataset_changed();
3508 self.reload_content();
3513 var id = self.dataset.ids[self.dataset.index];
3514 var pop = new instance.web.form.FormOpenPopup(self.view);
3515 pop.show_element(self.field.relation, id, self.build_context(), {
3516 title: _t("Open: ") + self.name,
3517 write_function: function(id, data, options) {
3518 return self.dataset.write(id, data, {}).then(function() {
3519 self.reload_content();
3522 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3523 parent_view: self.view,
3524 child_name: self.name,
3525 readonly: self.get("effective_readonly")
3529 add_id: function(id) {
3530 this.quick_create.add_id(id);
3534 function m2m_kanban_lazy_init() {
3535 if (instance.web.form.Many2ManyKanbanView)
3537 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3538 quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3539 _is_quick_create_enabled: function() {
3540 return this._super() && ! this.group_by;
3543 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3544 template: 'Many2ManyKanban.quick_create',
3547 * close_btn: If true, the widget will display a "Close" button able to trigger
3550 init: function(parent, dataset, context, buttons) {
3551 this._super(parent);
3552 this.m2m = this.getParent().view.m2m;
3553 this.m2m.quick_create = this;
3554 this._dataset = dataset;
3555 this._buttons = buttons || false;
3556 this._context = context || {};
3558 start: function () {
3560 self.$text = this.$element.find('input').css("width", "200px");
3561 self.$text.textext({
3562 plugins : 'arrow autocomplete',
3564 render: function(suggestion) {
3565 return $('<span class="text-label"/>').
3566 data('index', suggestion['index']).html(suggestion['label']);
3571 selectFromDropdown: function() {
3572 $(this).trigger('hideDropdown');
3573 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3574 var data = self.search_result[index];
3576 self.add_id(data.id);
3583 itemToString: function(item) {
3588 }).bind('getSuggestions', function(e, data) {
3590 var str = !!data ? data.query || '' : '';
3591 self.m2m.get_search_result(str).then(function(result) {
3592 self.search_result = result;
3593 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3594 return _.extend(el, {index:i});
3598 self.$text.focusout(function() {
3605 add_id: function(id) {
3608 self.trigger('added', id);
3609 this.m2m.dataset_changed();
3615 * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3617 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3618 template: "AbstractFormPopup.render",
3621 * -readonly: only applicable when not in creation mode, default to false
3622 * - alternative_form_view
3628 * - form_view_options
3630 init_popup: function(model, row_id, domain, context, options) {
3631 this.row_id = row_id;
3633 this.domain = domain || [];
3634 this.context = context || {};
3635 this.options = options;
3636 _.defaults(this.options, {
3639 init_dataset: function() {
3641 this.created_elements = [];
3642 this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3643 this.dataset.read_function = this.options.read_function;
3644 this.dataset.create_function = function(data, sup) {
3645 var fct = self.options.create_function || sup;
3646 return fct.call(this, data).then(function(r) {
3647 self.created_elements.push(r.result);
3650 this.dataset.write_function = function(id, data, options, sup) {
3651 var fct = self.options.write_function || sup;
3652 return fct.call(this, id, data, options).then(self.on_write_completed);
3654 this.dataset.parent_view = this.options.parent_view;
3655 this.dataset.child_name = this.options.child_name;
3657 display_popup: function() {
3659 this.renderElement();
3660 new instance.web.Dialog(this, {
3664 self.check_exit(true);
3666 title: this.options.title || "",
3667 }, this.$element).open();
3670 on_write_completed: function() {},
3671 setup_form_view: function() {
3674 this.dataset.ids = [this.row_id];
3675 this.dataset.index = 0;
3677 this.dataset.index = null;
3679 var options = _.clone(self.options.form_view_options) || {};
3680 if (this.row_id !== null) {
3681 options.initial_mode = this.options.readonly ? "view" : "edit";
3683 this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3684 if (this.options.alternative_form_view) {
3685 this.view_form.set_embedded_view(this.options.alternative_form_view);
3687 this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3688 this.view_form.on_loaded.add_last(function() {
3689 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3690 var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3691 $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3692 var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3693 $snbutton.click(function() {
3694 $.when(self.view_form.do_save()).then(function() {
3695 self.view_form.reload_mutex.exec(function() {
3696 self.view_form.on_button_new();
3700 var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3701 $sbutton.click(function() {
3702 $.when(self.view_form.do_save()).then(function() {
3703 self.view_form.reload_mutex.exec(function() {
3708 var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3709 $cbutton.click(function() {
3712 if (self.row_id !== null && self.options.readonly) {
3715 $cbutton.text(_t("Close"));
3717 self.view_form.do_show();
3720 on_select_elements: function(element_ids) {
3722 check_exit: function(no_destroy) {
3723 if (this.created_elements.length > 0) {
3724 this.on_select_elements(this.created_elements);
3725 this.created_elements = [];
3729 destroy: function () {
3730 this.$element.dialog('close');
3736 * Class to display a popup containing a form view.
3738 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3739 show_element: function(model, row_id, context, options) {
3740 this.init_popup(model, row_id, [], context, options);
3741 _.defaults(this.options, {
3743 this.display_popup();
3747 this.init_dataset();
3748 this.setup_form_view();
3753 * Class to display a popup to display a list to search a row. It also allows
3754 * to switch to a form view to create a new row.
3756 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3760 * - initial_view: form or search (default search)
3761 * - disable_multiple_selection
3762 * - list_view_options
3764 select_element: function(model, options, domain, context) {
3765 this.init_popup(model, null, domain, context, options);
3767 _.defaults(this.options, {
3768 initial_view: "search",
3770 this.initial_ids = this.options.initial_ids;
3771 this.display_popup();
3775 this.init_dataset();
3776 if (this.options.initial_view == "search") {
3777 self.rpc('/web/session/eval_domain_and_context', {
3779 contexts: [this.context]
3780 }, function (results) {
3781 var search_defaults = {};
3782 _.each(results.context, function (value_, key) {
3783 var match = /^search_default_(.*)$/.exec(key);
3785 search_defaults[match[1]] = value_;
3788 self.setup_search_view(search_defaults);
3794 setup_search_view: function(search_defaults) {
3796 if (this.searchview) {
3797 this.searchview.destroy();
3799 this.searchview = new instance.web.SearchView(this,
3800 this.dataset, false, search_defaults);
3801 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3802 if (self.initial_ids) {
3803 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3804 contexts, groupbys);
3805 self.initial_ids = undefined;
3807 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3810 this.searchview.on_loaded.add_last(function () {
3811 self.view_list = new instance.web.form.SelectCreateListView(self,
3812 self.dataset, false,
3813 _.extend({'deletable': false,
3814 'selectable': !self.options.disable_multiple_selection,
3816 }, self.options.list_view_options || {}));
3817 self.view_list.popup = self;
3818 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3819 self.view_list.do_show();
3820 }).pipe(function() {
3821 self.searchview.do_search();
3823 self.view_list.on_loaded.add_last(function() {
3824 var $buttons = self.view_list.$element.find(".oe-actions");
3825 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3826 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3827 $cbutton.click(function() {
3830 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3831 if(self.options.disable_multiple_selection) {
3834 $sbutton.click(function() {
3835 self.on_select_elements(self.selected_ids);
3840 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3842 do_search: function(domains, contexts, groupbys) {
3844 this.rpc('/web/session/eval_domain_and_context', {
3845 domains: domains || [],
3846 contexts: contexts || [],
3847 group_by_seq: groupbys || []
3848 }, function (results) {
3849 self.view_list.do_search(results.domain, results.context, results.group_by);
3852 on_click_element: function(ids) {
3853 this.selected_ids = ids || [];
3854 if(this.selected_ids.length > 0) {
3855 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3857 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3860 new_object: function() {
3861 if (this.searchview) {
3862 this.searchview.hide();
3864 if (this.view_list) {
3865 this.view_list.$element.hide();
3867 this.setup_form_view();
3871 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3872 do_add_record: function () {
3873 this.popup.new_object();
3875 select_record: function(index) {
3876 this.popup.on_select_elements([this.dataset.ids[index]]);
3877 this.popup.destroy();
3879 do_select: function(ids, records) {
3880 this._super(ids, records);
3881 this.popup.on_click_element(ids);
3885 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3886 template: 'FieldReference',
3887 init: function(field_manager, node) {
3888 this._super(field_manager, node);
3889 this.reference_ready = true;
3891 on_nop: function() {
3893 on_selection_changed: function() {
3894 if (this.reference_ready) {
3895 var sel = this.selection.get_value();
3896 this.m2o.field.relation = sel;
3897 this.m2o.set_value(false);
3898 this.m2o.$element.toggle(sel !== false);
3901 destroy_content: function() {
3902 if (this.selection) {
3903 this.selection.destroy();
3904 this.selection = undefined;
3908 this.m2o = undefined;
3911 initialize_content: function() {
3912 this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3915 this.selection.view = this.view;
3916 this.selection.set({force_readonly: this.get('effective_readonly')});
3917 this.selection.on("change:value", this, this.on_selection_changed);
3918 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3919 this.selection.renderElement();
3920 this.selection.start();
3922 this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3925 this.m2o.view = this.view;
3926 this.m2o.set({force_readonly: this.get("effective_readonly")});
3927 this.m2o.on("change:value", this, this.data_changed);
3928 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3929 this.m2o.renderElement();
3932 is_false: function() {
3933 return typeof(this.get_value()) !== 'string';
3935 set_value: function(value_) {
3936 this._super(value_);
3937 this.render_value();
3939 render_value: function() {
3940 this.reference_ready = false;
3941 var vals = [], sel_val, m2o_val;
3942 if (typeof(this.get('value')) === 'string') {
3943 vals = this.get('value').split(',');
3945 sel_val = vals[0] || false;
3946 m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3947 if (!this.get("effective_readonly")) {
3948 this.selection.set_value(sel_val);
3950 this.m2o.field.relation = sel_val;
3951 this.m2o.set_value(m2o_val);
3952 this.reference_ready = true;
3954 data_changed: function() {
3955 var model = this.selection.get_value(),
3956 id = this.m2o.get_value();
3957 if (typeof(model) === 'string' && typeof(id) === 'number') {
3958 this.set({'value': model + ',' + id});
3960 this.set({'value': false});
3963 get_field: function(name) {
3964 if (name === "selection") {
3966 selection: this.view.fields_view.fields[this.name].selection,
3969 } else if (name === "m2o") {
3975 throw Exception("Should not happen");
3979 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3980 init: function(field_manager, node) {
3982 this._super(field_manager, node);
3983 this.binary_value = false;
3984 this.fileupload_id = _.uniqueId('oe_fileupload');
3985 $(window).on(this.fileupload_id, function() {
3986 var args = [].slice.call(arguments).slice(1);
3987 self.on_file_uploaded.apply(self, args);
3991 $(window).off(this.fileupload_id);
3992 this._super.apply(this, arguments);
3994 initialize_content: function() {
3995 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3996 this.$element.find('button.oe_binary_file_save').click(this.on_save_as);
3997 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3999 human_filesize : function(size) {
4000 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
4002 while (size >= 1024) {
4006 return size.toFixed(2) + ' ' + units[i];
4008 on_file_change: function(e) {
4009 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
4010 // http://www.html5rocks.com/tutorials/file/dndfiles/
4011 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
4013 if ($(e.target).val() !== '') {
4014 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
4015 this.$element.find('form.oe-binary-form').submit();
4016 this.$element.find('.oe-binary-progress').show();
4017 this.$element.find('.oe-binary').hide();
4020 on_file_uploaded: function(size, name, content_type, file_base64) {
4021 if (size === false) {
4022 this.do_warn("File Upload", "There was a problem while uploading your file");
4023 // TODO: use openerp web crashmanager
4024 console.warn("Error while uploading file : ", name);
4026 this.filename = name;
4027 this.on_file_uploaded_and_valid.apply(this, arguments);
4029 this.$element.find('.oe-binary-progress').hide();
4030 this.$element.find('.oe-binary').show();
4032 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4034 on_save_as: function(ev) {
4035 var value = this.get('value');
4037 this.do_warn(_t("Save As..."), _t("The field is empty, there's nothing to save !"));
4038 ev.stopPropagation();
4039 } else if (this._dirty_flag) {
4040 var link = this.$('.oe_binary_file_save_data')[0];
4041 link.download = this.filename || "download.bin"; // Works on only on Google Chrome
4042 //link.target = '_blank';
4043 link.href = "data:application/octet-stream;base64," + value;
4046 this.session.get_file({
4047 url: '/web/binary/saveas_ajax',
4048 data: {data: JSON.stringify({
4049 model: this.view.dataset.model,
4050 id: (this.view.datarecord.id || ''),
4052 filename_field: (this.node.attrs.filename || ''),
4053 context: this.view.dataset.get_context()
4055 complete: $.unblockUI,
4056 error: instance.webclient.crashmanager.on_rpc_error
4058 ev.stopPropagation();
4062 on_clear: function() {
4063 if (this.get('value') !== false) {
4064 this.binary_value = false;
4065 this.set({'value': false});
4071 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
4072 template: 'FieldBinaryFile',
4073 initialize_content: function() {
4075 if (this.get("effective_readonly")) {
4077 this.$element.find('a').click(function() {
4078 if (self.get('value')) {
4085 set_value: function(value_) {
4086 this._super.apply(this, arguments);
4087 this.render_value();
4089 render_value: function() {
4090 if (!this.get("effective_readonly")) {
4092 if (this.node.attrs.filename) {
4093 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4095 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4097 this.$element.find('input').eq(0).val(show_value);
4099 this.$element.find('a').show(!!this.get('value'));
4100 if (this.get('value')) {
4101 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4102 this.$element.find('a').text(show_value);
4106 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4107 this.binary_value = true;
4108 this.set({'value': file_base64});
4109 var show_value = name + " (" + this.human_filesize(size) + ")";
4110 this.$element.find('input').eq(0).val(show_value);
4111 this.set_filename(name);
4113 set_filename: function(value_) {
4114 var filename = this.node.attrs.filename;
4115 if (this.view.fields[filename]) {
4116 this.view.fields[filename].set({value: value_});
4119 on_clear: function() {
4120 this._super.apply(this, arguments);
4121 this.$element.find('input').eq(0).val('');
4122 this.set_filename('');
4126 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4127 template: 'FieldBinaryImage',
4128 set_value: function(value_) {
4129 this._super.apply(this, arguments);
4130 this.render_value();
4132 render_value: function() {
4134 if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4135 url = 'data:image/png;base64,' + this.get('value');
4136 } else if (this.get('value')) {
4137 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4138 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4140 url = "/web/static/src/img/placeholder.png";
4142 var img = QWeb.render("FieldBinaryImage-img", { widget: this, url: url });
4143 this.$element.find('> img').remove();
4144 this.$element.prepend(img);
4146 on_file_change: function() {
4147 this.render_value();
4148 this._super.apply(this, arguments);
4150 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4151 this.set({'value': file_base64});
4152 this.binary_value = true;
4153 this.render_value();
4155 on_clear: function() {
4156 this._super.apply(this, arguments);
4157 this.render_value();
4161 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4165 this.selected_value = null;
4166 // preview in start only for selection fields, because of the dynamic behavior of many2one fields.
4167 if (this.field.type in ['selection']) {
4171 set_value: function(value_) {
4173 this._super(value_);
4174 // find selected value:
4175 // - many2one: [2, "New"] -> 2
4176 // - selection: new -> new
4177 if (this.field.type == "many2one") {
4178 this.selected_value = value_[0];
4180 this.selected_value = value_;
4182 // trick to be sure all values are loaded in the form, therefore
4183 // enabling the evaluation of dynamic domains
4184 $.async_when().then(function() {
4185 return self.render_list();
4189 /** Get the status list and render them
4190 * to_show: [[identifier, value_to_display]] where
4191 * - identifier = key for a selection, id for a many2one
4192 * - display_val = label that will be displayed
4193 * - ex: [[0, "New"]] (many2one) or [["new", "In Progress"]] (selection)
4195 render_list: function() {
4197 // get selection values, filter them and render them
4198 var selection_done = this.get_selection().pipe(self.proxy('filter_selection')).pipe(self.proxy('render_elements'));
4201 /** Get the selection list to be displayed in the statusbar widget.
4202 * For selection fields: this is directly given by this.field.selection
4203 * For many2one fields :
4204 * - perform a search on the relation of the many2one field (given by
4206 * - get the field domain for the search
4207 * - self.build_domain() gives the domain given by the view or by
4209 * - if the optional statusbar_fold attribute is set to true, make
4210 * an AND with build_domain to hide all 'fold=true' columns
4211 * - make an OR with current value, to be sure it is displayed,
4212 * with the correct order, even if it is folded
4214 get_selection: function() {
4216 if (this.field.type == "many2one") {
4217 this.selection = [];
4218 // get fold information from widget
4219 var fold = ((this.node.attrs || {}).statusbar_fold || true);
4220 // build final domain: if fold option required, add the
4222 var domain = new instance.web.CompoundDomain(['|'], ['&'], self.build_domain(), [['fold', '=', false]], [['id', '=', self.selected_value]]);
4224 var domain = new instance.web.CompoundDomain(['|'], self.build_domain(), [['id', '=', self.selected_value]]);
4226 // get a DataSetSearch on the current field relation (ex: crm.lead.stage_id -> crm.case.stage)
4227 var model_ext = new instance.web.DataSetSearch(this, this.field.relation, self.build_context(), domain);
4229 var read_defer = model_ext.read_slice(['name'], {}).pipe( function (records) {
4230 _(records).each(function (record) {
4231 self.selection.push([record.id, record.name]);
4235 this.selection = this.field.selection;
4236 var read_defer = new $.Deferred().resolve();
4241 /** Filters this.selection, according to values coming from the statusbar_visible
4242 * attribute of the field. For example: statusbar_visible="draft,open"
4243 * Currently, the key of (key, label) pairs has to be used in the
4244 * selection of visible items. This feature is not meant to be used
4245 * with many2one fields.
4247 filter_selection: function() {
4249 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4250 function(x) { return _.str.trim(x); });
4251 shown = _.select(shown, function(x) { return x.length > 0; });
4253 if (shown.length == 0) {
4254 this.to_show = this.selection;
4256 this.to_show = _.select(this.selection, function(x) {
4257 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4262 /** Renders the widget. This function also checks for statusbar_colors='{"pending": "blue"}'
4263 * attribute in the widget. This allows to set a given color to a given
4264 * state (given by the key of (key, label)).
4266 render_elements: function () {
4267 var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4268 this.$element.html(content);
4270 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4271 var color = colors[this.selected_value];
4273 var elem = this.$element.find("li.oe_form_steps_active span");
4274 elem.css("color", color);
4280 * Registry of form fields, called by :js:`instance.web.FormView`.
4282 * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4283 * will substitute to the <field> tags as defined in OpenERP's views.
4285 instance.web.form.widgets = new instance.web.Registry({
4286 'char' : 'instance.web.form.FieldChar',
4287 'id' : 'instance.web.form.FieldID',
4288 'email' : 'instance.web.form.FieldEmail',
4289 'url' : 'instance.web.form.FieldUrl',
4290 'text' : 'instance.web.form.FieldText',
4291 'date' : 'instance.web.form.FieldDate',
4292 'datetime' : 'instance.web.form.FieldDatetime',
4293 'selection' : 'instance.web.form.FieldSelection',
4294 'many2one' : 'instance.web.form.FieldMany2One',
4295 'many2many' : 'instance.web.form.FieldMany2Many',
4296 'many2many_tags' : 'instance.web.form.FieldMany2ManyTags',
4297 'many2many_kanban' : 'instance.web.form.FieldMany2ManyKanban',
4298 'one2many' : 'instance.web.form.FieldOne2Many',
4299 'one2many_list' : 'instance.web.form.FieldOne2Many',
4300 'reference' : 'instance.web.form.FieldReference',
4301 'boolean' : 'instance.web.form.FieldBoolean',
4302 'float' : 'instance.web.form.FieldFloat',
4303 'integer': 'instance.web.form.FieldFloat',
4304 'float_time': 'instance.web.form.FieldFloat',
4305 'progressbar': 'instance.web.form.FieldProgressBar',
4306 'image': 'instance.web.form.FieldBinaryImage',
4307 'binary': 'instance.web.form.FieldBinaryFile',
4308 'statusbar': 'instance.web.form.FieldStatus'
4312 * Registry of widgets usable in the form view that can substitute to any possible
4313 * tags defined in OpenERP's form views.
4315 * Every referenced class should extend FormWidget.
4317 instance.web.form.tags = new instance.web.Registry({
4318 'button' : 'instance.web.form.WidgetButton',
4323 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: