1 openerp.web.form = function (instance) {
2 var _t = instance.web._t,
3 _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
7 instance.web.form = {};
10 * Interface implemented by the form view or any other object
11 * able to provide the features necessary for the fields to work.
14 * - display_invalid_fields : if true, all fields where is_valid() return true should
15 * be displayed as invalid.
17 * - view_content_has_changed : when the values of the fields have changed. When
18 * this event is triggered all fields should reprocess their modifiers.
20 instance.web.form.FieldManagerMixin = {
22 * Must return the asked field as in fields_get.
24 get_field: function(field_name) {},
26 * Called by the field when the translate button is clicked.
28 open_translate_dialog: function(field) {},
30 * Returns true when the view is in create mode.
32 is_create_mode: function() {},
35 instance.web.views.add('form', 'instance.web.FormView');
36 instance.web.FormView = instance.web.View.extend(_.extend({}, instance.web.form.FieldManagerMixin, {
38 * Indicates that this view is not searchable, and thus that no search
39 * view should be displayed (if there is one active).
43 display_name: _lt('Form'),
46 * @constructs instance.web.FormView
47 * @extends instance.web.View
49 * @param {instance.web.Session} session the current openerp session
50 * @param {instance.web.DataSet} dataset the dataset this view will work with
51 * @param {String} view_id the identifier of the OpenERP view object
52 * @param {Object} options
53 * - resize_textareas : [true|false|max_height]
55 * @property {instance.web.Registry} registry=instance.web.form.widgets widgets registry for this form view instance
57 init: function(parent, dataset, view_id, options) {
59 this.set_default_options(options);
60 this.dataset = dataset;
61 this.model = dataset.model;
62 this.view_id = view_id || false;
63 this.fields_view = {};
65 this.fields_order = [];
67 this.default_focus_field = null;
68 this.default_focus_button = null;
69 this.fields_registry = instance.web.form.widgets;
70 this.tags_registry = instance.web.form.tags;
71 this.has_been_loaded = $.Deferred();
72 this.translatable_fields = [];
73 _.defaults(this.options, {
74 "not_interactible_on_create": false,
75 "initial_mode": "view",
77 this.is_initialized = $.Deferred();
78 this.mutating_mutex = new $.Mutex();
79 this.on_change_mutex = new $.Mutex();
80 this.reload_mutex = new $.Mutex();
81 this.rendering_engine = new instance.web.form.FormRenderingEngineReadonly(this);
82 this.qweb = null; // A QWeb instance will be created if the view is a QWeb template
85 _.each(this.get_widgets(), function(w) {
90 on_loaded: function(data) {
93 throw new Error("No data provided.");
96 throw "Form view does not support multiple calls to on_loaded";
98 this.fields_order = [];
99 this.fields_view = data;
101 this.rendering_engine.set_fields_registry(this.fields_registry);
102 this.rendering_engine.set_tags_registry(this.tags_registry);
103 if (!this.extract_qweb_template(data)) {
104 this.rendering_engine.set_fields_view(data);
105 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
106 this.rendering_engine.render_to($dest);
110 this.$buttons = $(QWeb.render("FormView.buttons", {'widget':self}));
111 if (this.options.$buttons) {
112 this.$buttons.appendTo(this.options.$buttons);
114 this.$element.find('.oe_form_buttons').replaceWith(this.$buttons);
116 this.$buttons.on('click','.oe_form_button_create',this.on_button_create);
117 this.$buttons.on('click','.oe_form_button_edit',this.on_button_edit);
118 this.$buttons.on('click','.oe_form_button_save',this.on_button_save);
119 this.$buttons.on('click','.oe_form_button_cancel',this.on_button_cancel);
121 this.$pager = $(QWeb.render("FormView.pager", {'widget':self}));
122 if (this.options.$pager) {
123 this.$pager.appendTo(this.options.$pager);
125 this.$element.find('.oe_form_pager').replaceWith(this.$pager);
127 this.$pager.on('click','a[data-pager-action]',function() {
128 var action = $(this).data('pager-action');
129 self.on_pager_action(action);
132 this.$sidebar = this.options.$sidebar || this.$element.find('.oe_form_sidebar');
133 if (!this.sidebar && this.options.$sidebar) {
134 this.sidebar = new instance.web.Sidebar(this);
135 this.sidebar.appendTo(this.$sidebar);
136 if(this.fields_view.toolbar) {
137 this.sidebar.add_toolbar(this.fields_view.toolbar);
139 this.sidebar.add_items('other', [
140 { label: _t('Delete'), callback: self.on_button_delete },
141 { label: _t('Duplicate'), callback: self.on_button_duplicate },
142 { label: _t('Set Default'), callback: function (item) { self.open_defaults_dialog(); } },
145 this.on("change:mode", this, this.switch_mode);
146 this.set({mode: this.options.initial_mode});
147 this.has_been_loaded.resolve();
150 extract_qweb_template: function(fvg) {
151 for (var i=0, ii=fvg.arch.children.length; i < ii; i++) {
152 var child = fvg.arch.children[i];
153 if (child.tag === "templates") {
154 this.qweb = new QWeb2.Engine();
155 this.qweb.add_template(instance.web.json_node_to_xml(child));
156 if (!this.qweb.has_template('form')) {
157 throw new Error("No QWeb template found for form view");
165 get_fvg_from_qweb: function(record) {
166 var view = this.qweb.render('form', this.get_qweb_context(record));
167 var fvg = _.clone(this.fields_view);
168 fvg.arch = instance.web.xml_to_json(instance.web.str_to_xml(view).firstChild);
171 get_qweb_context: function(record) {
174 _.each(record, function(value_, name) {
175 var r = _.clone(self.fields_view.fields[name] || {});
176 if ((r.type === 'date' || r.type === 'datetime') && value_) {
177 r.raw_value = instance.web.auto_str_to_date(value_);
179 r.raw_value = value_;
181 r.value = instance.web.format_value(value_, r);
182 new_record[name] = r;
186 new_record : !record.id
189 kill_current_form: function() {
190 _.each(this.getChildren(), function(el) {
194 this.fields_order = [];
195 this.default_focus_field = null;
196 this.default_focus_button = null;
197 this.translatable_fields = [];
198 this.$element.find('.oe_form_container').empty();
200 do_load_state: function(state, warm) {
201 if (state.id && this.datarecord.id != state.id) {
202 if (!this.dataset.get_id_index(state.id)) {
203 this.dataset.ids.push(state.id);
205 this.dataset.select_id(state.id);
211 do_show: function () {
214 this.sidebar.$element.show();
217 this.$buttons.show();
218 this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
223 this.$element.show().css('visibility', 'hidden');
224 this.$element.removeClass('oe_form_dirty');
225 return this.has_been_loaded.pipe(function() {
227 if (self.dataset.index === null) {
228 // null index means we should start a new record
229 result = self.on_button_new();
231 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
232 context : { 'bin_size' : true }
233 }).pipe(self.on_record_loaded);
235 result.pipe(function() {
236 self.$element.css('visibility', 'visible');
241 do_hide: function () {
243 this.sidebar.$element.hide();
246 this.$buttons.hide();
253 on_record_loaded: function(record) {
254 var self = this, set_values = [];
256 this.do_warn("Form", "The record could not be found in the database.", true);
257 return $.Deferred().reject();
259 this.datarecord = record;
262 this.kill_current_form();
263 this.rendering_engine.set_fields_view(this.get_fvg_from_qweb(record));
264 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
265 this.rendering_engine.render_to($dest);
268 _(this.fields).each(function (field, f) {
269 field._dirty_flag = false;
270 var result = field.set_value(self.datarecord[f] || false);
271 set_values.push(result);
273 return $.when.apply(null, set_values).pipe(function() {
275 // New record: Second pass in order to trigger the onchanges
276 // respecting the fields order defined in the view
277 _.each(self.fields_order, function(field_name) {
278 if (record[field_name] !== undefined) {
279 var field = self.fields[field_name];
280 field._dirty_flag = true;
281 self.do_onchange(field);
285 self.on_form_changed();
286 self.is_initialized.resolve();
287 self.do_update_pager(record.id == null);
289 self.sidebar.do_attachement_update(self.dataset, self.datarecord.id);
291 if (self.default_focus_field) {
292 self.default_focus_field.focus();
295 self.do_push_state({id:record.id});
297 self.$element.removeClass('oe_form_dirty');
298 self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
301 on_form_changed: function() {
302 this.trigger("view_content_has_changed");
304 do_notify_change: function() {
305 this.$element.addClass('oe_form_dirty');
306 this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
308 on_pager_action: function(action) {
309 if (this.can_be_discarded()) {
312 this.dataset.index = 0;
315 this.dataset.previous();
321 this.dataset.index = this.dataset.ids.length - 1;
327 do_update_pager: function(hide_index) {
328 var index = hide_index ? '-' : this.dataset.index + 1;
329 this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
330 .find('span.oe_pager_index').html(index).end()
331 .find('span.oe_pager_count').html(this.dataset.ids.length);
333 parse_on_change: function (on_change, widget) {
335 var onchange = _.str.trim(on_change);
336 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
341 var method = call[1];
342 if (!_.str.trim(call[2])) {
343 return {method: method, args: [], context_index: null}
346 var argument_replacement = {
347 'False': function () {return false;},
348 'True': function () {return true;},
349 'None': function () {return null;},
350 'context': function (i) {
352 var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
356 var parent_fields = null, context_index = null;
357 var args = _.map(call[2].split(','), function (a, i) {
358 var field = _.str.trim(a);
360 // literal constant or context
361 if (field in argument_replacement) {
362 return argument_replacement[field](i);
365 if (/^-?\d+(\.\d+)?$/.test(field)) {
366 return Number(field);
369 if (self.fields[field]) {
370 var value_ = self.fields[field].get_value();
371 return value_ == null ? false : value_;
374 var splitted = field.split('.');
375 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
376 if (parent_fields === null) {
377 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
379 var p_val = parent_fields[_.str.trim(splitted[1])];
380 if (p_val !== undefined) {
381 return p_val == null ? false : p_val;
385 var first_char = field[0], last_char = field[field.length-1];
386 if ((first_char === '"' && last_char === '"')
387 || (first_char === "'" && last_char === "'")) {
388 return field.slice(1, -1);
391 throw new Error("Could not get field with name '" + field +
392 "' for onchange '" + onchange + "'");
398 context_index: context_index
401 do_onchange: function(widget, processed) {
403 return this.on_change_mutex.exec(function() {
405 var response = {}, can_process_onchange = $.Deferred();
406 processed = processed || [];
407 processed.push(widget.name);
408 var on_change = widget.node.attrs.on_change;
410 var change_spec = self.parse_on_change(on_change, widget);
413 url: '/web/dataset/onchange',
416 can_process_onchange = self.rpc(ajax, {
417 model: self.dataset.model,
418 method: change_spec.method,
419 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
420 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
421 }).then(function(r) {
422 _.extend(response, r);
425 console.warn("Wrong on_change format", on_change);
428 // fail if onchange failed
429 if (can_process_onchange.isRejected()) {
430 return can_process_onchange;
433 if (widget.field['change_default']) {
434 var fieldname = widget.name, value_;
435 if (response.value && (fieldname in response.value)) {
436 // Use value from onchange if onchange executed
437 value_ = response.value[fieldname];
439 // otherwise get form value for field
440 value_ = self.fields[fieldname].get_value();
442 var condition = fieldname + '=' + value_;
445 can_process_onchange = self.rpc({
446 url: '/web/dataset/call',
450 method: 'get_defaults',
451 args: [self.model, condition]
452 }).then(function (results) {
453 if (!results.length) { return; }
454 if (!response.value) {
457 for(var i=0; i<results.length; ++i) {
458 // [whatever, key, value]
459 var triplet = results[i];
460 response.value[triplet[1]] = triplet[2];
465 if (can_process_onchange.isRejected()) {
466 return can_process_onchange;
469 return self.on_processed_onchange(response, processed);
472 return $.Deferred().reject();
476 on_processed_onchange: function(response, processed) {
478 var result = response;
480 for (var f in result.value) {
481 if (!result.value.hasOwnProperty(f)) { continue; }
482 var field = this.fields[f];
483 // If field is not defined in the view, just ignore it
485 var value_ = result.value[f];
486 if (field.get_value() != value_) {
487 field.set_value(value_);
488 field._dirty_flag = true;
489 if (!_.contains(processed, field.name)) {
490 this.do_onchange(field, processed);
495 this.on_form_changed();
497 if (!_.isEmpty(result.warning)) {
498 instance.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
501 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
506 function edit_domain(node) {
507 var new_domain = result.domain[node.attrs.name];
509 node.attrs.domain = new_domain;
511 _(node.children).each(edit_domain);
513 edit_domain(this.fields_view.arch);
515 return $.Deferred().resolve();
518 return $.Deferred().reject();
521 switch_mode: function() {
523 if(this.get("mode") == "view") {
524 self.$element.removeClass('oe_form_editable').addClass('oe_form_readonly');
525 self.$buttons.find('.oe_form_buttons_edit').hide();
526 self.$buttons.find('.oe_form_buttons_view').show();
527 self.$sidebar.show();
528 _.each(this.fields,function(field){
529 field.set({"force_readonly": true});
532 self.$element.removeClass('oe_form_readonly').addClass('oe_form_editable');
533 self.$buttons.find('.oe_form_buttons_edit').show();
534 self.$buttons.find('.oe_form_buttons_view').hide();
535 self.$sidebar.hide();
536 _.each(this.fields,function(field){
537 field.set({"force_readonly": false});
541 on_button_save: function() {
543 return this.do_save().then(function(result) {
544 self.set({mode: "view"});
547 on_button_cancel: function(event) {
548 if (this.can_be_discarded()) {
549 this.set({mode: "view"});
553 on_button_new: function() {
555 this.set({mode: "edit"});
556 var def = $.Deferred();
557 $.when(this.has_been_loaded).then(function() {
558 if (self.can_be_discarded()) {
559 var keys = _.keys(self.fields_view.fields);
561 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
565 self.on_record_loaded({}).then(function() {
571 return def.promise();
573 on_button_edit: function() {
574 return this.set({mode: "edit"});
576 on_button_create: function() {
577 this.dataset.index = null;
580 on_button_duplicate: function() {
582 var def = $.Deferred();
583 $.when(this.has_been_loaded).then(function() {
584 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
585 return self.on_created({ result : new_id });
587 return self.set({mode: "edit"});
592 return def.promise();
594 on_button_delete: function() {
596 var def = $.Deferred();
597 $.when(this.has_been_loaded).then(function() {
598 if (self.datarecord.id && confirm(_t("Do you really want to delete this record?"))) {
599 self.dataset.unlink([self.datarecord.id]).then(function() {
600 self.on_pager_action('next');
604 $.async_when().then(function () {
609 return def.promise();
611 can_be_discarded: function() {
612 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
615 * Triggers saving the form's record. Chooses between creating a new
616 * record or saving an existing one depending on whether the record
617 * already has an id property.
619 * @param {Function} success callback on save success
620 * @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)
622 do_save: function(success, prepend_on_create) {
624 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
626 var form_invalid = false,
628 first_invalid_field = null;
629 for (var f in self.fields) {
633 if (!first_invalid_field) {
634 first_invalid_field = f;
636 } else if (f.name !== 'id' && !f.get("readonly") && (!self.datarecord.id || f._dirty_flag)) {
637 // Special case 'id' field, do not save this field
638 // on 'create' : save all non readonly fields
639 // on 'edit' : save non readonly modified fields
640 values[f.name] = f.get_value();
644 self.set({'display_invalid_fields': true});
645 first_invalid_field.focus();
647 return $.Deferred().reject();
649 self.set({'display_invalid_fields': false});
651 if (!self.datarecord.id) {
652 //console.log("FormView(", self, ") : About to create", values);
653 save_deferral = self.dataset.create(values).pipe(function(r) {
654 return self.on_created(r, undefined, prepend_on_create);
656 } else if (_.isEmpty(values) && ! self.force_dirty) {
657 //console.log("FormView(", self, ") : Nothing to save");
658 save_deferral = $.Deferred().resolve({}).promise();
660 self.force_dirty = false;
661 //console.log("FormView(", self, ") : About to save", values);
662 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
663 return self.on_saved(r);
666 return save_deferral.then(success);
670 return $.Deferred().reject();
674 on_invalid: function() {
676 _.each(this.fields, function(f) {
678 msg += "<li>" + (f.node.attrs.string || f.field.string) + "</li>";
682 this.do_warn("The following fields are invalid :", msg);
684 on_saved: function(r, success) {
686 // should not happen in the server, but may happen for internal purpose
687 return $.Deferred().reject();
689 return $.when(this.reload()).pipe(function () {
690 return $.when(r).then(success); }, null);
694 * Updates the form' dataset to contain the new record:
696 * * Adds the newly created record to the current dataset (at the end by
698 * * Selects that record (sets the dataset's index to point to the new
700 * * Updates the pager and sidebar displays
703 * @param {Function} success callback to execute after having updated the dataset
704 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
706 on_created: function(r, success, prepend_on_create) {
708 // should not happen in the server, but may happen for internal purpose
709 return $.Deferred().reject();
711 this.datarecord.id = r.result;
712 if (!prepend_on_create) {
713 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
714 this.dataset.index = this.dataset.ids.length - 1;
716 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
717 this.dataset.index = 0;
719 this.do_update_pager();
721 this.sidebar.do_attachement_update(this.dataset, this.datarecord.id);
723 //instance.log("The record has been created with id #" + this.datarecord.id);
725 return $.when(_.extend(r, {created: true})).then(success);
728 on_action: function (action) {
729 console.debug('Executing action', action);
733 return this.reload_mutex.exec(function() {
734 if (self.dataset.index == null) {
736 return $.Deferred().reject().promise();
738 if (self.dataset.index == null || self.dataset.index < 0) {
739 return $.when(self.on_button_new());
741 return self.dataset.read_index(_.keys(self.fields_view.fields), {
742 context : { 'bin_size' : true }
743 }).pipe(self.on_record_loaded);
747 get_widgets: function() {
748 return _.filter(this.getChildren(), function(obj) {
749 return obj instanceof instance.web.form.FormWidget;
752 get_fields_values: function(blacklist) {
753 blacklist = blacklist || [];
755 var ids = this.get_selected_ids();
756 values["id"] = ids.length > 0 ? ids[0] : false;
757 _.each(this.fields, function(value_, key) {
758 if (_.include(blacklist, key))
760 var val = value_.get_value();
765 get_selected_ids: function() {
766 var id = this.dataset.ids[this.dataset.index];
767 return id ? [id] : [];
769 recursive_save: function() {
771 return $.when(this.do_save()).pipe(function(res) {
772 if (self.dataset.parent_view)
773 return self.dataset.parent_view.recursive_save();
776 is_dirty: function() {
777 return _.any(this.fields, function (value_) {
778 return value_._dirty_flag;
781 is_interactible_record: function() {
782 var id = this.datarecord.id;
784 if (this.options.not_interactible_on_create)
786 } else if (typeof(id) === "string") {
787 if(instance.web.BufferedDataSet.virtual_id_regex.test(id))
792 sidebar_context: function () {
793 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
795 open_defaults_dialog: function () {
797 var fields = _.chain(this.fields)
798 .map(function (field, name) {
799 var value = field.get_value();
800 // ignore fields which are empty, invisible, readonly, o2m
803 || field.get('invisible')
804 || field.get("readonly")
805 || field.field.type === 'one2many'
806 || field.field.type === 'many2many') {
809 var displayed = value;
810 switch (field.field.type) {
812 displayed = _(field.values).find(function (option) {
813 return option[0] === value;
820 string: field.node.attrs.string || field.field.string,
822 displayed: displayed,
823 // convert undefined to false
824 change_default: !!field.field.change_default
828 .sortBy(function (field) { return field.string; })
830 var conditions = _.chain(fields)
831 .filter(function (field) { return field.change_default; })
834 var d = new instance.web.Dialog(this, {
835 title: _t("Set Default"),
838 conditions: conditions
841 {text: _t("Close"), click: function () { d.close(); }},
842 {text: _t("Save default"), click: function () {
843 var $defaults = d.$element.find('#formview_default_fields');
844 var field_to_set = $defaults.val();
846 $defaults.parent().addClass('oe_form_invalid');
849 var condition = d.$element.find('#formview_default_conditions').val(),
850 all_users = d.$element.find('#formview_default_all').is(':checked');
851 new instance.web.DataSet(self, 'ir.values').call(
855 self.fields[field_to_set].get_value(),
859 ]).then(function () { d.close(); });
863 d.template = 'FormView.set_default';
866 register_field: function(field, name) {
867 this.fields[name] = field;
868 this.fields_order.push(name);
869 if (this.get_field(name).translate) {
870 this.translatable_fields.push(field);
872 field.on('changed_value', this, function() {
873 field._dirty_flag = true;
874 if (field.is_syntax_valid()) {
875 this.do_onchange(field);
876 this.on_form_changed(true);
877 this.do_notify_change();
881 get_field: function(field_name) {
882 return this.fields_view.fields[field_name];
884 is_create_mode: function() {
885 return !this.datarecord.id;
890 * Interface to be implemented by rendering engines for the form view.
892 instance.web.form.FormRenderingEngineInterface = instance.web.Class.extend({
893 set_fields_view: function(fields_view) {},
894 set_fields_registry: function(fields_registry) {},
895 render_to: function($element) {},
899 * Default rendering engine for the form view.
901 * It is necessary to set the view using set_view() before usage.
903 instance.web.form.FormRenderingEngine = instance.web.form.FormRenderingEngineInterface.extend({
904 init: function(view) {
907 set_fields_view: function(fvg) {
910 set_tags_registry: function(tags_registry) {
911 this.tags_registry = tags_registry;
913 set_fields_registry: function(fields_registry) {
914 this.fields_registry = fields_registry;
916 render_to: function($target) {
918 this.$target = $target;
920 // TODO: I know this will save the world and all the kitten for a moment,
921 // but one day, we will have to get rid of xml2json
922 var xml = instance.web.json_node_to_xml(this.fvg.arch);
923 this.$form = $('<div class="oe_form">' + xml + '</div>');
925 this.fields_to_init = [];
926 this.tags_to_init = [];
928 this.process(this.$form);
930 this.$form.appendTo(this.$target);
932 _.each(this.fields_to_init, function($elem) {
933 var name = $elem.attr("name");
934 if (!self.fvg.fields[name]) {
935 throw new Error("Field '" + name + "' specified in view could not be found.");
937 var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
939 throw new Error("Widget type '"+ $elem.attr('widget') + "' is not implemented");
941 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
942 var $label = self.labels[$elem.attr("name")];
944 w.set_input_id($label.attr("for"));
947 self.view.register_field(w, $elem.attr("name"));
950 _.each(this.tags_to_init, function($elem) {
951 var tag_name = $elem[0].tagName.toLowerCase();
952 var obj = self.tags_registry.get_object(tag_name);
953 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
956 // TODO: return a deferred
958 render_element: function(template /* dictionaries */) {
959 var dicts = [].slice.call(arguments).slice(1);
960 var dict = _.extend.apply(_, dicts);
961 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
962 return $(QWeb.render(template, dict));
964 alter_field: function(field) {
966 toggle_layout_debugging: function() {
967 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
968 this.$target.find('[title]').removeAttr('title');
969 this.$target.find('.oe_form_group_cell').each(function() {
970 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
971 $(this).attr('title', text);
974 this.$target.toggleClass('oe_layout_debugging');
976 process: function($tag) {
978 var tagname = $tag[0].nodeName.toLowerCase();
979 if (this.tags_registry.contains(tagname)) {
980 this.tags_to_init.push($tag);
983 var fn = self['process_' + tagname];
985 var args = [].slice.call(arguments);
987 return fn.apply(self, args);
989 // generic tag handling, just process children
990 $tag.children().each(function() {
991 self.process($(this));
993 self.handle_common_properties($tag, $tag);
994 $tag.removeAttr("modifiers");
998 process_sheet: function($sheet) {
999 var $new_sheet = this.render_element('FormRenderingSheet', $sheet.getAttributes());
1000 this.handle_common_properties($new_sheet, $sheet);
1001 var $dst = $new_sheet.find('.oe_form_sheet');
1002 $sheet.contents().appendTo($dst);
1003 $sheet.before($new_sheet).remove();
1004 this.process($new_sheet);
1006 process_form: function($form) {
1007 if ($form.find('> sheet').length === 0) {
1008 $form.addClass('oe_form_nosheet');
1010 var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
1011 this.handle_common_properties($new_form, $form);
1012 $form.contents().appendTo($new_form);
1013 if ($form[0] === this.$form[0]) {
1014 // If root element, replace it
1015 this.$form = $new_form;
1017 $form.before($new_form).remove();
1019 this.process($new_form);
1022 * Used by direct <field> children of a <group> tag only
1023 * This method will add the implicit <label...> for every field
1026 preprocess_field: function($field) {
1028 var name = $field.attr('name'),
1029 field_colspan = parseInt($field.attr('colspan'), 10),
1030 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1032 if ($field.attr('nolabel') === '1')
1034 $field.attr('nolabel', '1');
1036 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1037 $(el).parents().each(function(unused, tag) {
1038 var name = tag.tagName.toLowerCase();
1039 if (name === "field" || name in self.tags_registry.map)
1046 $label = $('<label/>').attr({
1048 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1049 "string": $field.attr('string'),
1050 "help": $field.attr('help'),
1051 "class": $field.attr('class'),
1053 $label.insertBefore($field);
1054 if (field_colspan > 1) {
1055 $field.attr('colspan', field_colspan - 1);
1059 process_field: function($field) {
1060 if ($field.parent().is('group')) {
1061 // No implicit labels for normal fields, only for <group> direct children
1062 var $label = this.preprocess_field($field);
1064 this.process($label);
1067 this.fields_to_init.push($field);
1070 process_group: function($group) {
1072 $group.children('field').each(function() {
1073 self.preprocess_field($(this));
1075 var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
1077 if ($new_group.first().is('table.oe_form_group')) {
1078 $table = $new_group;
1079 } else if ($new_group.filter('table.oe_form_group').length) {
1080 $table = $new_group.filter('table.oe_form_group').first();
1082 $table = $new_group.find('table.oe_form_group').first();
1086 cols = parseInt($group.attr('col') || 2, 10),
1090 $group.children().each(function(a,b,c) {
1091 var $child = $(this);
1092 var colspan = parseInt($child.attr('colspan') || 1, 10);
1093 var tagName = $child[0].tagName.toLowerCase();
1094 var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1095 var newline = tagName === 'newline';
1097 // Note FME: those classes are used in layout debug mode
1098 if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1099 $tr.addClass('oe_form_group_row_incomplete');
1101 $tr.addClass('oe_form_group_row_newline');
1108 if (!$tr || row_cols < colspan) {
1109 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1112 row_cols -= colspan;
1114 // invisibility transfer
1115 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1116 var invisible = field_modifiers.invisible;
1117 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1119 $tr.append($td.append($child));
1120 children.push($child[0]);
1122 if (row_cols && $td) {
1123 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1125 $group.before($new_group).remove();
1127 $table.find('> tbody > tr').each(function() {
1128 var to_compute = [],
1131 $(this).children().each(function() {
1133 $child = $td.children(':first');
1134 switch ($child[0].tagName.toLowerCase()) {
1136 if ($child.attr('orientation') === 'vertical') {
1137 $td.addClass('oe_vertical_separator').attr('width', '1');
1139 row_cols-= $td.attr('colspan') || 1;
1144 if ($child.attr('for')) {
1145 $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1146 row_cols-= $td.attr('colspan') || 1;
1151 var width = _.str.trim($child.attr('width') || ''),
1152 iwidth = parseInt(width, 10);
1154 if (width.substr(-1) === '%') {
1156 width = iwidth + '%';
1159 $td.css('min-width', width + 'px');
1161 $td.attr('width', width);
1162 $child.removeAttr('width');
1163 row_cols-= $td.attr('colspan') || 1;
1165 to_compute.push($td);
1171 var unit = Math.floor(total / row_cols);
1172 if (!$(this).is('.oe_form_group_row_incomplete')) {
1173 _.each(to_compute, function($td, i) {
1174 var width = parseInt($td.attr('colspan'), 10) * unit;
1175 $td.attr('width', width + '%');
1181 _.each(children, function(el) {
1182 self.process($(el));
1184 this.handle_common_properties($new_group, $group);
1187 process_notebook: function($notebook) {
1190 $notebook.find('> page').each(function() {
1191 var $page = $(this);
1192 var page_attrs = $page.getAttributes();
1193 page_attrs.id = _.uniqueId('notebook_page_');
1194 pages.push(page_attrs);
1195 var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
1196 $page.contents().appendTo($new_page);
1197 $page.before($new_page).remove();
1198 self.handle_common_properties($new_page, $page);
1200 var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
1201 $notebook.contents().appendTo($new_notebook);
1202 $notebook.before($new_notebook).remove();
1203 $new_notebook.children().each(function() {
1204 self.process($(this));
1206 $new_notebook.tabs();
1207 this.handle_common_properties($new_notebook, $notebook);
1208 return $new_notebook;
1210 process_separator: function($separator) {
1211 var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
1212 $separator.before($new_separator).remove();
1213 this.handle_common_properties($new_separator, $separator);
1214 return $new_separator;
1216 process_label: function($label) {
1217 var name = $label.attr("for"),
1218 field_orm = this.fvg.fields[name];
1220 string: $label.attr('string') || (field_orm || {}).string || '',
1221 help: $label.attr('help') || (field_orm || {}).help || '',
1222 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1224 var align = parseFloat(dict.align);
1225 if (isNaN(align) || align === 1) {
1227 } else if (align === 0) {
1233 var $new_label = this.render_element('FormRenderingLabel', dict);
1234 $label.before($new_label).remove();
1235 this.handle_common_properties($new_label, $label);
1237 this.labels[name] = $new_label;
1241 handle_common_properties: function($new_element, $node) {
1242 var str_modifiers = $node.attr("modifiers") || "{}"
1243 var modifiers = JSON.parse(str_modifiers);
1244 if (modifiers.invisible !== undefined)
1245 new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1246 $new_element.addClass($node.attr("class") || "");
1247 $new_element.attr('style', $node.attr('style'));
1251 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1252 alter_field: function(field) {
1253 field.set({"force_readonly": true});
1257 instance.web.form.FormDialog = instance.web.Dialog.extend({
1258 init: function(parent, options, view_id, dataset) {
1259 this._super(parent, options);
1260 this.dataset = dataset;
1261 this.view_id = view_id;
1266 this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1269 this.form.appendTo(this.$element);
1270 this.form.on_created.add_last(this.on_form_dialog_saved);
1271 this.form.on_saved.add_last(this.on_form_dialog_saved);
1274 select_id: function(id) {
1275 if (this.form.dataset.select_id(id)) {
1276 return this.form.do_show();
1278 this.do_warn("Could not find id in dataset");
1279 return $.Deferred().reject();
1282 on_form_dialog_saved: function(r) {
1287 instance.web.form.compute_domain = function(expr, fields) {
1289 for (var i = expr.length - 1; i >= 0; i--) {
1291 if (ex.length == 1) {
1292 var top = stack.pop();
1295 stack.push(stack.pop() || top);
1298 stack.push(stack.pop() && top);
1304 throw new Error(_.str.sprintf(
1305 _t("Unknown operator %s in domain %s"),
1306 ex, JSON.stringify(expr)));
1310 var field = fields[ex[0]];
1312 throw new Error(_.str.sprintf(
1313 _t("Unknown field %s in domain %s"),
1314 ex[0], JSON.stringify(expr)));
1316 var field_value = field.get_value ? field.get_value() : field.value;
1320 switch (op.toLowerCase()) {
1323 stack.push(field_value == val);
1327 stack.push(field_value != val);
1330 stack.push(field_value < val);
1333 stack.push(field_value > val);
1336 stack.push(field_value <= val);
1339 stack.push(field_value >= val);
1342 if (!_.isArray(val)) val = [val];
1343 stack.push(_(val).contains(field_value));
1346 if (!_.isArray(val)) val = [val];
1347 stack.push(!_(val).contains(field_value));
1351 _t("Unsupported operator %s in domain %s"),
1352 op, JSON.stringify(expr));
1355 return _.all(stack, _.identity);
1359 * Must be applied over an class already possessing the PropertiesMixin.
1361 * Apply the result of the "invisible" domain to this.$element.
1363 instance.web.form.InvisibilityChangerMixin = {
1364 init: function(field_manager, invisible_domain) {
1365 this._ic_field_manager = field_manager
1366 this._ic_invisible_modifier = invisible_domain;
1367 this._ic_field_manager.on("view_content_has_changed", this, function() {
1368 var result = this._ic_invisible_modifier === undefined ? false :
1369 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1370 this.set({"invisible": result});
1372 this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1373 var check = function() {
1374 if (this.get("invisible") || this.get('force_invisible')) {
1375 this.set({"effective_invisible": true});
1377 this.set({"effective_invisible": false});
1380 this.on('change:invisible', this, check);
1381 this.on('change:force_invisible', this, check);
1382 _.bind(check, this)();
1385 this.on("change:effective_invisible", this, this._check_visibility);
1386 this._check_visibility();
1388 _check_visibility: function() {
1389 if (this.get("effective_invisible")) {
1390 this.$element.hide();
1392 this.$element.show();
1397 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1398 init: function(parent, field_manager, invisible_domain, $element) {
1399 this.setParent(parent);
1400 instance.web.PropertiesMixin.init.call(this);
1401 instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1402 this.$element = $element;
1407 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1409 * @constructs instance.web.form.FormWidget
1410 * @extends instance.web.Widget
1415 init: function(view, node) {
1419 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1420 instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1422 this.view.on("view_content_has_changed", this, this.process_modifiers);
1424 renderElement: function() {
1426 this.$element.addClass(this.node.attrs["class"] || "");
1428 destroy: function() {
1430 this._super.apply(this, arguments);
1432 process_modifiers: function() {
1433 var compute_domain = instance.web.form.compute_domain;
1435 for (var a in this.modifiers) {
1436 if (!_.include(["invisible"], a)) {
1437 var val = compute_domain(this.modifiers[a], this.view.fields);
1443 do_attach_tooltip: function(widget, trigger, options) {
1444 widget = widget || this;
1445 trigger = trigger || this.$element;
1446 options = _.extend({
1451 var template = widget.template + '.tooltip';
1452 if (!QWeb.has_template(template)) {
1453 template = 'WidgetLabel.tooltip';
1455 return QWeb.render(template, {
1456 debug: instance.connection.debug,
1459 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1464 $(trigger).tipsy(options);
1466 _build_view_fields_values: function(blacklist) {
1467 var a_dataset = this.view.dataset;
1468 var fields_values = this.view.get_fields_values(blacklist);
1469 var active_id = a_dataset.ids[a_dataset.index];
1470 _.extend(fields_values, {
1471 active_id: active_id || false,
1472 active_ids: active_id ? [active_id] : [],
1473 active_model: a_dataset.model,
1476 if (a_dataset.parent_view) {
1477 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1479 return fields_values;
1481 _build_eval_context: function(blacklist) {
1482 var a_dataset = this.view.dataset;
1483 return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1486 * Builds a new context usable for operations related to fields by merging
1487 * the fields'context with the action's context.
1489 build_context: function(blacklist) {
1490 // only use the model's context if there is not context on the node
1491 var v_context = this.node.attrs.context;
1493 v_context = (this.field || {}).context || {};
1496 if (v_context.__ref || true) { //TODO: remove true
1497 var fields_values = this._build_eval_context(blacklist);
1498 v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1502 build_domain: function() {
1503 var f_domain = this.field.domain || [];
1504 var n_domain = this.node.attrs.domain || null;
1505 // if there is a domain on the node, overrides the model's domain
1506 var final_domain = n_domain !== null ? n_domain : f_domain;
1507 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1508 var fields_values = this._build_eval_context();
1509 final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1511 return final_domain;
1515 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1516 template: 'WidgetButton',
1517 init: function(view, node) {
1518 this._super(view, node);
1519 this.force_disabled = false;
1520 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1521 if (this.node.attrs.default_focus == '1') {
1522 // TODO fme: provide enter key binding to widgets
1523 this.view.default_focus_button = this;
1525 this.view.on('view_content_has_changed', this, this.check_disable);
1528 this._super.apply(this, arguments);
1529 this.$element.click(this.on_click);
1530 if (this.node.attrs.help || instance.connection.debug) {
1531 this.do_attach_tooltip();
1534 on_click: function() {
1536 this.force_disabled = true;
1537 this.check_disable();
1538 this.execute_action().always(function() {
1539 self.force_disabled = false;
1540 self.check_disable();
1543 execute_action: function() {
1545 var exec_action = function() {
1546 if (self.node.attrs.confirm) {
1547 var def = $.Deferred();
1548 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1549 title: _t('Confirm'),
1552 {text: _t("Cancel"), click: function() {
1554 $(this).dialog("close");
1557 {text: _t("Ok"), click: function() {
1558 self.on_confirmed().then(function() {
1561 $(this).dialog("close");
1566 return def.promise();
1568 return self.on_confirmed();
1571 if (!this.node.attrs.special) {
1572 this.view.force_dirty = true;
1573 return this.view.recursive_save().pipe(exec_action);
1575 return exec_action();
1578 on_confirmed: function() {
1581 var context = this.node.attrs.context;
1582 if (context && context.__ref) {
1583 context = new instance.web.CompoundContext(context);
1584 context.set_eval_context(this._build_eval_context());
1587 return this.view.do_execute_action(
1588 _.extend({}, this.node.attrs, {context: context}),
1589 this.view.dataset, this.view.datarecord.id, function () {
1593 check_disable: function() {
1594 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1595 this.$element.prop('disabled', disabled);
1596 this.$element.css('color', disabled ? 'grey' : '');
1601 * Interface to be implemented by fields.
1604 * - readonly: boolean. If set to true the field should appear in readonly mode.
1605 * - force_readonly: boolean, When it is true, the field should always appear
1606 * in read only mode, no matter what the value of the "readonly" property can be.
1608 * - changed_value: triggered to inform the view to check on_changes
1611 instance.web.form.FieldMixin = {
1613 * Constructor takes 2 arguments:
1614 * - field_manager: Implements FieldManagerMixin
1615 * - node: the "<field>" node in json form
1617 init: function(field_manager, node) {},
1619 * Called by the form view to indicate the value of the field.
1621 * set_value() may return an object that can be passed to $.when() that represents the moment when
1622 * the field has finished all operations necessary before the user can effectively use the widget.
1624 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1625 * regardless of any asynchronous operation currently running and the status of any promise that a
1626 * previous call to set_value() could have returned.
1628 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1629 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1630 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1631 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1632 * no information is ever given to know which format is used.
1634 set_value: function(value_) {},
1636 * Get the current value of the widget.
1638 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1639 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1640 * For example if the field is marqued as "required", a call to get_value() can return false.
1642 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1643 * return a defaut value according to the type of field.
1645 * This method is always assumed to perform synchronously, it can not return a promise.
1647 * If there was no user interaction to modify the value of the field, it is always assumed that
1648 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1649 * altough the syntax can be different. This can be the case for type of fields that have a different
1650 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1652 get_value: function() {},
1654 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1657 set_input_id: function(id) {},
1659 * Returns true if is_syntax_valid() returns true and the value is semantically
1660 * valid too according to the semantic restrictions applied to the field.
1662 is_valid: function() {},
1664 * Returns true if the field holds a value which is syntaxically correct, ignoring
1665 * the potential semantic restrictions applied to the field.
1667 is_syntax_valid: function() {},
1669 * Must set the focus on the field.
1671 focus: function() {},
1675 * Abstract class for classes implementing FieldMixin.
1678 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1679 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1680 * - value: useful property to hold the value of the field. By default, set_value() and get_value()
1681 * set and retrieve the value property. Changing the value property also triggers automatically
1682 * a 'changed_value' event that inform the view to trigger on_changes.
1685 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1687 * @constructs instance.web.form.AbstractField
1688 * @extends instance.web.form.FormWidget
1690 * @param field_manager
1693 init: function(field_manager, node) {
1694 this._super(field_manager, node);
1695 this.field_manager = field_manager;
1696 this.name = this.node.attrs.name;
1697 this.set({'value': false});
1698 this.field = this.field_manager.get_field(this.name);
1699 this.set({required: this.modifiers['required'] === true});
1701 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1703 this.set({"readonly": this.modifiers['readonly'] === true});
1704 var test_effective_readonly = function() {
1705 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1707 this.on("change:readonly", this, test_effective_readonly);
1708 this.on("change:force_readonly", this, test_effective_readonly);
1709 _.bind(test_effective_readonly, this)();
1711 this.on("change:value", this, function() {
1712 if (! this._inhibit_on_change)
1713 this.trigger('changed_value');
1714 this._check_css_flags();
1717 renderElement: function() {
1720 if (this.field.translate) {
1721 this.$element.addClass('oe_form_field_translatable');
1722 this.$element.find('.oe_field_translate').click(_.bind(function() {
1723 this.field_manager.open_translate_dialog(this);
1726 this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1727 if (instance.connection.debug) {
1728 this.do_attach_tooltip(this, this.$label[0] || this.$element);
1729 this.$label.off('dblclick').on('dblclick', function() {
1730 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1732 console.log("window.w =", window.w);
1735 if (!this.disable_utility_classes) {
1736 this.off("change:required", this, this._set_required);
1737 this.on("change:required", this, this._set_required);
1738 this._set_required();
1740 this._check_visibility();
1741 this._check_css_flags();
1744 * Private. Do not use.
1746 _set_required: function() {
1747 this.$element.toggleClass('oe_form_required', this.get("required"));
1749 set_value: function(value_) {
1750 this._inhibit_on_change = true;
1751 this.set({'value': value_});
1752 this._inhibit_on_change = false;
1754 get_value: function() {
1755 return this.get('value');
1757 is_valid: function() {
1758 return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1760 is_syntax_valid: function() {
1764 * Method useful to implement to ease validity testing. Must return true if the current
1765 * value is similar to false in OpenERP.
1767 is_false: function() {
1768 return this.get('value') === false;
1770 _check_css_flags: function(show_invalid) {
1771 if (this.field.translate) {
1772 this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1774 if (!this.disable_utility_classes) {
1775 if (this.field_manager.get('display_invalid_fields')) {
1776 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1783 * Utility method to focus an element, but only after a small amount of time.
1785 delay_focus: function($elem) {
1786 setTimeout(function() {
1791 * Utility method to get the widget options defined in the field xml description.
1793 get_definition_options: function() {
1794 if (!this.definition_options) {
1795 var str = this.node.attrs.options || '{}';
1796 this.definition_options = JSON.parse(str);
1798 return this.definition_options;
1800 set_input_id: function(id) {
1801 this.id_for_label = id;
1806 * A mixin to apply on any field that has to completely re-render when its readonly state
1809 instance.web.form.ReinitializeFieldMixin = {
1811 * Default implementation of start(), use it or call explicitly initialize_field().
1815 this.initialize_field();
1817 initialize_field: function() {
1818 this.on("change:effective_readonly", this, function() {
1819 this.destroy_content();
1820 this.renderElement();
1821 this.initialize_content();
1822 this.render_value();
1824 this.initialize_content();
1825 this.render_value();
1828 * Called to destroy anything that could have been created previously, called before a
1829 * re-initialization.
1831 destroy_content: function() {},
1833 * Called to initialize the content.
1835 initialize_content: function() {},
1837 * Called to render the value. Should also be explicitly called at the end of a set_value().
1839 render_value: function() {},
1842 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1843 template: 'FieldChar',
1844 widget_class: 'oe_form_field_char',
1845 init: function (field_manager, node) {
1846 this._super(field_manager, node);
1847 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1849 initialize_content: function() {
1851 this.$element.find('input').change(function() {
1852 self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1855 set_value: function(value_) {
1856 this._super(value_);
1857 this.render_value();
1859 render_value: function() {
1860 var show_value = instance.web.format_value(this.get('value'), this, '');
1861 if (!this.get("effective_readonly")) {
1862 this.$element.find('input').val(show_value);
1864 if (this.password) {
1865 show_value = new Array(show_value.length + 1).join('*');
1867 this.$element.text(show_value);
1870 is_syntax_valid: function() {
1871 if (!this.get("effective_readonly")) {
1873 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1881 is_false: function() {
1882 return this.get('value') === '';
1885 this.delay_focus(this.$element.find('input:first'));
1889 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1893 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1894 template: 'FieldEmail',
1895 initialize_content: function() {
1897 this.$element.find('button').click(this.on_button_clicked);
1899 render_value: function() {
1900 if (!this.get("effective_readonly")) {
1903 this.$element.find('a')
1904 .attr('href', 'mailto:' + this.get('value'))
1905 .text(this.get('value'));
1908 on_button_clicked: function() {
1909 if (!this.get('value') || !this.is_syntax_valid()) {
1910 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1912 location.href = 'mailto:' + this.get('value');
1917 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1918 template: 'FieldUrl',
1919 initialize_content: function() {
1921 this.$element.find('button').click(this.on_button_clicked);
1923 render_value: function() {
1924 if (!this.get("effective_readonly")) {
1927 var tmp = this.get('value');
1928 var s = /(\w+):(.+)/.exec(tmp);
1930 tmp = "http://" + this.get('value');
1932 this.$element.find('a').attr('href', tmp).text(tmp);
1935 on_button_clicked: function() {
1936 if (!this.get('value')) {
1937 this.do_warn("Resource error", "This resource is empty");
1939 var url = $.trim(this.get('value'));
1940 if(/^www\./i.test(url))
1941 url = 'http://'+url;
1947 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1948 is_field_number: true,
1949 widget_class: 'oe_form_field_float',
1950 init: function (field_manager, node) {
1951 this._super(field_manager, node);
1952 this.set({'value': 0});
1953 if (this.node.attrs.digits) {
1954 this.digits = py.eval(node.attrs.digits);
1956 this.digits = this.field.digits;
1959 set_value: function(value_) {
1960 if (value_ === false || value_ === undefined) {
1961 // As in GTK client, floats default to 0
1964 this._super.apply(this, [value_]);
1968 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
1969 template: "web.datepicker",
1970 jqueryui_object: 'datetimepicker',
1971 type_of_date: "datetime",
1972 init: function(parent) {
1973 this._super(parent);
1974 this.name = parent.name;
1978 this.$input = this.$element.find('input.oe_datepicker_master');
1979 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1980 this.$input.change(this.on_change);
1982 onSelect: this.on_picker_select,
1986 showButtonPanel: true
1988 this.$element.find('img.oe_datepicker_trigger').click(function() {
1989 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1990 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
1991 self.$input_picker.show();
1992 self.picker('show');
1993 self.$input_picker.hide();
1996 this.set_readonly(false);
1997 this.set({'value': false});
1999 picker: function() {
2000 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
2002 on_picker_select: function(text, instance_) {
2003 var date = this.picker('getDate');
2004 this.$input.val(date ? this.format_client(date) : '').change();
2006 set_value: function(value_) {
2007 this.set({'value': value_});
2008 this.$input.val(value_ ? this.format_client(value_) : '');
2010 get_value: function() {
2011 return this.get('value');
2013 set_value_from_ui_: function() {
2014 var value_ = this.$input.val() || false;
2015 this.set({'value': this.parse_client(value_)});
2017 set_readonly: function(readonly) {
2018 this.readonly = readonly;
2019 this.$input.prop('readonly', this.readonly);
2020 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2022 is_valid_: function() {
2023 var value_ = this.$input.val();
2024 if (value_ === "") {
2028 this.parse_client(value_);
2035 parse_client: function(v) {
2036 return instance.web.parse_value(v, {"widget": this.type_of_date});
2038 format_client: function(v) {
2039 return instance.web.format_value(v, {"widget": this.type_of_date});
2041 on_change: function() {
2042 if (this.is_valid_()) {
2043 this.set_value_from_ui_();
2048 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2049 jqueryui_object: 'datepicker',
2050 type_of_date: "date"
2053 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2054 template: "FieldDatetime",
2055 build_widget: function() {
2056 return new instance.web.DateTimeWidget(this);
2058 destroy_content: function() {
2059 if (this.datewidget) {
2060 this.datewidget.destroy();
2061 this.datewidget = undefined;
2064 initialize_content: function() {
2065 if (!this.get("effective_readonly")) {
2066 this.datewidget = this.build_widget();
2067 this.datewidget.on_change.add_last(_.bind(function() {
2068 this.set({'value': this.datewidget.get_value()});
2070 this.datewidget.appendTo(this.$element);
2073 set_value: function(value_) {
2074 this._super(value_);
2075 this.render_value();
2077 render_value: function() {
2078 if (!this.get("effective_readonly")) {
2079 this.datewidget.set_value(this.get('value'));
2081 this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2084 is_syntax_valid: function() {
2085 if (!this.get("effective_readonly")) {
2086 return this.datewidget.is_valid_();
2090 is_false: function() {
2091 return this.get('value') === '';
2094 if (this.datewidget && this.datewidget.$input)
2095 this.delay_focus(this.datewidget.$input);
2099 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2100 template: "FieldDate",
2101 build_widget: function() {
2102 return new instance.web.DateWidget(this);
2106 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2107 template: 'FieldText',
2108 initialize_content: function() {
2109 this.$textarea = this.$element.find('textarea');
2110 if (!this.get("effective_readonly")) {
2111 this.$textarea.change(_.bind(function() {
2112 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2115 this.$textarea.attr('disabled', 'disabled');
2118 set_value: function(value_) {
2119 this._super.apply(this, arguments);
2120 this.render_value();
2122 render_value: function() {
2123 var show_value = instance.web.format_value(this.get('value'), this, '');
2124 this.$textarea.val(show_value);
2125 if (show_value && this.view.options.resize_textareas) {
2126 this.do_resize(this.view.options.resize_textareas);
2129 is_syntax_valid: function() {
2130 if (!this.get("effective_readonly")) {
2132 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2140 is_false: function() {
2141 return this.get('value') === '';
2143 focus: function($element) {
2144 this.delay_focus(this.$textarea);
2146 do_resize: function(max_height) {
2147 max_height = parseInt(max_height, 10);
2148 var $input = this.$textarea,
2149 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2151 $div.text($input.val());
2152 _.each('font-family,font-size,white-space'.split(','), function(style) {
2153 $div.css(style, $input.css(style));
2155 $div.appendTo($('body'));
2156 new_height = $div.height();
2157 if (new_height < 90) {
2160 if (!isNaN(max_height) && new_height > max_height) {
2161 new_height = max_height;
2164 $input.height(new_height);
2168 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2169 template: 'FieldBoolean',
2171 this._super.apply(this, arguments);
2172 this.$checkbox = $("input", this.$element);
2173 this.$element.click(_.bind(function() {
2174 this.set({'value': this.$checkbox.is(':checked')});
2176 var check_readonly = function() {
2177 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2179 this.on("change:effective_readonly", this, check_readonly);
2180 _.bind(check_readonly, this)();
2182 set_value: function(value_) {
2183 this._super.apply(this, arguments);
2184 this.$checkbox[0].checked = value_;
2187 this.delay_focus(this.$checkbox);
2191 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2192 template: 'FieldProgressBar',
2194 this._super.apply(this, arguments);
2195 this.$element.progressbar({
2196 value: this.get('value'),
2197 disabled: this.get("effective_readonly")
2200 set_value: function(value_) {
2201 this._super.apply(this, arguments);
2202 var show_value = Number(value_);
2203 if (isNaN(show_value)) {
2206 var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2207 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2211 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2212 // to replace view editor
2215 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2216 template: 'FieldSelection',
2217 init: function(field_manager, node) {
2219 this._super(field_manager, node);
2220 this.values = _.clone(this.field.selection);
2221 _.each(this.values, function(v, i) {
2222 if (v[0] === false && v[1] === '') {
2223 self.values.splice(i, 1);
2226 this.values.unshift([false, '']);
2228 initialize_content: function() {
2229 // Flag indicating whether we're in an event chain containing a change
2230 // event on the select, in order to know what to do on keyup[RETURN]:
2231 // * If the user presses [RETURN] as part of changing the value of a
2232 // selection, we should just let the value change and not let the
2233 // event broadcast further (e.g. to validating the current state of
2234 // the form in editable list view, which would lead to saving the
2235 // current row or switching to the next one)
2236 // * If the user presses [RETURN] with a select closed (side-effect:
2237 // also if the user opened the select and pressed [RETURN] without
2238 // changing the selected value), takes the action as validating the
2240 var ischanging = false;
2241 this.$element.find('select')
2242 .change(_.bind(function() {
2243 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2245 .change(function () { ischanging = true; })
2246 .click(function () { ischanging = false; })
2247 .keyup(function (e) {
2248 if (e.which !== 13 || !ischanging) { return; }
2249 e.stopPropagation();
2253 set_value: function(value_) {
2254 value_ = value_ === null ? false : value_;
2255 value_ = value_ instanceof Array ? value_[0] : value_;
2256 this._super(value_);
2257 this.render_value();
2259 render_value: function() {
2260 if (!this.get("effective_readonly")) {
2262 for (var i = 0, ii = this.values.length; i < ii; i++) {
2263 if (this.values[i][0] === this.get('value')) index = i;
2265 this.$element.find('select')[0].selectedIndex = index;
2268 var option = _(this.values)
2269 .detect(function (record) { return record[0] === self.get('value'); });
2270 this.$element.text(option ? option[1] : this.values[0][1]);
2273 is_syntax_valid: function() {
2274 if (this.get("effective_readonly")) {
2277 var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2281 this.delay_focus(this.$element.find('select:first'));
2285 // jquery autocomplete tweak to allow html
2287 var proto = $.ui.autocomplete.prototype,
2288 initSource = proto._initSource;
2290 function filter( array, term ) {
2291 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2292 return $.grep( array, function(value_) {
2293 return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2298 _initSource: function() {
2299 if ( this.options.html && $.isArray(this.options.source) ) {
2300 this.source = function( request, response ) {
2301 response( filter( this.options.source, request.term ) );
2304 initSource.call( this );
2308 _renderItem: function( ul, item) {
2309 return $( "<li></li>" )
2310 .data( "item.autocomplete", item )
2311 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2318 * A mixin containing some useful methods to handle completion inputs.
2320 instance.web.form.CompletionFieldMixin = {
2323 this.orderer = new instance.web.DropMisordered();
2326 * Call this method to search using a string.
2328 get_search_result: function(search_val) {
2331 var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2332 var blacklist = this.get_search_blacklist();
2334 return this.orderer.add(dataset.name_search(
2335 search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
2336 'ilike', this.limit + 1)).pipe(function(data) {
2337 self.last_search = data;
2338 // possible selections for the m2o
2339 var values = _.map(data, function(x) {
2341 label: _.str.escapeHTML(x[1]),
2348 // search more... if more results that max
2349 if (values.length > self.limit) {
2350 values = values.slice(0, self.limit);
2351 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2352 dataset.name_search(search_val, self.build_domain(), 'ilike'
2353 , false, function(data) {
2354 self._search_create_popup("search", data);
2359 var raw_result = _(data.result).map(function(x) {return x[1];});
2360 if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2361 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2362 $('<span />').text(search_val).html()), action: function() {
2363 self._quick_create(search_val);
2367 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2368 self._search_create_popup("form", undefined, {"default_name": search_val});
2374 get_search_blacklist: function() {
2377 _quick_create: function(name) {
2379 var slow_create = function () {
2380 self._search_create_popup("form", undefined, {"default_name": name});
2382 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2383 new instance.web.DataSet(this, this.field.relation, self.build_context())
2384 .name_create(name, function(data) {
2385 self.add_id(data[0]);
2386 }).fail(function(error, event) {
2387 event.preventDefault();
2393 // all search/create popup handling
2394 _search_create_popup: function(view, ids, context) {
2396 var pop = new instance.web.form.SelectCreatePopup(this);
2398 self.field.relation,
2400 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2401 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2403 disable_multiple_selection: true
2405 self.build_domain(),
2406 new instance.web.CompoundContext(self.build_context(), context || {})
2408 pop.on_select_elements.add(function(element_ids) {
2409 self.add_id(element_ids[0]);
2415 add_id: function(id) {},
2418 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2419 instance.web.form.CompletionFieldMixin, {
2420 template: "FieldMany2One",
2421 init: function(field_manager, node) {
2422 this._super(field_manager, node);
2423 instance.web.form.CompletionFieldMixin.init.call(this);
2424 this.set({'value': false});
2425 this.display_value = {};
2426 this.last_search = [];
2427 this.floating = false;
2428 this.inhibit_on_change = false;
2432 instance.web.form.ReinitializeFieldMixin.start.call(this);
2433 this.on("change:value", this, function() {
2434 this.floating = false;
2435 this.render_value();
2438 initialize_content: function() {
2439 if (!this.get("effective_readonly"))
2440 this.render_editable();
2441 this.render_value();
2443 render_editable: function() {
2445 this.$input = this.$element.find("input");
2449 return "No element was selected, you should create or select one from the dropdown list.";
2455 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2456 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2458 this.$follow_button.click(function() {
2459 if (!self.get('value')) {
2462 var pop = new instance.web.form.FormOpenPopup(self.view);
2464 self.field.relation,
2466 self.build_context(),
2468 title: _t("Open: ") + (self.string || self.name)
2471 pop.on_write_completed.add_last(function() {
2472 self.display_value = {};
2473 self.render_value();
2477 // some behavior for input
2478 this.$input.keyup(function() {
2479 if (self.$input.val() === "") {
2480 self.set({value: false});
2482 self.floating = true;
2485 this.$drop_down.click(function() {
2486 if (self.$input.autocomplete("widget").is(":visible")) {
2487 self.$input.autocomplete("close");
2489 if (self.get("value") && ! self.floating) {
2490 self.$input.autocomplete("search", "");
2492 self.$input.autocomplete("search");
2494 self.$input.focus();
2497 var tip_def = $.Deferred();
2498 var untip_def = $.Deferred();
2499 var tip_delay = 200;
2500 var tip_duration = 3000;
2501 var anyoneLoosesFocus = function() {
2502 if (self.floating) {
2503 if (self.last_search.length > 0) {
2504 if (self.last_search[0][0] != self.get("value")) {
2505 self.display_value = {};
2506 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2507 self.set({value: self.last_search[0][0]});
2509 self.render_value();
2512 self.set({value: false});
2515 if (! self.get("value")) {
2518 tip_def = $.Deferred();
2519 tip_def.then(function() {
2520 self.$input.tipsy("show");
2522 setTimeout(function() {
2525 untip_def = $.Deferred();
2526 untip_def.then(function() {
2527 self.$input.tipsy("hide");
2529 setTimeout(function() {untip_def.resolve();}, tip_duration);
2535 this.$input.focusout(anyoneLoosesFocus);
2537 var isSelecting = false;
2539 this.$input.autocomplete({
2540 source: function(req, resp) {
2541 self.get_search_result(req.term).then(function(result) {
2545 select: function(event, ui) {
2549 self.display_value = {};
2550 self.display_value["" + item.id] = item.name;
2551 self.set({value: item.id});
2552 } else if (item.action) {
2553 self.floating = true;
2558 focus: function(e, ui) {
2562 close: anyoneLoosesFocus,
2566 this.$input.autocomplete("widget").addClass("openerp");
2567 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2568 this.$input.keyup(function(e) {
2569 if (e.which === 13) {
2571 e.stopPropagation();
2573 isSelecting = false;
2577 render_value: function(no_recurse) {
2579 if (! this.get("value")) {
2580 this.display_string("");
2583 var display = this.display_value["" + this.get("value")];
2585 this.display_string(display);
2589 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2590 dataset.name_get([self.get("value")], function(data) {
2591 self.display_value["" + self.get("value")] = data[0][1];
2592 self.render_value(true);
2596 display_string: function(str) {
2598 if (!this.get("effective_readonly")) {
2599 this.$input.val(str);
2601 this.$element.find('a')
2604 .click(function () {
2606 type: 'ir.actions.act_window',
2607 res_model: self.field.relation,
2608 res_id: self.get("value"),
2609 context: self.build_context(),
2610 views: [[false, 'form']],
2617 set_value: function(value_) {
2619 if (value_ instanceof Array) {
2620 this.display_value = {};
2621 this.display_value["" + value_[0]] = value_[1];
2624 value_ = value_ || false;
2625 this.inhibit_on_change = true;
2626 this._super(value_);
2627 this.inhibit_on_change = false;
2629 add_id: function(id) {
2630 this.display_value = {};
2631 this.set({value: id});
2633 is_false: function() {
2634 return ! this.get("value");
2636 focus: function () {
2637 this.delay_focus(this.$input);
2642 # Values: (0, 0, { fields }) create
2643 # (1, ID, { fields }) update
2644 # (2, ID) remove (delete)
2645 # (3, ID) unlink one (target id or target of relation)
2647 # (5) unlink all (only valid for one2many)
2652 'create': function (values) {
2653 return [commands.CREATE, false, values];
2655 // (1, id, {values})
2657 'update': function (id, values) {
2658 return [commands.UPDATE, id, values];
2662 'delete': function (id) {
2663 return [commands.DELETE, id, false];
2665 // (3, id[, _]) removes relation, but not linked record itself
2667 'forget': function (id) {
2668 return [commands.FORGET, id, false];
2672 'link_to': function (id) {
2673 return [commands.LINK_TO, id, false];
2677 'delete_all': function () {
2678 return [5, false, false];
2680 // (6, _, ids) replaces all linked records with provided ids
2682 'replace_with': function (ids) {
2683 return [6, false, ids];
2686 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2687 multi_selection: false,
2688 disable_utility_classes: true,
2689 init: function(field_manager, node) {
2690 this._super(field_manager, node);
2691 lazy_build_o2m_kanban_view();
2692 this.is_loaded = $.Deferred();
2693 this.initial_is_loaded = this.is_loaded;
2694 this.is_setted = $.Deferred();
2695 this.form_last_update = $.Deferred();
2696 this.init_form_last_update = this.form_last_update;
2699 this._super.apply(this, arguments);
2703 this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2704 this.dataset.o2m = this;
2705 this.dataset.parent_view = this.view;
2706 this.dataset.child_name = this.name;
2707 //this.dataset.child_name =
2708 this.dataset.on_change.add_last(function() {
2709 self.trigger_on_change();
2712 this.is_setted.then(function() {
2715 this.is_loaded.then(function() {
2716 self.on("change:effective_readonly", self, function() {
2717 self.is_loaded = self.is_loaded.pipe(function() {
2718 self.viewmanager.destroy();
2719 return $.when(self.load_views()).then(function() {
2720 self.reload_current_view();
2726 trigger_on_change: function() {
2727 var tmp = this.doing_on_change;
2728 this.doing_on_change = true;
2729 this.trigger('changed_value');
2730 this.doing_on_change = tmp;
2732 load_views: function() {
2735 var modes = this.node.attrs.mode;
2736 modes = !!modes ? modes.split(",") : ["tree"];
2738 _.each(modes, function(mode) {
2741 view_type: mode == "tree" ? "list" : mode,
2744 if (self.field.views && self.field.views[mode]) {
2745 view.embedded_view = self.field.views[mode];
2747 if(view.view_type === "list") {
2748 view.options.selectable = self.multi_selection;
2749 if (self.get("effective_readonly")) {
2750 view.options.addable = null;
2751 view.options.deletable = null;
2753 } else if (view.view_type === "form") {
2754 if (self.get("effective_readonly")) {
2755 view.view_type = 'form';
2757 view.options.not_interactible_on_create = true;
2758 } else if (view.view_type === "kanban") {
2759 view.options.confirm_on_delete = false;
2760 if (self.get("effective_readonly")) {
2761 view.options.action_buttons = false;
2762 view.options.quick_creatable = false;
2763 view.options.creatable = false;
2764 view.options.read_only_mode = true;
2771 this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2772 this.viewmanager.o2m = self;
2773 var once = $.Deferred().then(function() {
2774 self.init_form_last_update.resolve();
2776 var def = $.Deferred().then(function() {
2777 self.initial_is_loaded.resolve();
2779 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2780 controller.o2m = self;
2781 if (view_type == "list") {
2782 if (self.get("effective_readonly"))
2783 controller.set_editable(false);
2784 } else if (view_type === "form") {
2785 if (self.get("effective_readonly")) {
2786 $(".oe_form_buttons", controller.$element).children().remove();
2788 controller.on_record_loaded.add_last(function() {
2791 controller.on_pager_action.add_first(function() {
2792 self.save_any_view();
2794 } else if (view_type == "graph") {
2795 self.reload_current_view()
2799 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2800 $.when(self.save_any_view()).then(function() {
2801 if(n_mode === "list")
2802 $.async_when().then(function() {self.reload_current_view();});
2805 this.is_setted.then(function() {
2806 $.async_when().then(function () {
2807 self.viewmanager.appendTo(self.$element);
2812 reload_current_view: function() {
2814 return self.is_loaded = self.is_loaded.pipe(function() {
2815 var active_view = self.viewmanager.active_view;
2816 var view = self.viewmanager.views[active_view].controller;
2817 if(active_view === "list") {
2818 return view.reload_content();
2819 } else if (active_view === "form") {
2820 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2821 self.dataset.index = 0;
2823 var act = function() {
2824 return view.do_show();
2826 self.form_last_update = self.form_last_update.pipe(act, act);
2827 return self.form_last_update;
2828 } else if (view.do_search) {
2829 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2833 set_value: function(value_) {
2834 value_ = value_ || [];
2836 this.dataset.reset_ids([]);
2837 if(value_.length >= 1 && value_[0] instanceof Array) {
2839 _.each(value_, function(command) {
2840 var obj = {values: command[2]};
2841 switch (command[0]) {
2842 case commands.CREATE:
2843 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2845 self.dataset.to_create.push(obj);
2846 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2849 case commands.UPDATE:
2850 obj['id'] = command[1];
2851 self.dataset.to_write.push(obj);
2852 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2855 case commands.DELETE:
2856 self.dataset.to_delete.push({id: command[1]});
2858 case commands.LINK_TO:
2859 ids.push(command[1]);
2861 case commands.DELETE_ALL:
2862 self.dataset.delete_all = true;
2867 this.dataset.set_ids(ids);
2868 } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2870 this.dataset.delete_all = true;
2871 _.each(value_, function(command) {
2872 var obj = {values: command};
2873 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2875 self.dataset.to_create.push(obj);
2876 self.dataset.cache.push(_.clone(obj));
2880 this.dataset.set_ids(ids);
2882 this._super(value_);
2883 this.dataset.reset_ids(value_);
2885 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2886 this.dataset.index = 0;
2888 self.is_setted.resolve();
2889 return self.reload_current_view();
2891 get_value: function() {
2895 this.save_any_view();
2896 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2897 val = val.concat(_.map(this.dataset.ids, function(id) {
2898 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2900 return commands.create(alter_order.values);
2902 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2904 return commands.update(alter_order.id, alter_order.values);
2906 return commands.link_to(id);
2908 return val.concat(_.map(
2909 this.dataset.to_delete, function(x) {
2910 return commands['delete'](x.id);}));
2912 save_any_view: function() {
2913 if (this.doing_on_change)
2915 return this.session.synchronized_mode(_.bind(function() {
2916 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2917 this.viewmanager.views[this.viewmanager.active_view] &&
2918 this.viewmanager.views[this.viewmanager.active_view].controller) {
2919 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2920 if (this.viewmanager.active_view === "form") {
2921 if (!view.is_initialized.isResolved()) {
2924 var res = $.when(view.do_save());
2925 if (!res.isResolved() && !res.isRejected()) {
2926 console.warn("Asynchronous get_value() is not supported in form view.");
2929 } else if (this.viewmanager.active_view === "list") {
2930 var res = $.when(view.ensure_saved());
2931 if (!res.isResolved() && !res.isRejected()) {
2932 console.warn("Asynchronous get_value() is not supported in list view.");
2940 is_syntax_valid: function() {
2941 if (!this.viewmanager.views[this.viewmanager.active_view])
2943 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2944 if (this.viewmanager.active_view === "form") {
2945 for (var f in view.fields) {
2947 if (!f.is_valid()) {
2956 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
2957 template: 'One2Many.viewmanager',
2958 init: function(parent, dataset, views, flags) {
2959 this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
2960 this.registry = this.registry.extend({
2961 list: 'instance.web.form.One2ManyListView',
2962 form: 'instance.web.form.One2ManyFormView',
2963 kanban: 'instance.web.form.One2ManyKanbanView',
2966 switch_view: function(mode, unused) {
2967 if (mode !== 'form') {
2968 return this._super(mode, unused);
2971 var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
2972 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
2973 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2974 title: _t("Open: ") + self.name,
2975 create_function: function(data) {
2976 return self.o2m.dataset.create(data).then(function(r) {
2977 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2978 self.o2m.dataset.on_change();
2981 write_function: function(id, data, options) {
2982 return self.o2m.dataset.write(id, data, {}).then(function() {
2983 self.o2m.reload_current_view();
2986 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2987 parent_view: self.o2m.view,
2988 child_name: self.o2m.name,
2989 read_function: function() {
2990 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2992 form_view_options: {'not_interactible_on_create':true},
2993 readonly: self.o2m.get("effective_readonly")
2995 pop.on_select_elements.add_last(function() {
2996 self.o2m.reload_current_view();
3001 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
3002 get_context: function() {
3003 this.context = this.o2m.build_context([this.o2m.name]);
3004 return this.context;
3008 instance.web.form.One2ManyListView = instance.web.ListView.extend({
3009 _template: 'One2Many.listview',
3010 do_add_record: function () {
3011 if (this.options.editable) {
3012 this._super.apply(this, arguments);
3015 var pop = new instance.web.form.SelectCreatePopup(this);
3017 self.o2m.field.relation,
3019 title: _t("Create: ") + self.name,
3020 initial_view: "form",
3021 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3022 create_function: function(data, callback, error_callback) {
3023 return self.o2m.dataset.create(data).then(function(r) {
3024 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3025 self.o2m.dataset.on_change();
3026 }).then(callback, error_callback);
3028 read_function: function() {
3029 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3031 parent_view: self.o2m.view,
3032 child_name: self.o2m.name,
3033 form_view_options: {'not_interactible_on_create':true}
3035 self.o2m.build_domain(),
3036 self.o2m.build_context()
3038 pop.on_select_elements.add_last(function() {
3039 self.o2m.reload_current_view();
3043 do_activate_record: function(index, id) {
3045 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3046 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3047 title: _t("Open: ") + self.name,
3048 write_function: function(id, data) {
3049 return self.o2m.dataset.write(id, data, {}, function(r) {
3050 self.o2m.reload_current_view();
3053 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3054 parent_view: self.o2m.view,
3055 child_name: self.o2m.name,
3056 read_function: function() {
3057 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3059 form_view_options: {'not_interactible_on_create':true},
3060 readonly: self.o2m.get("effective_readonly")
3063 do_button_action: function (name, id, callback) {
3065 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3066 return this._super(name, id, _.bind(def.resolve, def));
3070 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3071 form_template: 'One2Many.formview',
3072 on_loaded: function(data) {
3075 this.$buttons.find('button.oe_form_button_create').click(function() {
3076 self.do_save().then(self.on_button_new);
3079 do_notify_change: function() {
3080 if (this.dataset.parent_view) {
3081 this.dataset.parent_view.do_notify_change();
3083 this._super.apply(this, arguments);
3088 var lazy_build_o2m_kanban_view = function() {
3089 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3091 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3095 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3096 instance.web.form.ReinitializeFieldMixin, {
3097 template: "FieldMany2ManyTags",
3099 this._super.apply(this, arguments);
3100 instance.web.form.CompletionFieldMixin.init.call(this);
3101 this.set({"value": []});
3102 this._display_orderer = new instance.web.DropMisordered();
3103 this._drop_shown = false;
3107 instance.web.form.ReinitializeFieldMixin.start.call(this);
3108 this.on("change:value", this, this.render_value);
3110 initialize_content: function() {
3111 if (this.get("effective_readonly"))
3114 self.$text = $("textarea", this.$element);
3115 self.$text.textext({
3116 plugins : 'tags arrow autocomplete',
3118 render: function(suggestion) {
3119 return $('<span class="text-label"/>').
3120 data('index', suggestion['index']).html(suggestion['label']);
3125 selectFromDropdown: function() {
3126 $(this).trigger('hideDropdown');
3127 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3128 var data = self.search_result[index];
3130 self.add_id(data.id);
3137 isTagAllowed: function(tag) {
3142 removeTag: function(tag) {
3143 var id = tag.data("id");
3144 self.set({"value": _.without(self.get("value"), id)});
3146 renderTag: function(stuff) {
3147 return $.fn.textext.TextExtTags.prototype.renderTag.
3148 call(this, stuff).data("id", stuff.id);
3152 itemToString: function(item) {
3157 }).bind('getSuggestions', function(e, data) {
3159 var str = !!data ? data.query || '' : '';
3160 self.get_search_result(str).then(function(result) {
3161 self.search_result = result;
3162 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3163 return _.extend(el, {index:i});
3166 }).bind('hideDropdown', function() {
3167 self._drop_shown = false;
3168 }).bind('showDropdown', function() {
3169 self._drop_shown = true;
3171 self.tags = self.$text.textext()[0].tags();
3172 $("textarea", this.$element).focusout(function() {
3173 self.$text.trigger("setInputData", "");
3174 }).keydown(function(e) {
3175 if (event.keyCode === 9 && self._drop_shown) {
3176 self.$text.textext()[0].autocomplete().selectFromDropdown();
3180 set_value: function(value_) {
3181 value_ = value_ || [];
3182 if (value_.length >= 1 && value_[0] instanceof Array) {
3183 value_ = value_[0][2];
3185 this._super(value_);
3187 get_value: function() {
3188 var tmp = [commands.replace_with(this.get("value"))];
3191 get_search_blacklist: function() {
3192 return this.get("value");
3194 render_value: function() {
3196 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3197 var handle_names = function(data) {
3199 _.each(data, function(el) {
3200 indexed[el[0]] = el;
3202 data = _.map(self.get("value"), function(el) { return indexed[el]; });
3203 if (! self.get("effective_readonly")) {
3204 self.tags.containerElement().children().remove();
3205 $("textarea", self.$element).css("padding-left", "3px");
3206 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3208 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3211 if (! self.get('values') || self.get('values').length > 0) {
3212 this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3217 add_id: function(id) {
3218 this.set({'value': _.uniq(this.get('value').concat([id]))});
3223 * TODO niv: clean those deferred stuff, it could be better
3225 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3226 multi_selection: false,
3227 disable_utility_classes: true,
3228 init: function(field_manager, node) {
3229 this._super(field_manager, node);
3230 this.is_loaded = $.Deferred();
3231 this.initial_is_loaded = this.is_loaded;
3232 this.is_setted = $.Deferred();
3235 this._super.apply(this, arguments);
3239 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3240 this.dataset.m2m = this;
3241 this.dataset.on_unlink.add_last(function(ids) {
3242 self.dataset_changed();
3245 this.is_setted.then(function() {
3248 this.is_loaded.then(function() {
3249 self.on("change:effective_readonly", self, function() {
3250 self.is_loaded = self.is_loaded.pipe(function() {
3251 self.list_view.destroy();
3252 return $.when(self.load_view()).then(function() {
3253 self.reload_content();
3259 set_value: function(value_) {
3260 value_ = value_ || [];
3261 if (value_.length >= 1 && value_[0] instanceof Array) {
3262 value_ = value_[0][2];
3264 this._super(value_);
3265 this.dataset.set_ids(value_);
3267 self.reload_content();
3268 this.is_setted.resolve();
3270 load_view: function() {
3272 this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3273 'addable': self.get("effective_readonly") ? null : _t("Add"),
3274 'deletable': self.get("effective_readonly") ? false : true,
3275 'selectable': self.multi_selection,
3277 var embedded = (this.field.views || {}).tree;
3279 this.list_view.set_embedded_view(embedded);
3281 this.list_view.m2m_field = this;
3282 var loaded = $.Deferred();
3283 this.list_view.on_loaded.add_last(function() {
3284 self.initial_is_loaded.resolve();
3287 $.async_when().then(function () {
3288 self.list_view.appendTo(self.$element);
3292 reload_content: function() {
3294 this.is_loaded = this.is_loaded.pipe(function() {
3295 return self.list_view.reload_content();
3298 dataset_changed: function() {
3299 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3303 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3304 get_context: function() {
3305 this.context = this.m2m.build_context();
3306 return this.context;
3312 * @extends instance.web.ListView
3314 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3315 do_add_record: function () {
3316 var pop = new instance.web.form.SelectCreatePopup(this);
3320 title: _t("Add: ") + this.name
3322 new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3323 this.m2m_field.build_context()
3326 pop.on_select_elements.add(function(element_ids) {
3327 _.each(element_ids, function(one_id) {
3328 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3329 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3330 self.m2m_field.dataset_changed();
3331 self.reload_content();
3336 do_activate_record: function(index, id) {
3338 var pop = new instance.web.form.FormOpenPopup(this);
3339 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3340 title: _t("Open: ") + this.name,
3341 readonly: this.getParent().get("effective_readonly")
3343 pop.on_write_completed.add_last(function() {
3344 self.reload_content();
3349 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3350 disable_utility_classes: true,
3351 init: function(field_manager, node) {
3352 this._super(field_manager, node);
3353 instance.web.form.CompletionFieldMixin.init.call(this);
3354 m2m_kanban_lazy_init();
3355 this.is_loaded = $.Deferred();
3356 this.initial_is_loaded = this.is_loaded;
3357 this.is_setted = $.Deferred();
3360 this._super.apply(this, arguments);
3364 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3365 this.dataset.m2m = this;
3366 this.dataset.on_unlink.add_last(function(ids) {
3367 self.dataset_changed();
3370 this.is_setted.then(function() {
3373 this.is_loaded.then(function() {
3374 self.on("change:effective_readonly", self, function() {
3375 self.is_loaded = self.is_loaded.pipe(function() {
3376 self.kanban_view.destroy();
3377 return $.when(self.load_view()).then(function() {
3378 self.reload_content();
3384 set_value: function(value_) {
3385 value_ = value_ || [];
3386 if (value_.length >= 1 && value_[0] instanceof Array) {
3387 value_ = value_[0][2];
3389 this._super(value_);
3390 this.dataset.set_ids(value_);
3392 self.reload_content();
3393 this.is_setted.resolve();
3395 load_view: function() {
3397 this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3398 'create_text': _t("Add"),
3399 'creatable': self.get("effective_readonly") ? false : true,
3400 'quick_creatable': self.get("effective_readonly") ? false : true,
3401 'read_only_mode': self.get("effective_readonly") ? true : false,
3402 'confirm_on_delete': false,
3404 var embedded = (this.field.views || {}).kanban;
3406 this.kanban_view.set_embedded_view(embedded);
3408 this.kanban_view.m2m = this;
3409 var loaded = $.Deferred();
3410 this.kanban_view.on_loaded.add_last(function() {
3411 self.initial_is_loaded.resolve();
3414 this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3415 $.async_when().then(function () {
3416 self.kanban_view.appendTo(self.$element);
3420 reload_content: function() {
3422 this.is_loaded = this.is_loaded.pipe(function() {
3423 return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3426 dataset_changed: function() {
3427 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3429 open_popup: function(type, unused) {
3430 if (type !== "form")
3433 if (this.dataset.index === null) {
3434 var pop = new instance.web.form.SelectCreatePopup(this);
3436 this.field.relation,
3438 title: _t("Add: ") + this.name
3440 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3441 this.build_context()
3443 pop.on_select_elements.add(function(element_ids) {
3444 _.each(element_ids, function(one_id) {
3445 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3446 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3447 self.dataset_changed();
3448 self.reload_content();
3453 var id = self.dataset.ids[self.dataset.index];
3454 var pop = new instance.web.form.FormOpenPopup(self.view);
3455 pop.show_element(self.field.relation, id, self.build_context(), {
3456 title: _t("Open: ") + self.name,
3457 write_function: function(id, data, options) {
3458 return self.dataset.write(id, data, {}).then(function() {
3459 self.reload_content();
3462 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3463 parent_view: self.view,
3464 child_name: self.name,
3465 readonly: self.get("effective_readonly")
3469 add_id: function(id) {
3470 this.quick_create.add_id(id);
3474 function m2m_kanban_lazy_init() {
3475 if (instance.web.form.Many2ManyKanbanView)
3477 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3478 quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3479 _is_quick_create_enabled: function() {
3480 return this._super() && ! this.group_by;
3483 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3484 template: 'Many2ManyKanban.quick_create',
3487 * close_btn: If true, the widget will display a "Close" button able to trigger
3490 init: function(parent, dataset, context, buttons) {
3491 this._super(parent);
3492 this.m2m = this.getParent().view.m2m;
3493 this.m2m.quick_create = this;
3494 this._dataset = dataset;
3495 this._buttons = buttons || false;
3496 this._context = context || {};
3498 start: function () {
3500 self.$text = this.$element.find('input').css("width", "200px");
3501 self.$text.textext({
3502 plugins : 'arrow autocomplete',
3504 render: function(suggestion) {
3505 return $('<span class="text-label"/>').
3506 data('index', suggestion['index']).html(suggestion['label']);
3511 selectFromDropdown: function() {
3512 $(this).trigger('hideDropdown');
3513 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3514 var data = self.search_result[index];
3516 self.add_id(data.id);
3523 itemToString: function(item) {
3528 }).bind('getSuggestions', function(e, data) {
3530 var str = !!data ? data.query || '' : '';
3531 self.m2m.get_search_result(str).then(function(result) {
3532 self.search_result = result;
3533 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3534 return _.extend(el, {index:i});
3538 self.$text.focusout(function() {
3545 add_id: function(id) {
3548 self.trigger('added', id);
3549 this.m2m.dataset_changed();
3555 * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3557 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3558 template: "AbstractFormPopup.render",
3561 * -readonly: only applicable when not in creation mode, default to false
3562 * - alternative_form_view
3568 * - form_view_options
3570 init_popup: function(model, row_id, domain, context, options) {
3571 this.row_id = row_id;
3573 this.domain = domain || [];
3574 this.context = context || {};
3575 this.options = options;
3576 _.defaults(this.options, {
3579 init_dataset: function() {
3581 this.created_elements = [];
3582 this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3583 this.dataset.read_function = this.options.read_function;
3584 this.dataset.create_function = function(data, sup) {
3585 var fct = self.options.create_function || sup;
3586 return fct.call(this, data).then(function(r) {
3587 self.created_elements.push(r.result);
3590 this.dataset.write_function = function(id, data, options, sup) {
3591 var fct = self.options.write_function || sup;
3592 return fct.call(this, id, data, options).then(self.on_write_completed);
3594 this.dataset.parent_view = this.options.parent_view;
3595 this.dataset.child_name = this.options.child_name;
3597 display_popup: function() {
3599 this.renderElement();
3600 new instance.web.Dialog(this, {
3604 self.check_exit(true);
3606 title: this.options.title || "",
3607 }, this.$element).open();
3610 on_write_completed: function() {},
3611 setup_form_view: function() {
3614 this.dataset.ids = [this.row_id];
3615 this.dataset.index = 0;
3617 this.dataset.index = null;
3619 var options = _.clone(self.options.form_view_options) || {};
3620 if (this.row_id !== null) {
3621 options.initial_mode = this.options.readonly ? "view" : "edit";
3623 this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3624 if (this.options.alternative_form_view) {
3625 this.view_form.set_embedded_view(this.options.alternative_form_view);
3627 this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3628 this.view_form.on_loaded.add_last(function() {
3629 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3630 var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3631 $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3632 var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3633 $snbutton.click(function() {
3634 $.when(self.view_form.do_save()).then(function() {
3635 self.view_form.reload_mutex.exec(function() {
3636 self.view_form.on_button_new();
3640 var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3641 $sbutton.click(function() {
3642 $.when(self.view_form.do_save()).then(function() {
3643 self.view_form.reload_mutex.exec(function() {
3648 var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3649 $cbutton.click(function() {
3652 if (self.row_id !== null && self.options.readonly) {
3655 $cbutton.text(_t("Close"));
3657 self.view_form.do_show();
3660 on_select_elements: function(element_ids) {
3662 check_exit: function(no_destroy) {
3663 if (this.created_elements.length > 0) {
3664 this.on_select_elements(this.created_elements);
3665 this.created_elements = [];
3669 destroy: function () {
3670 this.$element.dialog('close');
3676 * Class to display a popup containing a form view.
3678 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3679 show_element: function(model, row_id, context, options) {
3680 this.init_popup(model, row_id, [], context, options);
3681 _.defaults(this.options, {
3683 this.display_popup();
3687 this.init_dataset();
3688 this.setup_form_view();
3693 * Class to display a popup to display a list to search a row. It also allows
3694 * to switch to a form view to create a new row.
3696 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3700 * - initial_view: form or search (default search)
3701 * - disable_multiple_selection
3702 * - list_view_options
3704 select_element: function(model, options, domain, context) {
3705 this.init_popup(model, null, domain, context, options);
3707 _.defaults(this.options, {
3708 initial_view: "search",
3710 this.initial_ids = this.options.initial_ids;
3711 this.display_popup();
3715 this.init_dataset();
3716 if (this.options.initial_view == "search") {
3717 self.rpc('/web/session/eval_domain_and_context', {
3719 contexts: [this.context]
3720 }, function (results) {
3721 var search_defaults = {};
3722 _.each(results.context, function (value_, key) {
3723 var match = /^search_default_(.*)$/.exec(key);
3725 search_defaults[match[1]] = value_;
3728 self.setup_search_view(search_defaults);
3734 setup_search_view: function(search_defaults) {
3736 if (this.searchview) {
3737 this.searchview.destroy();
3739 this.searchview = new instance.web.SearchView(this,
3740 this.dataset, false, search_defaults);
3741 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3742 if (self.initial_ids) {
3743 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3744 contexts, groupbys);
3745 self.initial_ids = undefined;
3747 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3750 this.searchview.on_loaded.add_last(function () {
3751 self.view_list = new instance.web.form.SelectCreateListView(self,
3752 self.dataset, false,
3753 _.extend({'deletable': false,
3754 'selectable': !self.options.disable_multiple_selection
3755 }, self.options.list_view_options || {}));
3756 self.view_list.popup = self;
3757 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3758 self.view_list.do_show();
3759 }).pipe(function() {
3760 self.searchview.do_search();
3762 self.view_list.on_loaded.add_last(function() {
3763 var $buttons = self.view_list.$element.find(".oe-actions");
3764 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3765 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3766 $cbutton.click(function() {
3769 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3770 if(self.options.disable_multiple_selection) {
3773 $sbutton.click(function() {
3774 self.on_select_elements(self.selected_ids);
3779 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3781 do_search: function(domains, contexts, groupbys) {
3783 this.rpc('/web/session/eval_domain_and_context', {
3784 domains: domains || [],
3785 contexts: contexts || [],
3786 group_by_seq: groupbys || []
3787 }, function (results) {
3788 self.view_list.do_search(results.domain, results.context, results.group_by);
3791 on_click_element: function(ids) {
3792 this.selected_ids = ids || [];
3793 if(this.selected_ids.length > 0) {
3794 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3796 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3799 new_object: function() {
3800 if (this.searchview) {
3801 this.searchview.hide();
3803 if (this.view_list) {
3804 this.view_list.$element.hide();
3806 this.setup_form_view();
3810 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3811 do_add_record: function () {
3812 this.popup.new_object();
3814 select_record: function(index) {
3815 this.popup.on_select_elements([this.dataset.ids[index]]);
3816 this.popup.destroy();
3818 do_select: function(ids, records) {
3819 this._super(ids, records);
3820 this.popup.on_click_element(ids);
3824 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3825 template: 'FieldReference',
3826 init: function(field_manager, node) {
3827 this._super(field_manager, node);
3828 this.reference_ready = true;
3830 on_nop: function() {
3832 on_selection_changed: function() {
3833 if (this.reference_ready) {
3834 var sel = this.selection.get_value();
3835 this.m2o.field.relation = sel;
3836 this.m2o.set_value(false);
3837 this.m2o.$element.toggle(sel !== false);
3840 destroy_content: function() {
3841 if (this.selection) {
3842 this.selection.destroy();
3843 this.selection = undefined;
3847 this.m2o = undefined;
3850 initialize_content: function() {
3851 this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3854 this.selection.view = this.view;
3855 this.selection.set({force_readonly: this.get('effective_readonly')});
3856 this.selection.on("change:value", this, this.on_selection_changed);
3857 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3858 this.selection.renderElement();
3859 this.selection.start();
3861 this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3864 this.m2o.view = this.view;
3865 this.m2o.set({force_readonly: this.get("effective_readonly")});
3866 this.m2o.on("change:value", this, this.data_changed);
3867 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3868 this.m2o.renderElement();
3871 is_false: function() {
3872 return typeof(this.get_value()) !== 'string';
3874 set_value: function(value_) {
3875 this._super(value_);
3876 this.render_value();
3878 render_value: function() {
3879 this.reference_ready = false;
3880 var vals = [], sel_val, m2o_val;
3881 if (typeof(this.get('value')) === 'string') {
3882 vals = this.get('value').split(',');
3884 sel_val = vals[0] || false;
3885 m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3886 if (!this.get("effective_readonly")) {
3887 this.selection.set_value(sel_val);
3889 this.m2o.field.relation = sel_val;
3890 this.m2o.set_value(m2o_val);
3891 this.reference_ready = true;
3893 data_changed: function() {
3894 var model = this.selection.get_value(),
3895 id = this.m2o.get_value();
3896 if (typeof(model) === 'string' && typeof(id) === 'number') {
3897 this.set({'value': model + ',' + id});
3899 this.set({'value': false});
3902 get_field: function(name) {
3903 if (name === "selection") {
3905 selection: this.view.fields_view.fields[this.name].selection,
3908 } else if (name === "m2o") {
3914 throw Exception("Should not happen");
3918 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3919 init: function(field_manager, node) {
3920 this._super(field_manager, node);
3921 this.iframe = this.element_id + '_iframe';
3922 this.binary_value = false;
3924 initialize_content: function() {
3925 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3926 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3927 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3929 human_filesize : function(size) {
3930 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3932 while (size >= 1024) {
3936 return size.toFixed(2) + ' ' + units[i];
3938 on_file_change: function(e) {
3939 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3940 // http://www.html5rocks.com/tutorials/file/dndfiles/
3941 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3942 window[this.iframe] = this.on_file_uploaded;
3943 if ($(e.target).val() != '') {
3944 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3945 this.$element.find('form.oe-binary-form').submit();
3946 this.$element.find('.oe-binary-progress').show();
3947 this.$element.find('.oe-binary').hide();
3950 on_file_uploaded: function(size, name, content_type, file_base64) {
3951 delete(window[this.iframe]);
3952 if (size === false) {
3953 this.do_warn("File Upload", "There was a problem while uploading your file");
3954 // TODO: use openerp web crashmanager
3955 console.warn("Error while uploading file : ", name);
3957 this.on_file_uploaded_and_valid.apply(this, arguments);
3959 this.$element.find('.oe-binary-progress').hide();
3960 this.$element.find('.oe-binary').show();
3962 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3964 on_save_as: function() {
3966 this.session.get_file({
3967 url: '/web/binary/saveas_ajax',
3968 data: {data: JSON.stringify({
3969 model: this.view.dataset.model,
3970 id: (this.view.datarecord.id || ''),
3972 filename_field: (this.node.attrs.filename || ''),
3973 context: this.view.dataset.get_context()
3975 complete: $.unblockUI,
3976 error: instance.webclient.crashmanager.on_rpc_error
3979 on_clear: function() {
3980 if (this.get('value') !== false) {
3981 this.binary_value = false;
3982 this.set({'value': false});
3988 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
3989 template: 'FieldBinaryFile',
3990 initialize_content: function() {
3992 if (this.get("effective_readonly")) {
3994 this.$element.find('a').click(function() {
3995 if (self.get('value')) {
4002 set_value: function(value_) {
4003 this._super.apply(this, arguments);
4004 this.render_value();
4006 render_value: function() {
4007 if (!this.get("effective_readonly")) {
4009 if (this.node.attrs.filename) {
4010 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4012 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4014 this.$element.find('input').eq(0).val(show_value);
4016 this.$element.find('a').show(!!this.get('value'));
4017 if (this.get('value')) {
4018 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4019 this.$element.find('a').text(show_value);
4023 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4024 this.binary_value = true;
4025 this.set({'value': file_base64});
4026 var show_value = name + " (" + this.human_filesize(size) + ")";
4027 this.$element.find('input').eq(0).val(show_value);
4028 this.set_filename(name);
4030 set_filename: function(value_) {
4031 var filename = this.node.attrs.filename;
4032 if (this.view.fields[filename]) {
4033 this.view.fields[filename].set({value: value_});
4036 on_clear: function() {
4037 this._super.apply(this, arguments);
4038 this.$element.find('input').eq(0).val('');
4039 this.set_filename('');
4043 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4044 template: 'FieldBinaryImage',
4045 initialize_content: function() {
4047 if (!this.get("effective_readonly")) {
4048 this.$element.find('.oe_form_field_image_controls').show();
4050 this.$element.find('.oe_form_field_image_controls').hide();
4053 set_value: function(value_) {
4054 this._super.apply(this, arguments);
4055 this.render_value();
4057 render_value: function() {
4059 if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4060 url = 'data:image/png;base64,' + this.get('value');
4061 } else if (this.get('value')) {
4062 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4063 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4065 url = "/web/static/src/img/placeholder.png";
4067 var img = QWeb.render("FieldBinaryImage-img", { widget: this, url: url });
4068 this.$element.find('> img').remove();
4069 this.$element.prepend(img);
4071 on_file_change: function() {
4072 this.render_value();
4073 this._super.apply(this, arguments);
4075 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4076 this.set({'value': file_base64});
4077 this.binary_value = true;
4078 this.render_value();
4080 on_clear: function() {
4081 this._super.apply(this, arguments);
4082 this.render_value();
4086 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4090 this.selected_value = null;
4091 // preview in start only for selection fields, because of the dynamic behavior of many2one fields.
4092 if (this.field.type in ['selection']) {
4096 set_value: function(value_) {
4098 this._super(value_);
4099 // find selected value:
4100 // - many2one: [2, "New"] -> 2
4101 // - selection: new -> new
4102 if (this.field.type == "many2one") {
4103 this.selected_value = value_[0];
4105 this.selected_value = value_;
4107 // trick to be sure all values are loaded in the form, therefore
4108 // enabling the evaluation of dynamic domains
4109 $.async_when().then(function() {
4110 return self.render_list();
4114 /** Get the status list and render them
4115 * to_show: [[identifier, value_to_display]] where
4116 * - identifier = key for a selection, id for a many2one
4117 * - display_val = label that will be displayed
4118 * - ex: [[0, "New"]] (many2one) or [["new", "In Progress"]] (selection)
4120 render_list: function() {
4122 // get selection values, filter them and render them
4123 var selection_done = this.get_selection().pipe(self.proxy('filter_selection')).pipe(self.proxy('render_elements'));
4126 /** Get the selection list to be displayed in the statusbar widget.
4127 * For selection fields: this is directly given by this.field.selection
4128 * For many2one fields :
4129 * - perform a search on the relation of the many2one field (given by
4131 * - get the field domain for the search
4132 * - self.build_domain() gives the domain given by the view or by
4134 * - if the optional statusbar_fold attribute is set to true, make
4135 * an AND with build_domain to hide all 'fold=true' columns
4136 * - make an OR with current value, to be sure it is displayed,
4137 * with the correct order, even if it is folded
4139 get_selection: function() {
4141 if (this.field.type == "many2one") {
4142 this.selection = [];
4143 // get fold information from widget
4144 var fold = ((this.node.attrs || {}).statusbar_fold || true);
4145 // build final domain: if fold option required, add the
4147 var domain = new instance.web.CompoundDomain(['|'], ['&'], self.build_domain(), [['fold', '=', false]], [['id', '=', self.selected_value]]);
4149 var domain = new instance.web.CompoundDomain(['|'], self.build_domain(), [['id', '=', self.selected_value]]);
4151 // get a DataSetSearch on the current field relation (ex: crm.lead.stage_id -> crm.case.stage)
4152 var model_ext = new instance.web.DataSetSearch(this, this.field.relation, self.build_context(), domain);
4154 var read_defer = model_ext.read_slice(['name'], {}).pipe( function (records) {
4155 _(records).each(function (record) {
4156 self.selection.push([record.id, record.name]);
4160 this.selection = this.field.selection;
4161 var read_defer = new $.Deferred().resolve();
4166 /** Filters this.selection, according to values coming from the statusbar_visible
4167 * attribute of the field. For example: statusbar_visible="draft,open"
4168 * Currently, the key of (key, label) pairs has to be used in the
4169 * selection of visible items. This feature is not meant to be used
4170 * with many2one fields.
4172 filter_selection: function() {
4174 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4175 function(x) { return _.str.trim(x); });
4176 shown = _.select(shown, function(x) { return x.length > 0; });
4178 if (shown.length == 0) {
4179 this.to_show = this.selection;
4181 this.to_show = _.select(this.selection, function(x) {
4182 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4187 /** Renders the widget. This function also checks for statusbar_colors='{"pending": "blue"}'
4188 * attribute in the widget. This allows to set a given color to a given
4189 * state (given by the key of (key, label)).
4191 render_elements: function () {
4192 var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4193 this.$element.html(content);
4195 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4196 var color = colors[this.selected_value];
4198 var elem = this.$element.find("li.oe_form_steps_active span");
4199 elem.css("color", color);
4205 * Registry of form fields, called by :js:`instance.web.FormView`.
4207 * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4208 * will substitute to the <field> tags as defined in OpenERP's views.
4210 instance.web.form.widgets = new instance.web.Registry({
4211 'char' : 'instance.web.form.FieldChar',
4212 'id' : 'instance.web.form.FieldID',
4213 'email' : 'instance.web.form.FieldEmail',
4214 'url' : 'instance.web.form.FieldUrl',
4215 'text' : 'instance.web.form.FieldText',
4216 'date' : 'instance.web.form.FieldDate',
4217 'datetime' : 'instance.web.form.FieldDatetime',
4218 'selection' : 'instance.web.form.FieldSelection',
4219 'many2one' : 'instance.web.form.FieldMany2One',
4220 'many2many' : 'instance.web.form.FieldMany2Many',
4221 'many2many_tags' : 'instance.web.form.FieldMany2ManyTags',
4222 'many2many_kanban' : 'instance.web.form.FieldMany2ManyKanban',
4223 'one2many' : 'instance.web.form.FieldOne2Many',
4224 'one2many_list' : 'instance.web.form.FieldOne2Many',
4225 'reference' : 'instance.web.form.FieldReference',
4226 'boolean' : 'instance.web.form.FieldBoolean',
4227 'float' : 'instance.web.form.FieldFloat',
4228 'integer': 'instance.web.form.FieldFloat',
4229 'float_time': 'instance.web.form.FieldFloat',
4230 'progressbar': 'instance.web.form.FieldProgressBar',
4231 'image': 'instance.web.form.FieldBinaryImage',
4232 'binary': 'instance.web.form.FieldBinaryFile',
4233 'statusbar': 'instance.web.form.FieldStatus'
4237 * Registry of widgets usable in the form view that can substitute to any possible
4238 * tags defined in OpenERP's form views.
4240 * Every referenced class should extend FormWidget.
4242 instance.web.form.tags = new instance.web.Registry({
4243 'button' : 'instance.web.form.WidgetButton',
4248 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: