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) {
917 set_tags_registry: function(tags_registry) {
918 this.tags_registry = tags_registry;
920 set_fields_registry: function(fields_registry) {
921 this.fields_registry = fields_registry;
923 // Backward compatibility tools, current default version: v6.1
924 process_version: function() {
925 selector = 'form[version!="7.0"] page,form[version!="7.0"]';
926 this.$form.find(selector).add(this.$form.filter(selector)).wrapInner('<group col="4"/>');
928 render_to: function($target) {
930 this.$target = $target;
932 // TODO: I know this will save the world and all the kitten for a moment,
933 // but one day, we will have to get rid of xml2json
934 var xml = instance.web.json_node_to_xml(this.fvg.arch);
935 this.$form = $('<div class="oe_form">' + xml + '</div>');
937 this.process_version()
939 this.fields_to_init = [];
940 this.tags_to_init = [];
942 this.process(this.$form);
944 this.$form.appendTo(this.$target);
946 _.each(this.fields_to_init, function($elem) {
947 var name = $elem.attr("name");
948 if (!self.fvg.fields[name]) {
949 throw new Error("Field '" + name + "' specified in view could not be found.");
951 var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
953 throw new Error("Widget type '"+ $elem.attr('widget') + "' is not implemented");
955 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
956 var $label = self.labels[$elem.attr("name")];
958 w.set_input_id($label.attr("for"));
961 self.view.register_field(w, $elem.attr("name"));
964 _.each(this.tags_to_init, function($elem) {
965 var tag_name = $elem[0].tagName.toLowerCase();
966 var obj = self.tags_registry.get_object(tag_name);
967 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
970 // TODO: return a deferred
972 render_element: function(template /* dictionaries */) {
973 var dicts = [].slice.call(arguments).slice(1);
974 var dict = _.extend.apply(_, dicts);
975 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
976 return $(QWeb.render(template, dict));
978 alter_field: function(field) {
980 toggle_layout_debugging: function() {
981 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
982 this.$target.find('[title]').removeAttr('title');
983 this.$target.find('.oe_form_group_cell').each(function() {
984 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
985 $(this).attr('title', text);
988 this.$target.toggleClass('oe_layout_debugging');
990 process: function($tag) {
992 var tagname = $tag[0].nodeName.toLowerCase();
993 if (this.tags_registry.contains(tagname)) {
994 this.tags_to_init.push($tag);
997 var fn = self['process_' + tagname];
999 var args = [].slice.call(arguments);
1001 return fn.apply(self, args);
1003 // generic tag handling, just process children
1004 $tag.children().each(function() {
1005 self.process($(this));
1007 self.handle_common_properties($tag, $tag);
1008 $tag.removeAttr("modifiers");
1012 process_sheet: function($sheet) {
1013 var $new_sheet = this.render_element('FormRenderingSheet', $sheet.getAttributes());
1014 this.handle_common_properties($new_sheet, $sheet);
1015 var $dst = $new_sheet.find('.oe_form_sheet');
1016 $sheet.contents().appendTo($dst);
1017 $sheet.before($new_sheet).remove();
1018 this.process($new_sheet);
1020 process_form: function($form) {
1021 if ($form.find('> sheet').length === 0) {
1022 $form.addClass('oe_form_nosheet');
1024 var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
1025 this.handle_common_properties($new_form, $form);
1026 $form.contents().appendTo($new_form);
1027 if ($form[0] === this.$form[0]) {
1028 // If root element, replace it
1029 this.$form = $new_form;
1031 $form.before($new_form).remove();
1033 this.process($new_form);
1036 * Used by direct <field> children of a <group> tag only
1037 * This method will add the implicit <label...> for every field
1040 preprocess_field: function($field) {
1042 var name = $field.attr('name'),
1043 field_colspan = parseInt($field.attr('colspan'), 10),
1044 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1046 if ($field.attr('nolabel') === '1')
1048 $field.attr('nolabel', '1');
1050 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1051 $(el).parents().each(function(unused, tag) {
1052 var name = tag.tagName.toLowerCase();
1053 if (name === "field" || name in self.tags_registry.map)
1060 $label = $('<label/>').attr({
1062 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1063 "string": $field.attr('string'),
1064 "help": $field.attr('help'),
1065 "class": $field.attr('class'),
1067 $label.insertBefore($field);
1068 if (field_colspan > 1) {
1069 $field.attr('colspan', field_colspan - 1);
1073 process_field: function($field) {
1074 if ($field.parent().is('group')) {
1075 // No implicit labels for normal fields, only for <group> direct children
1076 var $label = this.preprocess_field($field);
1078 this.process($label);
1081 this.fields_to_init.push($field);
1084 process_group: function($group) {
1086 $group.children('field').each(function() {
1087 self.preprocess_field($(this));
1089 var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
1091 if ($new_group.first().is('table.oe_form_group')) {
1092 $table = $new_group;
1093 } else if ($new_group.filter('table.oe_form_group').length) {
1094 $table = $new_group.filter('table.oe_form_group').first();
1096 $table = $new_group.find('table.oe_form_group').first();
1100 cols = parseInt($group.attr('col') || 2, 10),
1104 $group.children().each(function(a,b,c) {
1105 var $child = $(this);
1106 var colspan = parseInt($child.attr('colspan') || 1, 10);
1107 var tagName = $child[0].tagName.toLowerCase();
1108 var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1109 var newline = tagName === 'newline';
1111 // Note FME: those classes are used in layout debug mode
1112 if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1113 $tr.addClass('oe_form_group_row_incomplete');
1115 $tr.addClass('oe_form_group_row_newline');
1122 if (!$tr || row_cols < colspan) {
1123 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1126 row_cols -= colspan;
1128 // invisibility transfer
1129 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1130 var invisible = field_modifiers.invisible;
1131 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1133 $tr.append($td.append($child));
1134 children.push($child[0]);
1136 if (row_cols && $td) {
1137 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1139 $group.before($new_group).remove();
1141 $table.find('> tbody > tr').each(function() {
1142 var to_compute = [],
1145 $(this).children().each(function() {
1147 $child = $td.children(':first');
1148 switch ($child[0].tagName.toLowerCase()) {
1150 if ($child.attr('orientation') === 'vertical') {
1151 $td.addClass('oe_vertical_separator').attr('width', '1');
1153 row_cols-= $td.attr('colspan') || 1;
1158 if ($child.attr('for')) {
1159 $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1160 row_cols-= $td.attr('colspan') || 1;
1165 var width = _.str.trim($child.attr('width') || ''),
1166 iwidth = parseInt(width, 10);
1168 if (width.substr(-1) === '%') {
1170 width = iwidth + '%';
1173 $td.css('min-width', width + 'px');
1175 $td.attr('width', width);
1176 $child.removeAttr('width');
1177 row_cols-= $td.attr('colspan') || 1;
1179 to_compute.push($td);
1185 var unit = Math.floor(total / row_cols);
1186 if (!$(this).is('.oe_form_group_row_incomplete')) {
1187 _.each(to_compute, function($td, i) {
1188 var width = parseInt($td.attr('colspan'), 10) * unit;
1189 $td.attr('width', width + '%');
1195 _.each(children, function(el) {
1196 self.process($(el));
1198 this.handle_common_properties($new_group, $group);
1201 process_notebook: function($notebook) {
1204 $notebook.find('> page').each(function() {
1205 var $page = $(this);
1206 var page_attrs = $page.getAttributes();
1207 page_attrs.id = _.uniqueId('notebook_page_');
1208 var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
1209 $page.contents().appendTo($new_page);
1210 $page.before($new_page).remove();
1211 var ic = self.handle_common_properties($new_page, $page).invisibility_changer;
1212 page_attrs.__page = $new_page;
1213 page_attrs.__ic = ic;
1214 pages.push(page_attrs);
1216 $new_page.children().each(function() {
1217 self.process($(this));
1220 var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
1221 $notebook.contents().appendTo($new_notebook);
1222 $notebook.before($new_notebook).remove();
1223 self.process($($new_notebook.children()[0]));
1224 //tabs and invisibility handling
1225 $new_notebook.tabs();
1226 _.each(pages, function(page, i) {
1229 page.__ic.on("change:effective_invisible", null, function() {
1230 var current = $new_notebook.tabs("option", "selected");
1231 if (! pages[current].__ic || ! pages[current].__ic.get("effective_invisible"))
1233 var first_visible = _.find(_.range(pages.length), function(i2) {
1234 return (! pages[i2].__ic) || (! pages[i2].__ic.get("effective_invisible"));
1236 if (first_visible !== undefined) {
1237 $new_notebook.tabs('select', first_visible);
1242 this.handle_common_properties($new_notebook, $notebook);
1243 return $new_notebook;
1245 process_separator: function($separator) {
1246 var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
1247 $separator.before($new_separator).remove();
1248 this.handle_common_properties($new_separator, $separator);
1249 return $new_separator;
1251 process_label: function($label) {
1252 var name = $label.attr("for"),
1253 field_orm = this.fvg.fields[name];
1255 string: $label.attr('string') || (field_orm || {}).string || '',
1256 help: $label.attr('help') || (field_orm || {}).help || '',
1257 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1259 var align = parseFloat(dict.align);
1260 if (isNaN(align) || align === 1) {
1262 } else if (align === 0) {
1268 var $new_label = this.render_element('FormRenderingLabel', dict);
1269 $label.before($new_label).remove();
1270 this.handle_common_properties($new_label, $label);
1272 this.labels[name] = $new_label;
1276 handle_common_properties: function($new_element, $node) {
1277 var str_modifiers = $node.attr("modifiers") || "{}"
1278 var modifiers = JSON.parse(str_modifiers);
1280 if (modifiers.invisible !== undefined)
1281 ic = new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1282 $new_element.addClass($node.attr("class") || "");
1283 $new_element.attr('style', $node.attr('style'));
1284 return {invisibility_changer: ic,};
1288 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1289 alter_field: function(field) {
1290 field.set({"force_readonly": true});
1294 instance.web.form.FormDialog = instance.web.Dialog.extend({
1295 init: function(parent, options, view_id, dataset) {
1296 this._super(parent, options);
1297 this.dataset = dataset;
1298 this.view_id = view_id;
1303 this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1306 this.form.appendTo(this.$element);
1307 this.form.on_created.add_last(this.on_form_dialog_saved);
1308 this.form.on_saved.add_last(this.on_form_dialog_saved);
1311 select_id: function(id) {
1312 if (this.form.dataset.select_id(id)) {
1313 return this.form.do_show();
1315 this.do_warn("Could not find id in dataset");
1316 return $.Deferred().reject();
1319 on_form_dialog_saved: function(r) {
1324 instance.web.form.compute_domain = function(expr, fields) {
1326 for (var i = expr.length - 1; i >= 0; i--) {
1328 if (ex.length == 1) {
1329 var top = stack.pop();
1332 stack.push(stack.pop() || top);
1335 stack.push(stack.pop() && top);
1341 throw new Error(_.str.sprintf(
1342 _t("Unknown operator %s in domain %s"),
1343 ex, JSON.stringify(expr)));
1347 var field = fields[ex[0]];
1349 throw new Error(_.str.sprintf(
1350 _t("Unknown field %s in domain %s"),
1351 ex[0], JSON.stringify(expr)));
1353 var field_value = field.get_value ? field.get_value() : field.value;
1357 switch (op.toLowerCase()) {
1360 stack.push(field_value == val);
1364 stack.push(field_value != val);
1367 stack.push(field_value < val);
1370 stack.push(field_value > val);
1373 stack.push(field_value <= val);
1376 stack.push(field_value >= val);
1379 if (!_.isArray(val)) val = [val];
1380 stack.push(_(val).contains(field_value));
1383 if (!_.isArray(val)) val = [val];
1384 stack.push(!_(val).contains(field_value));
1388 _t("Unsupported operator %s in domain %s"),
1389 op, JSON.stringify(expr));
1392 return _.all(stack, _.identity);
1396 * Must be applied over an class already possessing the PropertiesMixin.
1398 * Apply the result of the "invisible" domain to this.$element.
1400 instance.web.form.InvisibilityChangerMixin = {
1401 init: function(field_manager, invisible_domain) {
1402 this._ic_field_manager = field_manager
1403 this._ic_invisible_modifier = invisible_domain;
1404 this._ic_field_manager.on("view_content_has_changed", this, function() {
1405 var result = this._ic_invisible_modifier === undefined ? false :
1406 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1407 this.set({"invisible": result});
1409 this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1410 var check = function() {
1411 if (this.get("invisible") || this.get('force_invisible')) {
1412 this.set({"effective_invisible": true});
1414 this.set({"effective_invisible": false});
1417 this.on('change:invisible', this, check);
1418 this.on('change:force_invisible', this, check);
1419 _.bind(check, this)();
1422 this.on("change:effective_invisible", this, this._check_visibility);
1423 this._check_visibility();
1425 _check_visibility: function() {
1426 this.$element.toggleClass('oe_form_invisible', this.get("effective_invisible"));
1430 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1431 init: function(parent, field_manager, invisible_domain, $element) {
1432 this.setParent(parent);
1433 instance.web.PropertiesMixin.init.call(this);
1434 instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1435 this.$element = $element;
1440 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1442 * @constructs instance.web.form.FormWidget
1443 * @extends instance.web.Widget
1448 init: function(view, node) {
1452 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1453 instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1455 this.view.on("view_content_has_changed", this, this.process_modifiers);
1457 renderElement: function() {
1459 this.$element.addClass(this.node.attrs["class"] || "");
1461 destroy: function() {
1463 this._super.apply(this, arguments);
1465 process_modifiers: function() {
1466 var compute_domain = instance.web.form.compute_domain;
1468 for (var a in this.modifiers) {
1469 if (!_.include(["invisible"], a)) {
1470 var val = compute_domain(this.modifiers[a], this.view.fields);
1476 do_attach_tooltip: function(widget, trigger, options) {
1477 widget = widget || this;
1478 trigger = trigger || this.$element;
1479 options = _.extend({
1484 var template = widget.template + '.tooltip';
1485 if (!QWeb.has_template(template)) {
1486 template = 'WidgetLabel.tooltip';
1488 return QWeb.render(template, {
1489 debug: instance.connection.debug,
1492 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1497 $(trigger).tipsy(options);
1499 _build_view_fields_values: function(blacklist) {
1500 var a_dataset = this.view.dataset;
1501 var fields_values = this.view.get_fields_values(blacklist);
1502 var active_id = a_dataset.ids[a_dataset.index];
1503 _.extend(fields_values, {
1504 active_id: active_id || false,
1505 active_ids: active_id ? [active_id] : [],
1506 active_model: a_dataset.model,
1509 if (a_dataset.parent_view) {
1510 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1512 return fields_values;
1514 _build_eval_context: function(blacklist) {
1515 var a_dataset = this.view.dataset;
1516 return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1519 * Builds a new context usable for operations related to fields by merging
1520 * the fields'context with the action's context.
1522 build_context: function(blacklist) {
1523 // only use the model's context if there is not context on the node
1524 var v_context = this.node.attrs.context;
1526 v_context = (this.field || {}).context || {};
1529 if (v_context.__ref || true) { //TODO: remove true
1530 var fields_values = this._build_eval_context(blacklist);
1531 v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1535 build_domain: function() {
1536 var f_domain = this.field.domain || [];
1537 var n_domain = this.node.attrs.domain || null;
1538 // if there is a domain on the node, overrides the model's domain
1539 var final_domain = n_domain !== null ? n_domain : f_domain;
1540 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1541 var fields_values = this._build_eval_context();
1542 final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1544 return final_domain;
1548 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1549 template: 'WidgetButton',
1550 init: function(view, node) {
1551 this._super(view, node);
1552 this.force_disabled = false;
1553 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1554 if (this.node.attrs.default_focus == '1') {
1555 // TODO fme: provide enter key binding to widgets
1556 this.view.default_focus_button = this;
1558 this.view.on('view_content_has_changed', this, this.check_disable);
1561 this._super.apply(this, arguments);
1562 this.$element.click(this.on_click);
1563 if (this.node.attrs.help || instance.connection.debug) {
1564 this.do_attach_tooltip();
1567 on_click: function() {
1569 this.force_disabled = true;
1570 this.check_disable();
1571 this.execute_action().always(function() {
1572 self.force_disabled = false;
1573 self.check_disable();
1576 execute_action: function() {
1578 var exec_action = function() {
1579 if (self.node.attrs.confirm) {
1580 var def = $.Deferred();
1581 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1582 title: _t('Confirm'),
1585 {text: _t("Cancel"), click: function() {
1587 $(this).dialog("close");
1590 {text: _t("Ok"), click: function() {
1591 self.on_confirmed().then(function() {
1594 $(this).dialog("close");
1599 return def.promise();
1601 return self.on_confirmed();
1604 if (!this.node.attrs.special) {
1605 this.view.force_dirty = true;
1606 return this.view.recursive_save().pipe(exec_action);
1608 return exec_action();
1611 on_confirmed: function() {
1614 var context = this.node.attrs.context;
1615 if (context && context.__ref) {
1616 context = new instance.web.CompoundContext(context);
1617 context.set_eval_context(this._build_eval_context());
1620 return this.view.do_execute_action(
1621 _.extend({}, this.node.attrs, {context: context}),
1622 this.view.dataset, this.view.datarecord.id, function () {
1626 check_disable: function() {
1627 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1628 this.$element.prop('disabled', disabled);
1629 this.$element.css('color', disabled ? 'grey' : '');
1634 * Interface to be implemented by fields.
1637 * - readonly: boolean. If set to true the field should appear in readonly mode.
1638 * - force_readonly: boolean, When it is true, the field should always appear
1639 * in read only mode, no matter what the value of the "readonly" property can be.
1641 * - changed_value: triggered to inform the view to check on_changes
1644 instance.web.form.FieldMixin = {
1646 * Constructor takes 2 arguments:
1647 * - field_manager: Implements FieldManagerMixin
1648 * - node: the "<field>" node in json form
1650 init: function(field_manager, node) {},
1652 * Called by the form view to indicate the value of the field.
1654 * set_value() may return an object that can be passed to $.when() that represents the moment when
1655 * the field has finished all operations necessary before the user can effectively use the widget.
1657 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1658 * regardless of any asynchronous operation currently running and the status of any promise that a
1659 * previous call to set_value() could have returned.
1661 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1662 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1663 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1664 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1665 * no information is ever given to know which format is used.
1667 set_value: function(value_) {},
1669 * Get the current value of the widget.
1671 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1672 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1673 * For example if the field is marqued as "required", a call to get_value() can return false.
1675 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1676 * return a defaut value according to the type of field.
1678 * This method is always assumed to perform synchronously, it can not return a promise.
1680 * If there was no user interaction to modify the value of the field, it is always assumed that
1681 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1682 * altough the syntax can be different. This can be the case for type of fields that have a different
1683 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1685 get_value: function() {},
1687 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1690 set_input_id: function(id) {},
1692 * Returns true if is_syntax_valid() returns true and the value is semantically
1693 * valid too according to the semantic restrictions applied to the field.
1695 is_valid: function() {},
1697 * Returns true if the field holds a value which is syntaxically correct, ignoring
1698 * the potential semantic restrictions applied to the field.
1700 is_syntax_valid: function() {},
1702 * Must set the focus on the field.
1704 focus: function() {},
1708 * Abstract class for classes implementing FieldMixin.
1711 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1712 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1713 * - value: useful property to hold the value of the field. By default, set_value() and get_value()
1714 * set and retrieve the value property. Changing the value property also triggers automatically
1715 * a 'changed_value' event that inform the view to trigger on_changes.
1718 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1720 * @constructs instance.web.form.AbstractField
1721 * @extends instance.web.form.FormWidget
1723 * @param field_manager
1726 init: function(field_manager, node) {
1727 this._super(field_manager, node);
1728 this.field_manager = field_manager;
1729 this.name = this.node.attrs.name;
1730 this.set({'value': false});
1731 this.field = this.field_manager.get_field(this.name);
1732 this.set({required: this.modifiers['required'] === true});
1734 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1736 this.set({"readonly": this.modifiers['readonly'] === true});
1737 var test_effective_readonly = function() {
1738 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1740 this.on("change:readonly", this, test_effective_readonly);
1741 this.on("change:force_readonly", this, test_effective_readonly);
1742 _.bind(test_effective_readonly, this)();
1744 this.on("change:value", this, function() {
1745 if (! this._inhibit_on_change)
1746 this.trigger('changed_value');
1747 this._check_css_flags();
1750 renderElement: function() {
1753 if (this.field.translate) {
1754 this.$element.addClass('oe_form_field_translatable');
1755 this.$element.find('.oe_field_translate').click(_.bind(function() {
1756 this.field_manager.open_translate_dialog(this);
1759 this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1760 if (instance.connection.debug) {
1761 this.do_attach_tooltip(this, this.$label[0] || this.$element);
1762 this.$label.off('dblclick').on('dblclick', function() {
1763 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1765 console.log("window.w =", window.w);
1768 if (!this.disable_utility_classes) {
1769 this.off("change:required", this, this._set_required);
1770 this.on("change:required", this, this._set_required);
1771 this._set_required();
1773 this._check_visibility();
1774 this._check_css_flags();
1777 * Private. Do not use.
1779 _set_required: function() {
1780 this.$element.toggleClass('oe_form_required', this.get("required"));
1782 set_value: function(value_) {
1783 this._inhibit_on_change = true;
1784 this.set({'value': value_});
1785 this._inhibit_on_change = false;
1787 get_value: function() {
1788 return this.get('value');
1790 is_valid: function() {
1791 return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1793 is_syntax_valid: function() {
1797 * Method useful to implement to ease validity testing. Must return true if the current
1798 * value is similar to false in OpenERP.
1800 is_false: function() {
1801 return this.get('value') === false;
1803 _check_css_flags: function(show_invalid) {
1804 if (this.field.translate) {
1805 this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1807 if (!this.disable_utility_classes) {
1808 if (this.field_manager.get('display_invalid_fields')) {
1809 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1816 * Utility method to focus an element, but only after a small amount of time.
1818 delay_focus: function($elem) {
1819 setTimeout(function() {
1824 * Utility method to get the widget options defined in the field xml description.
1826 get_definition_options: function() {
1827 if (!this.definition_options) {
1828 var str = this.node.attrs.options || '{}';
1829 this.definition_options = JSON.parse(str);
1831 return this.definition_options;
1833 set_input_id: function(id) {
1834 this.id_for_label = id;
1839 * A mixin to apply on any field that has to completely re-render when its readonly state
1842 instance.web.form.ReinitializeFieldMixin = {
1844 * Default implementation of start(), use it or call explicitly initialize_field().
1848 this.initialize_field();
1850 initialize_field: function() {
1851 this.on("change:effective_readonly", this, function() {
1852 this.destroy_content();
1853 this.renderElement();
1854 this.initialize_content();
1855 this.render_value();
1857 this.initialize_content();
1858 this.render_value();
1861 * Called to destroy anything that could have been created previously, called before a
1862 * re-initialization.
1864 destroy_content: function() {},
1866 * Called to initialize the content.
1868 initialize_content: function() {},
1870 * Called to render the value. Should also be explicitly called at the end of a set_value().
1872 render_value: function() {},
1875 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1876 template: 'FieldChar',
1877 widget_class: 'oe_form_field_char',
1878 init: function (field_manager, node) {
1879 this._super(field_manager, node);
1880 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1882 initialize_content: function() {
1884 this.$element.find('input').change(function() {
1885 self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1888 set_value: function(value_) {
1889 this._super(value_);
1890 this.render_value();
1892 render_value: function() {
1893 var show_value = instance.web.format_value(this.get('value'), this, '');
1894 if (!this.get("effective_readonly")) {
1895 this.$element.find('input').val(show_value);
1897 if (this.password) {
1898 show_value = new Array(show_value.length + 1).join('*');
1900 this.$element.text(show_value);
1903 is_syntax_valid: function() {
1904 if (!this.get("effective_readonly")) {
1906 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1914 is_false: function() {
1915 return this.get('value') === '' || this._super();
1918 this.delay_focus(this.$element.find('input:first'));
1922 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1926 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1927 template: 'FieldEmail',
1928 initialize_content: function() {
1930 this.$element.find('button').click(this.on_button_clicked);
1932 render_value: function() {
1933 if (!this.get("effective_readonly")) {
1936 this.$element.find('a')
1937 .attr('href', 'mailto:' + this.get('value'))
1938 .text(this.get('value'));
1941 on_button_clicked: function() {
1942 if (!this.get('value') || !this.is_syntax_valid()) {
1943 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1945 location.href = 'mailto:' + this.get('value');
1950 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1951 template: 'FieldUrl',
1952 initialize_content: function() {
1954 this.$element.find('button').click(this.on_button_clicked);
1956 render_value: function() {
1957 if (!this.get("effective_readonly")) {
1960 var tmp = this.get('value');
1961 var s = /(\w+):(.+)/.exec(tmp);
1963 tmp = "http://" + this.get('value');
1965 this.$element.find('a').attr('href', tmp).text(tmp);
1968 on_button_clicked: function() {
1969 if (!this.get('value')) {
1970 this.do_warn("Resource error", "This resource is empty");
1972 var url = $.trim(this.get('value'));
1973 if(/^www\./i.test(url))
1974 url = 'http://'+url;
1980 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1981 is_field_number: true,
1982 widget_class: 'oe_form_field_float',
1983 init: function (field_manager, node) {
1984 this._super(field_manager, node);
1985 this.set({'value': 0});
1986 if (this.node.attrs.digits) {
1987 this.digits = py.eval(node.attrs.digits);
1989 this.digits = this.field.digits;
1992 set_value: function(value_) {
1993 if (value_ === false || value_ === undefined) {
1994 // As in GTK client, floats default to 0
1997 this._super.apply(this, [value_]);
2001 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
2002 template: "web.datepicker",
2003 jqueryui_object: 'datetimepicker',
2004 type_of_date: "datetime",
2005 init: function(parent) {
2006 this._super(parent);
2007 this.name = parent.name;
2011 this.$input = this.$element.find('input.oe_datepicker_master');
2012 this.$input_picker = this.$element.find('input.oe_datepicker_container');
2013 this.$input.change(this.on_change);
2015 onSelect: this.on_picker_select,
2019 showButtonPanel: true
2021 this.$element.find('img.oe_datepicker_trigger').click(function() {
2022 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
2023 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
2024 self.$input_picker.show();
2025 self.picker('show');
2026 self.$input_picker.hide();
2029 this.set_readonly(false);
2030 this.set({'value': false});
2032 picker: function() {
2033 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
2035 on_picker_select: function(text, instance_) {
2036 var date = this.picker('getDate');
2037 this.$input.val(date ? this.format_client(date) : '').change();
2039 set_value: function(value_) {
2040 this.set({'value': value_});
2041 this.$input.val(value_ ? this.format_client(value_) : '');
2043 get_value: function() {
2044 return this.get('value');
2046 set_value_from_ui_: function() {
2047 var value_ = this.$input.val() || false;
2048 this.set({'value': this.parse_client(value_)});
2050 set_readonly: function(readonly) {
2051 this.readonly = readonly;
2052 this.$input.prop('readonly', this.readonly);
2053 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2055 is_valid_: function() {
2056 var value_ = this.$input.val();
2057 if (value_ === "") {
2061 this.parse_client(value_);
2068 parse_client: function(v) {
2069 return instance.web.parse_value(v, {"widget": this.type_of_date});
2071 format_client: function(v) {
2072 return instance.web.format_value(v, {"widget": this.type_of_date});
2074 on_change: function() {
2075 if (this.is_valid_()) {
2076 this.set_value_from_ui_();
2081 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2082 jqueryui_object: 'datepicker',
2083 type_of_date: "date"
2086 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2087 template: "FieldDatetime",
2088 build_widget: function() {
2089 return new instance.web.DateTimeWidget(this);
2091 destroy_content: function() {
2092 if (this.datewidget) {
2093 this.datewidget.destroy();
2094 this.datewidget = undefined;
2097 initialize_content: function() {
2098 if (!this.get("effective_readonly")) {
2099 this.datewidget = this.build_widget();
2100 this.datewidget.on_change.add_last(_.bind(function() {
2101 this.set({'value': this.datewidget.get_value()});
2103 this.datewidget.appendTo(this.$element);
2106 set_value: function(value_) {
2107 this._super(value_);
2108 this.render_value();
2110 render_value: function() {
2111 if (!this.get("effective_readonly")) {
2112 this.datewidget.set_value(this.get('value'));
2114 this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2117 is_syntax_valid: function() {
2118 if (!this.get("effective_readonly")) {
2119 return this.datewidget.is_valid_();
2123 is_false: function() {
2124 return this.get('value') === '' || this._super();
2127 if (this.datewidget && this.datewidget.$input)
2128 this.delay_focus(this.datewidget.$input);
2132 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2133 template: "FieldDate",
2134 build_widget: function() {
2135 return new instance.web.DateWidget(this);
2139 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2140 template: 'FieldText',
2141 initialize_content: function() {
2142 this.$textarea = this.$element.find('textarea');
2143 if (!this.get("effective_readonly")) {
2144 this.$textarea.change(_.bind(function() {
2145 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2148 this.$textarea.attr('disabled', 'disabled');
2151 set_value: function(value_) {
2152 this._super.apply(this, arguments);
2153 this.render_value();
2155 render_value: function() {
2156 var show_value = instance.web.format_value(this.get('value'), this, '');
2157 this.$textarea.val(show_value);
2158 if (show_value && this.view.options.resize_textareas) {
2159 this.do_resize(this.view.options.resize_textareas);
2162 is_syntax_valid: function() {
2163 if (!this.get("effective_readonly")) {
2165 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2173 is_false: function() {
2174 return this.get('value') === '' || this._super();
2176 focus: function($element) {
2177 this.delay_focus(this.$textarea);
2179 do_resize: function(max_height) {
2180 max_height = parseInt(max_height, 10);
2181 var $input = this.$textarea,
2182 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2184 $div.text($input.val());
2185 _.each('font-family,font-size,white-space'.split(','), function(style) {
2186 $div.css(style, $input.css(style));
2188 $div.appendTo($('body'));
2189 new_height = $div.height();
2190 if (new_height < 90) {
2193 if (!isNaN(max_height) && new_height > max_height) {
2194 new_height = max_height;
2197 $input.height(new_height);
2201 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2202 template: 'FieldBoolean',
2204 this._super.apply(this, arguments);
2205 this.$checkbox = $("input", this.$element);
2206 this.$element.click(_.bind(function() {
2207 this.set({'value': this.$checkbox.is(':checked')});
2209 var check_readonly = function() {
2210 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2212 this.on("change:effective_readonly", this, check_readonly);
2213 _.bind(check_readonly, this)();
2215 set_value: function(value_) {
2216 this._super.apply(this, arguments);
2217 this.$checkbox[0].checked = value_;
2220 this.delay_focus(this.$checkbox);
2224 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2225 template: 'FieldProgressBar',
2227 this._super.apply(this, arguments);
2228 this.$element.progressbar({
2229 value: this.get('value'),
2230 disabled: this.get("effective_readonly")
2233 set_value: function(value_) {
2234 this._super.apply(this, arguments);
2235 var show_value = Number(value_);
2236 if (isNaN(show_value)) {
2239 var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2240 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2244 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2245 // to replace view editor
2248 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2249 template: 'FieldSelection',
2250 init: function(field_manager, node) {
2252 this._super(field_manager, node);
2253 this.values = _.clone(this.field.selection);
2254 _.each(this.values, function(v, i) {
2255 if (v[0] === false && v[1] === '') {
2256 self.values.splice(i, 1);
2259 this.values.unshift([false, '']);
2261 initialize_content: function() {
2262 // Flag indicating whether we're in an event chain containing a change
2263 // event on the select, in order to know what to do on keyup[RETURN]:
2264 // * If the user presses [RETURN] as part of changing the value of a
2265 // selection, we should just let the value change and not let the
2266 // event broadcast further (e.g. to validating the current state of
2267 // the form in editable list view, which would lead to saving the
2268 // current row or switching to the next one)
2269 // * If the user presses [RETURN] with a select closed (side-effect:
2270 // also if the user opened the select and pressed [RETURN] without
2271 // changing the selected value), takes the action as validating the
2273 var ischanging = false;
2274 this.$element.find('select')
2275 .change(_.bind(function() {
2276 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2278 .change(function () { ischanging = true; })
2279 .click(function () { ischanging = false; })
2280 .keyup(function (e) {
2281 if (e.which !== 13 || !ischanging) { return; }
2282 e.stopPropagation();
2286 set_value: function(value_) {
2287 value_ = value_ === null ? false : value_;
2288 value_ = value_ instanceof Array ? value_[0] : value_;
2289 this._super(value_);
2290 this.render_value();
2292 render_value: function() {
2293 if (!this.get("effective_readonly")) {
2295 for (var i = 0, ii = this.values.length; i < ii; i++) {
2296 if (this.values[i][0] === this.get('value')) index = i;
2298 this.$element.find('select')[0].selectedIndex = index;
2301 var option = _(this.values)
2302 .detect(function (record) { return record[0] === self.get('value'); });
2303 this.$element.text(option ? option[1] : this.values[0][1]);
2306 is_syntax_valid: function() {
2307 if (this.get("effective_readonly")) {
2310 var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2314 this.delay_focus(this.$element.find('select:first'));
2318 // jquery autocomplete tweak to allow html
2320 var proto = $.ui.autocomplete.prototype,
2321 initSource = proto._initSource;
2323 function filter( array, term ) {
2324 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2325 return $.grep( array, function(value_) {
2326 return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2331 _initSource: function() {
2332 if ( this.options.html && $.isArray(this.options.source) ) {
2333 this.source = function( request, response ) {
2334 response( filter( this.options.source, request.term ) );
2337 initSource.call( this );
2341 _renderItem: function( ul, item) {
2342 return $( "<li></li>" )
2343 .data( "item.autocomplete", item )
2344 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2351 * A mixin containing some useful methods to handle completion inputs.
2353 instance.web.form.CompletionFieldMixin = {
2356 this.orderer = new instance.web.DropMisordered();
2359 * Call this method to search using a string.
2361 get_search_result: function(search_val) {
2364 var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2365 var blacklist = this.get_search_blacklist();
2367 return this.orderer.add(dataset.name_search(
2368 search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
2369 'ilike', this.limit + 1)).pipe(function(data) {
2370 self.last_search = data;
2371 // possible selections for the m2o
2372 var values = _.map(data, function(x) {
2374 label: _.str.escapeHTML(x[1]),
2381 // search more... if more results that max
2382 if (values.length > self.limit) {
2383 values = values.slice(0, self.limit);
2384 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2385 dataset.name_search(search_val, self.build_domain(), 'ilike'
2386 , false, function(data) {
2387 self._search_create_popup("search", data);
2392 var raw_result = _(data.result).map(function(x) {return x[1];});
2393 if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2394 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2395 $('<span />').text(search_val).html()), action: function() {
2396 self._quick_create(search_val);
2400 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2401 self._search_create_popup("form", undefined, {"default_name": search_val});
2407 get_search_blacklist: function() {
2410 _quick_create: function(name) {
2412 var slow_create = function () {
2413 self._search_create_popup("form", undefined, {"default_name": name});
2415 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2416 new instance.web.DataSet(this, this.field.relation, self.build_context())
2417 .name_create(name, function(data) {
2418 self.add_id(data[0]);
2419 }).fail(function(error, event) {
2420 event.preventDefault();
2426 // all search/create popup handling
2427 _search_create_popup: function(view, ids, context) {
2429 var pop = new instance.web.form.SelectCreatePopup(this);
2431 self.field.relation,
2433 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2434 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2436 disable_multiple_selection: true
2438 self.build_domain(),
2439 new instance.web.CompoundContext(self.build_context(), context || {})
2441 pop.on_select_elements.add(function(element_ids) {
2442 self.add_id(element_ids[0]);
2448 add_id: function(id) {},
2451 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2452 instance.web.form.CompletionFieldMixin, {
2453 template: "FieldMany2One",
2454 init: function(field_manager, node) {
2455 this._super(field_manager, node);
2456 instance.web.form.CompletionFieldMixin.init.call(this);
2457 this.set({'value': false});
2458 this.display_value = {};
2459 this.last_search = [];
2460 this.floating = false;
2461 this.inhibit_on_change = false;
2465 instance.web.form.ReinitializeFieldMixin.start.call(this);
2466 this.on("change:value", this, function() {
2467 this.floating = false;
2468 this.render_value();
2471 initialize_content: function() {
2472 if (!this.get("effective_readonly"))
2473 this.render_editable();
2474 this.render_value();
2476 render_editable: function() {
2478 this.$input = this.$element.find("input");
2482 return "No element was selected, you should create or select one from the dropdown list.";
2488 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2489 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2491 this.$follow_button.click(function() {
2492 if (!self.get('value')) {
2495 var pop = new instance.web.form.FormOpenPopup(self.view);
2497 self.field.relation,
2499 self.build_context(),
2501 title: _t("Open: ") + (self.string || self.name)
2504 pop.on_write_completed.add_last(function() {
2505 self.display_value = {};
2506 self.render_value();
2510 // some behavior for input
2511 this.$input.keyup(function() {
2512 if (self.$input.val() === "") {
2513 self.set({value: false});
2515 self.floating = true;
2518 this.$drop_down.click(function() {
2519 if (self.$input.autocomplete("widget").is(":visible")) {
2520 self.$input.autocomplete("close");
2522 if (self.get("value") && ! self.floating) {
2523 self.$input.autocomplete("search", "");
2525 self.$input.autocomplete("search");
2527 self.$input.focus();
2530 var tip_def = $.Deferred();
2531 var untip_def = $.Deferred();
2532 var tip_delay = 200;
2533 var tip_duration = 3000;
2534 var anyoneLoosesFocus = function() {
2535 if (self.floating) {
2536 if (self.last_search.length > 0) {
2537 if (self.last_search[0][0] != self.get("value")) {
2538 self.display_value = {};
2539 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2540 self.set({value: self.last_search[0][0]});
2542 self.render_value();
2545 self.set({value: false});
2548 if (! self.get("value")) {
2551 tip_def = $.Deferred();
2552 tip_def.then(function() {
2553 self.$input.tipsy("show");
2555 setTimeout(function() {
2558 untip_def = $.Deferred();
2559 untip_def.then(function() {
2560 self.$input.tipsy("hide");
2562 setTimeout(function() {untip_def.resolve();}, tip_duration);
2568 this.$input.focusout(anyoneLoosesFocus);
2570 var isSelecting = false;
2572 this.$input.autocomplete({
2573 source: function(req, resp) {
2574 self.get_search_result(req.term).then(function(result) {
2578 select: function(event, ui) {
2582 self.display_value = {};
2583 self.display_value["" + item.id] = item.name;
2584 self.set({value: item.id});
2585 } else if (item.action) {
2586 self.floating = true;
2591 focus: function(e, ui) {
2595 close: anyoneLoosesFocus,
2599 this.$input.autocomplete("widget").addClass("openerp");
2600 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2601 this.$input.keyup(function(e) {
2602 if (e.which === 13) {
2604 e.stopPropagation();
2606 isSelecting = false;
2610 render_value: function(no_recurse) {
2612 if (! this.get("value")) {
2613 this.display_string("");
2616 var display = this.display_value["" + this.get("value")];
2618 this.display_string(display);
2622 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2623 dataset.name_get([self.get("value")], function(data) {
2624 self.display_value["" + self.get("value")] = data[0][1];
2625 self.render_value(true);
2629 display_string: function(str) {
2631 if (!this.get("effective_readonly")) {
2632 this.$input.val(str);
2634 this.$element.find('a')
2637 .click(function () {
2639 type: 'ir.actions.act_window',
2640 res_model: self.field.relation,
2641 res_id: self.get("value"),
2642 context: self.build_context(),
2643 views: [[false, 'form']],
2650 set_value: function(value_) {
2652 if (value_ instanceof Array) {
2653 this.display_value = {};
2654 this.display_value["" + value_[0]] = value_[1];
2657 value_ = value_ || false;
2658 this.inhibit_on_change = true;
2659 this._super(value_);
2660 this.inhibit_on_change = false;
2662 add_id: function(id) {
2663 this.display_value = {};
2664 this.set({value: id});
2666 is_false: function() {
2667 return ! this.get("value");
2669 focus: function () {
2670 this.delay_focus(this.$input);
2675 # Values: (0, 0, { fields }) create
2676 # (1, ID, { fields }) update
2677 # (2, ID) remove (delete)
2678 # (3, ID) unlink one (target id or target of relation)
2680 # (5) unlink all (only valid for one2many)
2685 'create': function (values) {
2686 return [commands.CREATE, false, values];
2688 // (1, id, {values})
2690 'update': function (id, values) {
2691 return [commands.UPDATE, id, values];
2695 'delete': function (id) {
2696 return [commands.DELETE, id, false];
2698 // (3, id[, _]) removes relation, but not linked record itself
2700 'forget': function (id) {
2701 return [commands.FORGET, id, false];
2705 'link_to': function (id) {
2706 return [commands.LINK_TO, id, false];
2710 'delete_all': function () {
2711 return [5, false, false];
2713 // (6, _, ids) replaces all linked records with provided ids
2715 'replace_with': function (ids) {
2716 return [6, false, ids];
2719 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2720 multi_selection: false,
2721 disable_utility_classes: true,
2722 init: function(field_manager, node) {
2723 this._super(field_manager, node);
2724 lazy_build_o2m_kanban_view();
2725 this.is_loaded = $.Deferred();
2726 this.initial_is_loaded = this.is_loaded;
2727 this.is_setted = $.Deferred();
2728 this.form_last_update = $.Deferred();
2729 this.init_form_last_update = this.form_last_update;
2732 this._super.apply(this, arguments);
2736 this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2737 this.dataset.o2m = this;
2738 this.dataset.parent_view = this.view;
2739 this.dataset.child_name = this.name;
2740 //this.dataset.child_name =
2741 this.dataset.on_change.add_last(function() {
2742 self.trigger_on_change();
2745 this.is_setted.then(function() {
2748 this.is_loaded.then(function() {
2749 self.on("change:effective_readonly", self, function() {
2750 self.is_loaded = self.is_loaded.pipe(function() {
2751 self.viewmanager.destroy();
2752 return $.when(self.load_views()).then(function() {
2753 self.reload_current_view();
2759 trigger_on_change: function() {
2760 var tmp = this.doing_on_change;
2761 this.doing_on_change = true;
2762 this.trigger('changed_value');
2763 this.doing_on_change = tmp;
2765 load_views: function() {
2768 var modes = this.node.attrs.mode;
2769 modes = !!modes ? modes.split(",") : ["tree"];
2771 _.each(modes, function(mode) {
2774 view_type: mode == "tree" ? "list" : mode,
2777 if (self.field.views && self.field.views[mode]) {
2778 view.embedded_view = self.field.views[mode];
2780 if(view.view_type === "list") {
2781 view.options.selectable = self.multi_selection;
2782 if (self.get("effective_readonly")) {
2783 view.options.addable = null;
2784 view.options.deletable = null;
2786 } else if (view.view_type === "form") {
2787 if (self.get("effective_readonly")) {
2788 view.view_type = 'form';
2790 view.options.not_interactible_on_create = true;
2791 } else if (view.view_type === "kanban") {
2792 view.options.confirm_on_delete = false;
2793 view.options.sortable = false;
2794 if (self.get("effective_readonly")) {
2795 view.options.action_buttons = false;
2796 view.options.quick_creatable = false;
2797 view.options.creatable = false;
2798 view.options.read_only_mode = true;
2805 this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2806 this.viewmanager.o2m = self;
2807 var once = $.Deferred().then(function() {
2808 self.init_form_last_update.resolve();
2810 var def = $.Deferred().then(function() {
2811 self.initial_is_loaded.resolve();
2813 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2814 controller.o2m = self;
2815 if (view_type == "list") {
2816 if (self.get("effective_readonly"))
2817 controller.set_editable(false);
2818 } else if (view_type === "form") {
2819 if (self.get("effective_readonly")) {
2820 $(".oe_form_buttons", controller.$element).children().remove();
2822 controller.on_record_loaded.add_last(function() {
2825 controller.on_pager_action.add_first(function() {
2826 self.save_any_view();
2828 } else if (view_type == "graph") {
2829 self.reload_current_view()
2833 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2834 $.when(self.save_any_view()).then(function() {
2835 if(n_mode === "list")
2836 $.async_when().then(function() {self.reload_current_view();});
2839 this.is_setted.then(function() {
2840 $.async_when().then(function () {
2841 self.viewmanager.appendTo(self.$element);
2846 reload_current_view: function() {
2848 return self.is_loaded = self.is_loaded.pipe(function() {
2849 var active_view = self.viewmanager.active_view;
2850 var view = self.viewmanager.views[active_view].controller;
2851 if(active_view === "list") {
2852 return view.reload_content();
2853 } else if (active_view === "form") {
2854 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2855 self.dataset.index = 0;
2857 var act = function() {
2858 return view.do_show();
2860 self.form_last_update = self.form_last_update.pipe(act, act);
2861 return self.form_last_update;
2862 } else if (view.do_search) {
2863 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2867 set_value: function(value_) {
2868 value_ = value_ || [];
2870 this.dataset.reset_ids([]);
2871 if(value_.length >= 1 && value_[0] instanceof Array) {
2873 _.each(value_, function(command) {
2874 var obj = {values: command[2]};
2875 switch (command[0]) {
2876 case commands.CREATE:
2877 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2879 self.dataset.to_create.push(obj);
2880 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2883 case commands.UPDATE:
2884 obj['id'] = command[1];
2885 self.dataset.to_write.push(obj);
2886 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2889 case commands.DELETE:
2890 self.dataset.to_delete.push({id: command[1]});
2892 case commands.LINK_TO:
2893 ids.push(command[1]);
2895 case commands.DELETE_ALL:
2896 self.dataset.delete_all = true;
2901 this.dataset.set_ids(ids);
2902 } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2904 this.dataset.delete_all = true;
2905 _.each(value_, function(command) {
2906 var obj = {values: command};
2907 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2909 self.dataset.to_create.push(obj);
2910 self.dataset.cache.push(_.clone(obj));
2914 this.dataset.set_ids(ids);
2916 this._super(value_);
2917 this.dataset.reset_ids(value_);
2919 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2920 this.dataset.index = 0;
2922 self.is_setted.resolve();
2923 return self.reload_current_view();
2925 get_value: function() {
2929 this.save_any_view();
2930 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2931 val = val.concat(_.map(this.dataset.ids, function(id) {
2932 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2934 return commands.create(alter_order.values);
2936 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2938 return commands.update(alter_order.id, alter_order.values);
2940 return commands.link_to(id);
2942 return val.concat(_.map(
2943 this.dataset.to_delete, function(x) {
2944 return commands['delete'](x.id);}));
2946 save_any_view: function() {
2947 if (this.doing_on_change)
2949 return this.session.synchronized_mode(_.bind(function() {
2950 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2951 this.viewmanager.views[this.viewmanager.active_view] &&
2952 this.viewmanager.views[this.viewmanager.active_view].controller) {
2953 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2954 if (this.viewmanager.active_view === "form") {
2955 if (!view.is_initialized.isResolved()) {
2958 var res = $.when(view.do_save());
2959 if (!res.isResolved() && !res.isRejected()) {
2960 console.warn("Asynchronous get_value() is not supported in form view.");
2963 } else if (this.viewmanager.active_view === "list") {
2964 var res = $.when(view.ensure_saved());
2965 if (!res.isResolved() && !res.isRejected()) {
2966 console.warn("Asynchronous get_value() is not supported in list view.");
2974 is_syntax_valid: function() {
2975 if (!this.viewmanager.views[this.viewmanager.active_view])
2977 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2978 if (this.viewmanager.active_view === "form") {
2979 for (var f in view.fields) {
2981 if (!f.is_valid()) {
2990 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
2991 template: 'One2Many.viewmanager',
2992 init: function(parent, dataset, views, flags) {
2993 this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
2994 this.registry = this.registry.extend({
2995 list: 'instance.web.form.One2ManyListView',
2996 form: 'instance.web.form.One2ManyFormView',
2997 kanban: 'instance.web.form.One2ManyKanbanView',
3000 switch_view: function(mode, unused) {
3001 if (mode !== 'form') {
3002 return this._super(mode, unused);
3005 var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
3006 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3007 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3008 title: _t("Open: ") + self.name,
3009 create_function: function(data) {
3010 return self.o2m.dataset.create(data).then(function(r) {
3011 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3012 self.o2m.dataset.on_change();
3015 write_function: function(id, data, options) {
3016 return self.o2m.dataset.write(id, data, {}).then(function() {
3017 self.o2m.reload_current_view();
3020 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3021 parent_view: self.o2m.view,
3022 child_name: self.o2m.name,
3023 read_function: function() {
3024 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3026 form_view_options: {'not_interactible_on_create':true},
3027 readonly: self.o2m.get("effective_readonly")
3029 pop.on_select_elements.add_last(function() {
3030 self.o2m.reload_current_view();
3035 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
3036 get_context: function() {
3037 this.context = this.o2m.build_context([this.o2m.name]);
3038 return this.context;
3042 instance.web.form.One2ManyListView = instance.web.ListView.extend({
3043 _template: 'One2Many.listview',
3044 do_add_record: function () {
3045 if (this.options.editable) {
3046 this._super.apply(this, arguments);
3049 var pop = new instance.web.form.SelectCreatePopup(this);
3051 self.o2m.field.relation,
3053 title: _t("Create: ") + self.name,
3054 initial_view: "form",
3055 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3056 create_function: function(data, callback, error_callback) {
3057 return self.o2m.dataset.create(data).then(function(r) {
3058 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3059 self.o2m.dataset.on_change();
3060 }).then(callback, error_callback);
3062 read_function: function() {
3063 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3065 parent_view: self.o2m.view,
3066 child_name: self.o2m.name,
3067 form_view_options: {'not_interactible_on_create':true}
3069 self.o2m.build_domain(),
3070 self.o2m.build_context()
3072 pop.on_select_elements.add_last(function() {
3073 self.o2m.reload_current_view();
3077 do_activate_record: function(index, id) {
3079 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3080 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3081 title: _t("Open: ") + self.name,
3082 write_function: function(id, data) {
3083 return self.o2m.dataset.write(id, data, {}, function(r) {
3084 self.o2m.reload_current_view();
3087 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3088 parent_view: self.o2m.view,
3089 child_name: self.o2m.name,
3090 read_function: function() {
3091 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3093 form_view_options: {'not_interactible_on_create':true},
3094 readonly: self.o2m.get("effective_readonly")
3097 do_button_action: function (name, id, callback) {
3099 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3100 return this._super(name, id, _.bind(def.resolve, def));
3104 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3105 form_template: 'One2Many.formview',
3106 on_loaded: function(data) {
3109 this.$buttons.find('button.oe_form_button_create').click(function() {
3110 self.do_save().then(self.on_button_new);
3113 do_notify_change: function() {
3114 if (this.dataset.parent_view) {
3115 this.dataset.parent_view.do_notify_change();
3117 this._super.apply(this, arguments);
3122 var lazy_build_o2m_kanban_view = function() {
3123 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3125 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3129 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3130 instance.web.form.ReinitializeFieldMixin, {
3131 template: "FieldMany2ManyTags",
3133 this._super.apply(this, arguments);
3134 instance.web.form.CompletionFieldMixin.init.call(this);
3135 this.set({"value": []});
3136 this._display_orderer = new instance.web.DropMisordered();
3137 this._drop_shown = false;
3141 instance.web.form.ReinitializeFieldMixin.start.call(this);
3142 this.on("change:value", this, this.render_value);
3144 initialize_content: function() {
3145 if (this.get("effective_readonly"))
3148 self.$text = $("textarea", this.$element);
3149 self.$text.textext({
3150 plugins : 'tags arrow autocomplete',
3152 render: function(suggestion) {
3153 return $('<span class="text-label"/>').
3154 data('index', suggestion['index']).html(suggestion['label']);
3159 selectFromDropdown: function() {
3160 $(this).trigger('hideDropdown');
3161 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3162 var data = self.search_result[index];
3164 self.add_id(data.id);
3171 isTagAllowed: function(tag) {
3176 removeTag: function(tag) {
3177 var id = tag.data("id");
3178 self.set({"value": _.without(self.get("value"), id)});
3180 renderTag: function(stuff) {
3181 return $.fn.textext.TextExtTags.prototype.renderTag.
3182 call(this, stuff).data("id", stuff.id);
3186 itemToString: function(item) {
3191 }).bind('getSuggestions', function(e, data) {
3193 var str = !!data ? data.query || '' : '';
3194 self.get_search_result(str).then(function(result) {
3195 self.search_result = result;
3196 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3197 return _.extend(el, {index:i});
3200 }).bind('hideDropdown', function() {
3201 self._drop_shown = false;
3202 }).bind('showDropdown', function() {
3203 self._drop_shown = true;
3205 self.tags = self.$text.textext()[0].tags();
3206 $("textarea", this.$element).focusout(function() {
3207 self.$text.trigger("setInputData", "");
3208 }).keydown(function(e) {
3209 if (event.keyCode === 9 && self._drop_shown) {
3210 self.$text.textext()[0].autocomplete().selectFromDropdown();
3214 set_value: function(value_) {
3215 value_ = value_ || [];
3216 if (value_.length >= 1 && value_[0] instanceof Array) {
3217 value_ = value_[0][2];
3219 this._super(value_);
3221 get_value: function() {
3222 var tmp = [commands.replace_with(this.get("value"))];
3225 get_search_blacklist: function() {
3226 return this.get("value");
3228 render_value: function() {
3230 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3231 var handle_names = function(data) {
3233 _.each(data, function(el) {
3234 indexed[el[0]] = el;
3236 data = _.map(self.get("value"), function(el) { return indexed[el]; });
3237 if (! self.get("effective_readonly")) {
3238 self.tags.containerElement().children().remove();
3239 $("textarea", self.$element).css("padding-left", "3px");
3240 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3242 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3245 if (! self.get('values') || self.get('values').length > 0) {
3246 this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3251 add_id: function(id) {
3252 this.set({'value': _.uniq(this.get('value').concat([id]))});
3257 * TODO niv: clean those deferred stuff, it could be better
3259 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3260 multi_selection: false,
3261 disable_utility_classes: true,
3262 init: function(field_manager, node) {
3263 this._super(field_manager, node);
3264 this.is_loaded = $.Deferred();
3265 this.initial_is_loaded = this.is_loaded;
3266 this.is_setted = $.Deferred();
3269 this._super.apply(this, arguments);
3273 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3274 this.dataset.m2m = this;
3275 this.dataset.on_unlink.add_last(function(ids) {
3276 self.dataset_changed();
3279 this.is_setted.then(function() {
3282 this.is_loaded.then(function() {
3283 self.on("change:effective_readonly", self, function() {
3284 self.is_loaded = self.is_loaded.pipe(function() {
3285 self.list_view.destroy();
3286 return $.when(self.load_view()).then(function() {
3287 self.reload_content();
3293 set_value: function(value_) {
3294 value_ = value_ || [];
3295 if (value_.length >= 1 && value_[0] instanceof Array) {
3296 value_ = value_[0][2];
3298 this._super(value_);
3299 this.dataset.set_ids(value_);
3301 self.reload_content();
3302 this.is_setted.resolve();
3304 get_value: function() {
3305 return [commands.replace_with(this.get('value'))];
3307 load_view: function() {
3309 this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3310 'addable': self.get("effective_readonly") ? null : _t("Add"),
3311 'deletable': self.get("effective_readonly") ? false : true,
3312 'selectable': self.multi_selection,
3315 var embedded = (this.field.views || {}).tree;
3317 this.list_view.set_embedded_view(embedded);
3319 this.list_view.m2m_field = this;
3320 var loaded = $.Deferred();
3321 this.list_view.on_loaded.add_last(function() {
3322 self.initial_is_loaded.resolve();
3325 $.async_when().then(function () {
3326 self.list_view.appendTo(self.$element);
3330 reload_content: function() {
3332 this.is_loaded = this.is_loaded.pipe(function() {
3333 return self.list_view.reload_content();
3336 dataset_changed: function() {
3337 this.set({'value': this.dataset.ids});
3341 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3342 get_context: function() {
3343 this.context = this.m2m.build_context();
3344 return this.context;
3350 * @extends instance.web.ListView
3352 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3353 do_add_record: function () {
3354 var pop = new instance.web.form.SelectCreatePopup(this);
3358 title: _t("Add: ") + this.name
3360 new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3361 this.m2m_field.build_context()
3364 pop.on_select_elements.add(function(element_ids) {
3365 _.each(element_ids, function(one_id) {
3366 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3367 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3368 self.m2m_field.dataset_changed();
3369 self.reload_content();
3374 do_activate_record: function(index, id) {
3376 var pop = new instance.web.form.FormOpenPopup(this);
3377 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3378 title: _t("Open: ") + this.name,
3379 readonly: this.getParent().get("effective_readonly")
3381 pop.on_write_completed.add_last(function() {
3382 self.reload_content();
3387 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3388 disable_utility_classes: true,
3389 init: function(field_manager, node) {
3390 this._super(field_manager, node);
3391 instance.web.form.CompletionFieldMixin.init.call(this);
3392 m2m_kanban_lazy_init();
3393 this.is_loaded = $.Deferred();
3394 this.initial_is_loaded = this.is_loaded;
3395 this.is_setted = $.Deferred();
3398 this._super.apply(this, arguments);
3402 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3403 this.dataset.m2m = this;
3404 this.dataset.on_unlink.add_last(function(ids) {
3405 self.dataset_changed();
3408 this.is_setted.then(function() {
3411 this.is_loaded.then(function() {
3412 self.on("change:effective_readonly", self, function() {
3413 self.is_loaded = self.is_loaded.pipe(function() {
3414 self.kanban_view.destroy();
3415 return $.when(self.load_view()).then(function() {
3416 self.reload_content();
3422 set_value: function(value_) {
3423 value_ = value_ || [];
3424 if (value_.length >= 1 && value_[0] instanceof Array) {
3425 value_ = value_[0][2];
3427 this._super(value_);
3428 this.dataset.set_ids(value_);
3430 self.reload_content();
3431 this.is_setted.resolve();
3433 load_view: function() {
3435 this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3436 'create_text': _t("Add"),
3437 'creatable': self.get("effective_readonly") ? false : true,
3438 'quick_creatable': self.get("effective_readonly") ? false : true,
3439 'read_only_mode': self.get("effective_readonly") ? true : false,
3440 'confirm_on_delete': false,
3442 var embedded = (this.field.views || {}).kanban;
3444 this.kanban_view.set_embedded_view(embedded);
3446 this.kanban_view.m2m = this;
3447 var loaded = $.Deferred();
3448 this.kanban_view.on_loaded.add_last(function() {
3449 self.initial_is_loaded.resolve();
3452 this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3453 $.async_when().then(function () {
3454 self.kanban_view.appendTo(self.$element);
3458 reload_content: function() {
3460 this.is_loaded = this.is_loaded.pipe(function() {
3461 return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3464 dataset_changed: function() {
3465 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3467 open_popup: function(type, unused) {
3468 if (type !== "form")
3471 if (this.dataset.index === null) {
3472 var pop = new instance.web.form.SelectCreatePopup(this);
3474 this.field.relation,
3476 title: _t("Add: ") + this.name
3478 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3479 this.build_context()
3481 pop.on_select_elements.add(function(element_ids) {
3482 _.each(element_ids, function(one_id) {
3483 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3484 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3485 self.dataset_changed();
3486 self.reload_content();
3491 var id = self.dataset.ids[self.dataset.index];
3492 var pop = new instance.web.form.FormOpenPopup(self.view);
3493 pop.show_element(self.field.relation, id, self.build_context(), {
3494 title: _t("Open: ") + self.name,
3495 write_function: function(id, data, options) {
3496 return self.dataset.write(id, data, {}).then(function() {
3497 self.reload_content();
3500 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3501 parent_view: self.view,
3502 child_name: self.name,
3503 readonly: self.get("effective_readonly")
3507 add_id: function(id) {
3508 this.quick_create.add_id(id);
3512 function m2m_kanban_lazy_init() {
3513 if (instance.web.form.Many2ManyKanbanView)
3515 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3516 quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3517 _is_quick_create_enabled: function() {
3518 return this._super() && ! this.group_by;
3521 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3522 template: 'Many2ManyKanban.quick_create',
3525 * close_btn: If true, the widget will display a "Close" button able to trigger
3528 init: function(parent, dataset, context, buttons) {
3529 this._super(parent);
3530 this.m2m = this.getParent().view.m2m;
3531 this.m2m.quick_create = this;
3532 this._dataset = dataset;
3533 this._buttons = buttons || false;
3534 this._context = context || {};
3536 start: function () {
3538 self.$text = this.$element.find('input').css("width", "200px");
3539 self.$text.textext({
3540 plugins : 'arrow autocomplete',
3542 render: function(suggestion) {
3543 return $('<span class="text-label"/>').
3544 data('index', suggestion['index']).html(suggestion['label']);
3549 selectFromDropdown: function() {
3550 $(this).trigger('hideDropdown');
3551 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3552 var data = self.search_result[index];
3554 self.add_id(data.id);
3561 itemToString: function(item) {
3566 }).bind('getSuggestions', function(e, data) {
3568 var str = !!data ? data.query || '' : '';
3569 self.m2m.get_search_result(str).then(function(result) {
3570 self.search_result = result;
3571 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3572 return _.extend(el, {index:i});
3576 self.$text.focusout(function() {
3583 add_id: function(id) {
3586 self.trigger('added', id);
3587 this.m2m.dataset_changed();
3593 * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3595 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3596 template: "AbstractFormPopup.render",
3599 * -readonly: only applicable when not in creation mode, default to false
3600 * - alternative_form_view
3606 * - form_view_options
3608 init_popup: function(model, row_id, domain, context, options) {
3609 this.row_id = row_id;
3611 this.domain = domain || [];
3612 this.context = context || {};
3613 this.options = options;
3614 _.defaults(this.options, {
3617 init_dataset: function() {
3619 this.created_elements = [];
3620 this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3621 this.dataset.read_function = this.options.read_function;
3622 this.dataset.create_function = function(data, sup) {
3623 var fct = self.options.create_function || sup;
3624 return fct.call(this, data).then(function(r) {
3625 self.created_elements.push(r.result);
3628 this.dataset.write_function = function(id, data, options, sup) {
3629 var fct = self.options.write_function || sup;
3630 return fct.call(this, id, data, options).then(self.on_write_completed);
3632 this.dataset.parent_view = this.options.parent_view;
3633 this.dataset.child_name = this.options.child_name;
3635 display_popup: function() {
3637 this.renderElement();
3638 new instance.web.Dialog(this, {
3642 self.check_exit(true);
3644 title: this.options.title || "",
3645 }, this.$element).open();
3648 on_write_completed: function() {},
3649 setup_form_view: function() {
3652 this.dataset.ids = [this.row_id];
3653 this.dataset.index = 0;
3655 this.dataset.index = null;
3657 var options = _.clone(self.options.form_view_options) || {};
3658 if (this.row_id !== null) {
3659 options.initial_mode = this.options.readonly ? "view" : "edit";
3661 this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3662 if (this.options.alternative_form_view) {
3663 this.view_form.set_embedded_view(this.options.alternative_form_view);
3665 this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3666 this.view_form.on_loaded.add_last(function() {
3667 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3668 var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3669 $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3670 var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3671 $snbutton.click(function() {
3672 $.when(self.view_form.do_save()).then(function() {
3673 self.view_form.reload_mutex.exec(function() {
3674 self.view_form.on_button_new();
3678 var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3679 $sbutton.click(function() {
3680 $.when(self.view_form.do_save()).then(function() {
3681 self.view_form.reload_mutex.exec(function() {
3686 var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3687 $cbutton.click(function() {
3690 if (self.row_id !== null && self.options.readonly) {
3693 $cbutton.text(_t("Close"));
3695 self.view_form.do_show();
3698 on_select_elements: function(element_ids) {
3700 check_exit: function(no_destroy) {
3701 if (this.created_elements.length > 0) {
3702 this.on_select_elements(this.created_elements);
3703 this.created_elements = [];
3707 destroy: function () {
3708 this.$element.dialog('close');
3714 * Class to display a popup containing a form view.
3716 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3717 show_element: function(model, row_id, context, options) {
3718 this.init_popup(model, row_id, [], context, options);
3719 _.defaults(this.options, {
3721 this.display_popup();
3725 this.init_dataset();
3726 this.setup_form_view();
3731 * Class to display a popup to display a list to search a row. It also allows
3732 * to switch to a form view to create a new row.
3734 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3738 * - initial_view: form or search (default search)
3739 * - disable_multiple_selection
3740 * - list_view_options
3742 select_element: function(model, options, domain, context) {
3743 this.init_popup(model, null, domain, context, options);
3745 _.defaults(this.options, {
3746 initial_view: "search",
3748 this.initial_ids = this.options.initial_ids;
3749 this.display_popup();
3753 this.init_dataset();
3754 if (this.options.initial_view == "search") {
3755 self.rpc('/web/session/eval_domain_and_context', {
3757 contexts: [this.context]
3758 }, function (results) {
3759 var search_defaults = {};
3760 _.each(results.context, function (value_, key) {
3761 var match = /^search_default_(.*)$/.exec(key);
3763 search_defaults[match[1]] = value_;
3766 self.setup_search_view(search_defaults);
3772 setup_search_view: function(search_defaults) {
3774 if (this.searchview) {
3775 this.searchview.destroy();
3777 this.searchview = new instance.web.SearchView(this,
3778 this.dataset, false, search_defaults);
3779 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3780 if (self.initial_ids) {
3781 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3782 contexts, groupbys);
3783 self.initial_ids = undefined;
3785 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3788 this.searchview.on_loaded.add_last(function () {
3789 self.view_list = new instance.web.form.SelectCreateListView(self,
3790 self.dataset, false,
3791 _.extend({'deletable': false,
3792 'selectable': !self.options.disable_multiple_selection,
3794 }, self.options.list_view_options || {}));
3795 self.view_list.popup = self;
3796 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3797 self.view_list.do_show();
3798 }).pipe(function() {
3799 self.searchview.do_search();
3801 self.view_list.on_loaded.add_last(function() {
3802 var $buttons = self.view_list.$element.find(".oe-actions");
3803 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3804 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3805 $cbutton.click(function() {
3808 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3809 if(self.options.disable_multiple_selection) {
3812 $sbutton.click(function() {
3813 self.on_select_elements(self.selected_ids);
3818 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3820 do_search: function(domains, contexts, groupbys) {
3822 this.rpc('/web/session/eval_domain_and_context', {
3823 domains: domains || [],
3824 contexts: contexts || [],
3825 group_by_seq: groupbys || []
3826 }, function (results) {
3827 self.view_list.do_search(results.domain, results.context, results.group_by);
3830 on_click_element: function(ids) {
3831 this.selected_ids = ids || [];
3832 if(this.selected_ids.length > 0) {
3833 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3835 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3838 new_object: function() {
3839 if (this.searchview) {
3840 this.searchview.hide();
3842 if (this.view_list) {
3843 this.view_list.$element.hide();
3845 this.setup_form_view();
3849 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3850 do_add_record: function () {
3851 this.popup.new_object();
3853 select_record: function(index) {
3854 this.popup.on_select_elements([this.dataset.ids[index]]);
3855 this.popup.destroy();
3857 do_select: function(ids, records) {
3858 this._super(ids, records);
3859 this.popup.on_click_element(ids);
3863 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3864 template: 'FieldReference',
3865 init: function(field_manager, node) {
3866 this._super(field_manager, node);
3867 this.reference_ready = true;
3869 on_nop: function() {
3871 on_selection_changed: function() {
3872 if (this.reference_ready) {
3873 var sel = this.selection.get_value();
3874 this.m2o.field.relation = sel;
3875 this.m2o.set_value(false);
3876 this.m2o.$element.toggle(sel !== false);
3879 destroy_content: function() {
3880 if (this.selection) {
3881 this.selection.destroy();
3882 this.selection = undefined;
3886 this.m2o = undefined;
3889 initialize_content: function() {
3890 this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3893 this.selection.view = this.view;
3894 this.selection.set({force_readonly: this.get('effective_readonly')});
3895 this.selection.on("change:value", this, this.on_selection_changed);
3896 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3897 this.selection.renderElement();
3898 this.selection.start();
3900 this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3903 this.m2o.view = this.view;
3904 this.m2o.set({force_readonly: this.get("effective_readonly")});
3905 this.m2o.on("change:value", this, this.data_changed);
3906 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3907 this.m2o.renderElement();
3910 is_false: function() {
3911 return typeof(this.get_value()) !== 'string';
3913 set_value: function(value_) {
3914 this._super(value_);
3915 this.render_value();
3917 render_value: function() {
3918 this.reference_ready = false;
3919 var vals = [], sel_val, m2o_val;
3920 if (typeof(this.get('value')) === 'string') {
3921 vals = this.get('value').split(',');
3923 sel_val = vals[0] || false;
3924 m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3925 if (!this.get("effective_readonly")) {
3926 this.selection.set_value(sel_val);
3928 this.m2o.field.relation = sel_val;
3929 this.m2o.set_value(m2o_val);
3930 this.reference_ready = true;
3932 data_changed: function() {
3933 var model = this.selection.get_value(),
3934 id = this.m2o.get_value();
3935 if (typeof(model) === 'string' && typeof(id) === 'number') {
3936 this.set({'value': model + ',' + id});
3938 this.set({'value': false});
3941 get_field: function(name) {
3942 if (name === "selection") {
3944 selection: this.view.fields_view.fields[this.name].selection,
3947 } else if (name === "m2o") {
3953 throw Exception("Should not happen");
3957 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3958 init: function(field_manager, node) {
3959 this._super(field_manager, node);
3960 this.iframe = this.element_id + '_iframe';
3961 this.binary_value = false;
3963 initialize_content: function() {
3964 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3965 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3966 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3968 human_filesize : function(size) {
3969 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3971 while (size >= 1024) {
3975 return size.toFixed(2) + ' ' + units[i];
3977 on_file_change: function(e) {
3978 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3979 // http://www.html5rocks.com/tutorials/file/dndfiles/
3980 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3981 window[this.iframe] = this.on_file_uploaded;
3982 if ($(e.target).val() != '') {
3983 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3984 this.$element.find('form.oe-binary-form').submit();
3985 this.$element.find('.oe-binary-progress').show();
3986 this.$element.find('.oe-binary').hide();
3989 on_file_uploaded: function(size, name, content_type, file_base64) {
3990 delete(window[this.iframe]);
3991 if (size === false) {
3992 this.do_warn("File Upload", "There was a problem while uploading your file");
3993 // TODO: use openerp web crashmanager
3994 console.warn("Error while uploading file : ", name);
3996 this.on_file_uploaded_and_valid.apply(this, arguments);
3998 this.$element.find('.oe-binary-progress').hide();
3999 this.$element.find('.oe-binary').show();
4001 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4003 on_save_as: function() {
4005 this.session.get_file({
4006 url: '/web/binary/saveas_ajax',
4007 data: {data: JSON.stringify({
4008 model: this.view.dataset.model,
4009 id: (this.view.datarecord.id || ''),
4011 filename_field: (this.node.attrs.filename || ''),
4012 context: this.view.dataset.get_context()
4014 complete: $.unblockUI,
4015 error: instance.webclient.crashmanager.on_rpc_error
4018 on_clear: function() {
4019 if (this.get('value') !== false) {
4020 this.binary_value = false;
4021 this.set({'value': false});
4027 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
4028 template: 'FieldBinaryFile',
4029 initialize_content: function() {
4031 if (this.get("effective_readonly")) {
4033 this.$element.find('a').click(function() {
4034 if (self.get('value')) {
4041 set_value: function(value_) {
4042 this._super.apply(this, arguments);
4043 this.render_value();
4045 render_value: function() {
4046 if (!this.get("effective_readonly")) {
4048 if (this.node.attrs.filename) {
4049 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4051 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4053 this.$element.find('input').eq(0).val(show_value);
4055 this.$element.find('a').show(!!this.get('value'));
4056 if (this.get('value')) {
4057 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4058 this.$element.find('a').text(show_value);
4062 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4063 this.binary_value = true;
4064 this.set({'value': file_base64});
4065 var show_value = name + " (" + this.human_filesize(size) + ")";
4066 this.$element.find('input').eq(0).val(show_value);
4067 this.set_filename(name);
4069 set_filename: function(value_) {
4070 var filename = this.node.attrs.filename;
4071 if (this.view.fields[filename]) {
4072 this.view.fields[filename].set({value: value_});
4075 on_clear: function() {
4076 this._super.apply(this, arguments);
4077 this.$element.find('input').eq(0).val('');
4078 this.set_filename('');
4082 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4083 template: 'FieldBinaryImage',
4084 initialize_content: function() {
4086 if (!this.get("effective_readonly")) {
4087 this.$element.find('.oe_form_field_image_controls').show();
4089 this.$element.find('.oe_form_field_image_controls').hide();
4092 set_value: function(value_) {
4093 this._super.apply(this, arguments);
4094 this.render_value();
4096 render_value: function() {
4098 if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4099 url = 'data:image/png;base64,' + this.get('value');
4100 } else if (this.get('value')) {
4101 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4102 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4104 url = "/web/static/src/img/placeholder.png";
4106 var img = QWeb.render("FieldBinaryImage-img", { widget: this, url: url });
4107 this.$element.find('> img').remove();
4108 this.$element.prepend(img);
4110 on_file_change: function() {
4111 this.render_value();
4112 this._super.apply(this, arguments);
4114 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4115 this.set({'value': file_base64});
4116 this.binary_value = true;
4117 this.render_value();
4119 on_clear: function() {
4120 this._super.apply(this, arguments);
4121 this.render_value();
4125 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4129 this.selected_value = null;
4130 // preview in start only for selection fields, because of the dynamic behavior of many2one fields.
4131 if (this.field.type in ['selection']) {
4135 set_value: function(value_) {
4137 this._super(value_);
4138 // find selected value:
4139 // - many2one: [2, "New"] -> 2
4140 // - selection: new -> new
4141 if (this.field.type == "many2one") {
4142 this.selected_value = value_[0];
4144 this.selected_value = value_;
4146 // trick to be sure all values are loaded in the form, therefore
4147 // enabling the evaluation of dynamic domains
4148 $.async_when().then(function() {
4149 return self.render_list();
4153 /** Get the status list and render them
4154 * to_show: [[identifier, value_to_display]] where
4155 * - identifier = key for a selection, id for a many2one
4156 * - display_val = label that will be displayed
4157 * - ex: [[0, "New"]] (many2one) or [["new", "In Progress"]] (selection)
4159 render_list: function() {
4161 // get selection values, filter them and render them
4162 var selection_done = this.get_selection().pipe(self.proxy('filter_selection')).pipe(self.proxy('render_elements'));
4165 /** Get the selection list to be displayed in the statusbar widget.
4166 * For selection fields: this is directly given by this.field.selection
4167 * For many2one fields :
4168 * - perform a search on the relation of the many2one field (given by
4170 * - get the field domain for the search
4171 * - self.build_domain() gives the domain given by the view or by
4173 * - if the optional statusbar_fold attribute is set to true, make
4174 * an AND with build_domain to hide all 'fold=true' columns
4175 * - make an OR with current value, to be sure it is displayed,
4176 * with the correct order, even if it is folded
4178 get_selection: function() {
4180 if (this.field.type == "many2one") {
4181 this.selection = [];
4182 // get fold information from widget
4183 var fold = ((this.node.attrs || {}).statusbar_fold || true);
4184 // build final domain: if fold option required, add the
4186 var domain = new instance.web.CompoundDomain(['|'], ['&'], self.build_domain(), [['fold', '=', false]], [['id', '=', self.selected_value]]);
4188 var domain = new instance.web.CompoundDomain(['|'], self.build_domain(), [['id', '=', self.selected_value]]);
4190 // get a DataSetSearch on the current field relation (ex: crm.lead.stage_id -> crm.case.stage)
4191 var model_ext = new instance.web.DataSetSearch(this, this.field.relation, self.build_context(), domain);
4193 var read_defer = model_ext.read_slice(['name'], {}).pipe( function (records) {
4194 _(records).each(function (record) {
4195 self.selection.push([record.id, record.name]);
4199 this.selection = this.field.selection;
4200 var read_defer = new $.Deferred().resolve();
4205 /** Filters this.selection, according to values coming from the statusbar_visible
4206 * attribute of the field. For example: statusbar_visible="draft,open"
4207 * Currently, the key of (key, label) pairs has to be used in the
4208 * selection of visible items. This feature is not meant to be used
4209 * with many2one fields.
4211 filter_selection: function() {
4213 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4214 function(x) { return _.str.trim(x); });
4215 shown = _.select(shown, function(x) { return x.length > 0; });
4217 if (shown.length == 0) {
4218 this.to_show = this.selection;
4220 this.to_show = _.select(this.selection, function(x) {
4221 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4226 /** Renders the widget. This function also checks for statusbar_colors='{"pending": "blue"}'
4227 * attribute in the widget. This allows to set a given color to a given
4228 * state (given by the key of (key, label)).
4230 render_elements: function () {
4231 var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4232 this.$element.html(content);
4234 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4235 var color = colors[this.selected_value];
4237 var elem = this.$element.find("li.oe_form_steps_active span");
4238 elem.css("color", color);
4244 * Registry of form fields, called by :js:`instance.web.FormView`.
4246 * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4247 * will substitute to the <field> tags as defined in OpenERP's views.
4249 instance.web.form.widgets = new instance.web.Registry({
4250 'char' : 'instance.web.form.FieldChar',
4251 'id' : 'instance.web.form.FieldID',
4252 'email' : 'instance.web.form.FieldEmail',
4253 'url' : 'instance.web.form.FieldUrl',
4254 'text' : 'instance.web.form.FieldText',
4255 'date' : 'instance.web.form.FieldDate',
4256 'datetime' : 'instance.web.form.FieldDatetime',
4257 'selection' : 'instance.web.form.FieldSelection',
4258 'many2one' : 'instance.web.form.FieldMany2One',
4259 'many2many' : 'instance.web.form.FieldMany2Many',
4260 'many2many_tags' : 'instance.web.form.FieldMany2ManyTags',
4261 'many2many_kanban' : 'instance.web.form.FieldMany2ManyKanban',
4262 'one2many' : 'instance.web.form.FieldOne2Many',
4263 'one2many_list' : 'instance.web.form.FieldOne2Many',
4264 'reference' : 'instance.web.form.FieldReference',
4265 'boolean' : 'instance.web.form.FieldBoolean',
4266 'float' : 'instance.web.form.FieldFloat',
4267 'integer': 'instance.web.form.FieldFloat',
4268 'float_time': 'instance.web.form.FieldFloat',
4269 'progressbar': 'instance.web.form.FieldProgressBar',
4270 'image': 'instance.web.form.FieldBinaryImage',
4271 'binary': 'instance.web.form.FieldBinaryFile',
4272 'statusbar': 'instance.web.form.FieldStatus'
4276 * Registry of widgets usable in the form view that can substitute to any possible
4277 * tags defined in OpenERP's form views.
4279 * Every referenced class should extend FormWidget.
4281 instance.web.form.tags = new instance.web.Registry({
4282 'button' : 'instance.web.form.WidgetButton',
4287 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: