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);
109 this.$sidebar = this.options.$sidebar || this.$element.find('.oe_form_sidebar');
111 this.$buttons = $(QWeb.render("FormView.buttons", {'widget':self}));
112 if (this.options.$buttons) {
113 this.$buttons.appendTo(this.options.$buttons);
115 this.$element.find('.oe_form_buttons').replaceWith(this.$buttons);
117 this.$buttons.on('click','.oe_form_button_create',this.on_button_create);
118 this.$buttons.on('click','.oe_form_button_edit',this.on_button_edit);
119 this.$buttons.on('click','.oe_form_button_duplicate',this.on_button_duplicate);
120 this.$buttons.on('click','.oe_form_button_delete',this.on_button_delete);
121 this.$buttons.on('click','.oe_form_button_save',this.on_button_save);
122 this.$buttons.on('click','.oe_form_button_cancel',this.on_button_cancel);
124 this.$pager = $(QWeb.render("FormView.pager", {'widget':self}));
125 if (this.options.$pager) {
126 this.$pager.appendTo(this.options.$pager);
128 this.$element.find('.oe_form_pager').replaceWith(this.$pager);
130 this.$pager.on('click','a[data-pager-action]',function() {
131 var action = $(this).data('pager-action');
132 self.on_pager_action(action);
135 if (!this.sidebar && this.options.$sidebar) {
136 this.sidebar = new instance.web.Sidebar(this);
137 this.sidebar.appendTo(this.$sidebar);
138 if(this.fields_view.toolbar) {
139 this.sidebar.add_toolbar(this.fields_view.toolbar);
141 this.sidebar.add_items('other', [{
142 label: _t('Set Default'),
144 callback: function (item) {
145 item.form.open_defaults_dialog();
149 this.on("change:mode", this, this.switch_mode);
150 this.set({mode: this.options.initial_mode});
151 this.has_been_loaded.resolve();
154 extract_qweb_template: function(fvg) {
155 for (var i=0, ii=fvg.arch.children.length; i < ii; i++) {
156 var child = fvg.arch.children[i];
157 if (child.tag === "templates") {
158 this.qweb = new QWeb2.Engine();
159 this.qweb.add_template(instance.web.json_node_to_xml(child));
160 if (!this.qweb.has_template('form')) {
161 throw new Error("No QWeb template found for form view");
169 get_fvg_from_qweb: function(record) {
170 var view = this.qweb.render('form', this.get_qweb_context(record));
171 var fvg = _.clone(this.fields_view);
172 fvg.arch = instance.web.xml_to_json(instance.web.str_to_xml(view).firstChild);
175 get_qweb_context: function(record) {
178 _.each(record, function(value_, name) {
179 var r = _.clone(self.fields_view.fields[name] || {});
180 if ((r.type === 'date' || r.type === 'datetime') && value_) {
181 r.raw_value = instance.web.auto_str_to_date(value_);
183 r.raw_value = value_;
185 r.value = instance.web.format_value(value_, r);
186 new_record[name] = r;
190 new_record : !record.id
193 kill_current_form: function() {
194 _.each(this.getChildren(), function(el) {
198 this.fields_order = [];
199 this.default_focus_field = null;
200 this.default_focus_button = null;
201 this.translatable_fields = [];
202 this.$element.find('.oe_form_container').empty();
204 do_load_state: function(state, warm) {
205 if (state.id && this.datarecord.id != state.id) {
206 if (!this.dataset.get_id_index(state.id)) {
207 this.dataset.ids.push(state.id);
209 this.dataset.select_id(state.id);
215 do_show: function () {
218 this.sidebar.$element.show();
221 this.$buttons.show();
222 this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
227 this.$element.show().css('visibility', 'hidden');
228 this.$element.removeClass('oe_form_dirty');
229 return this.has_been_loaded.pipe(function() {
231 if (self.dataset.index === null) {
232 // null index means we should start a new record
233 result = self.on_button_new();
235 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
236 context : { 'bin_size' : true }
237 }).pipe(self.on_record_loaded);
239 result.pipe(function() {
240 self.$element.css('visibility', 'visible');
245 do_hide: function () {
247 this.sidebar.$element.hide();
250 this.$buttons.hide();
257 on_record_loaded: function(record) {
258 var self = this, set_values = [];
260 this.do_warn("Form", "The record could not be found in the database.", true);
261 return $.Deferred().reject();
263 this.datarecord = record;
266 this.kill_current_form();
267 this.rendering_engine.set_fields_view(this.get_fvg_from_qweb(record));
268 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
269 this.rendering_engine.render_to($dest);
272 _(this.fields).each(function (field, f) {
273 field._dirty_flag = false;
274 var result = field.set_value(self.datarecord[f] || false);
275 set_values.push(result);
277 return $.when.apply(null, set_values).pipe(function() {
279 // New record: Second pass in order to trigger the onchanges
280 // respecting the fields order defined in the view
281 _.each(self.fields_order, function(field_name) {
282 if (record[field_name] !== undefined) {
283 var field = self.fields[field_name];
284 field._dirty_flag = true;
285 self.do_onchange(field);
289 self.on_form_changed();
290 self.is_initialized.resolve();
291 self.do_update_pager(record.id == null);
293 self.sidebar.do_attachement_update(self.dataset, self.datarecord.id);
295 if (self.default_focus_field) {
296 self.default_focus_field.focus();
299 self.do_push_state({id:record.id});
301 self.$element.removeClass('oe_form_dirty');
302 self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
305 on_form_changed: function() {
306 this.trigger("view_content_has_changed");
308 do_notify_change: function() {
309 this.$element.addClass('oe_form_dirty');
310 this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
312 on_pager_action: function(action) {
313 if (this.can_be_discarded()) {
316 this.dataset.index = 0;
319 this.dataset.previous();
325 this.dataset.index = this.dataset.ids.length - 1;
331 do_update_pager: function(hide_index) {
332 var index = hide_index ? '-' : this.dataset.index + 1;
333 this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
334 .find('span.oe_pager_index').html(index).end()
335 .find('span.oe_pager_count').html(this.dataset.ids.length);
337 parse_on_change: function (on_change, widget) {
339 var onchange = _.str.trim(on_change);
340 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
345 var method = call[1];
346 if (!_.str.trim(call[2])) {
347 return {method: method, args: [], context_index: null}
350 var argument_replacement = {
351 'False': function () {return false;},
352 'True': function () {return true;},
353 'None': function () {return null;},
354 'context': function (i) {
356 var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
360 var parent_fields = null, context_index = null;
361 var args = _.map(call[2].split(','), function (a, i) {
362 var field = _.str.trim(a);
364 // literal constant or context
365 if (field in argument_replacement) {
366 return argument_replacement[field](i);
369 if (/^-?\d+(\.\d+)?$/.test(field)) {
370 return Number(field);
373 if (self.fields[field]) {
374 var value_ = self.fields[field].get_value();
375 return value_ == null ? false : value_;
378 var splitted = field.split('.');
379 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
380 if (parent_fields === null) {
381 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
383 var p_val = parent_fields[_.str.trim(splitted[1])];
384 if (p_val !== undefined) {
385 return p_val == null ? false : p_val;
389 var first_char = field[0], last_char = field[field.length-1];
390 if ((first_char === '"' && last_char === '"')
391 || (first_char === "'" && last_char === "'")) {
392 return field.slice(1, -1);
395 throw new Error("Could not get field with name '" + field +
396 "' for onchange '" + onchange + "'");
402 context_index: context_index
405 do_onchange: function(widget, processed) {
407 return this.on_change_mutex.exec(function() {
409 var response = {}, can_process_onchange = $.Deferred();
410 processed = processed || [];
411 processed.push(widget.name);
412 var on_change = widget.node.attrs.on_change;
414 var change_spec = self.parse_on_change(on_change, widget);
417 url: '/web/dataset/onchange',
420 can_process_onchange = self.rpc(ajax, {
421 model: self.dataset.model,
422 method: change_spec.method,
423 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
424 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
425 }).then(function(r) {
426 _.extend(response, r);
429 console.warn("Wrong on_change format", on_change);
432 // fail if onchange failed
433 if (can_process_onchange.isRejected()) {
434 return can_process_onchange;
437 if (widget.field['change_default']) {
438 var fieldname = widget.name, value_;
439 if (response.value && (fieldname in response.value)) {
440 // Use value from onchange if onchange executed
441 value_ = response.value[fieldname];
443 // otherwise get form value for field
444 value_ = self.fields[fieldname].get_value();
446 var condition = fieldname + '=' + value_;
449 can_process_onchange = self.rpc({
450 url: '/web/dataset/call',
454 method: 'get_defaults',
455 args: [self.model, condition]
456 }).then(function (results) {
457 if (!results.length) { return; }
458 if (!response.value) {
461 for(var i=0; i<results.length; ++i) {
462 // [whatever, key, value]
463 var triplet = results[i];
464 response.value[triplet[1]] = triplet[2];
469 if (can_process_onchange.isRejected()) {
470 return can_process_onchange;
473 return self.on_processed_onchange(response, processed);
476 return $.Deferred().reject();
480 on_processed_onchange: function(response, processed) {
482 var result = response;
484 for (var f in result.value) {
485 if (!result.value.hasOwnProperty(f)) { continue; }
486 var field = this.fields[f];
487 // If field is not defined in the view, just ignore it
489 var value_ = result.value[f];
490 if (field.get_value() != value_) {
491 field.set_value(value_);
492 field._dirty_flag = true;
493 if (!_.contains(processed, field.name)) {
494 this.do_onchange(field, processed);
499 this.on_form_changed();
501 if (!_.isEmpty(result.warning)) {
502 instance.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
505 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
510 function edit_domain(node) {
511 var new_domain = result.domain[node.attrs.name];
513 node.attrs.domain = new_domain;
515 _(node.children).each(edit_domain);
517 edit_domain(this.fields_view.arch);
519 return $.Deferred().resolve();
522 return $.Deferred().reject();
525 switch_mode: function() {
527 if(this.get("mode") == "view") {
528 self.$buttons.find('.oe_form_buttons_edit').hide();
529 self.$buttons.find('.oe_form_buttons_view').show();
530 _.each(this.fields,function(field){
531 field.set({"force_readonly": true});
534 self.$buttons.find('.oe_form_buttons_edit').show();
535 self.$buttons.find('.oe_form_buttons_view').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 + "</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') {
810 switch(field.field.type) {
812 displayed = _(field.values).find(function (option) {
813 return option[0] === value_;
825 string: field.node_atts.string,
827 displayed: displayed,
828 // convert undefined to false
829 change_default: !!field.field.change_default
833 .sortBy(function (field) { return field.node_atts.string; })
835 var conditions = _.chain(fields)
836 .filter(function (field) { return field.change_default; })
839 var d = new instance.web.Dialog(this, {
840 title: _t("Set Default"),
843 conditions: conditions
846 {text: _t("Close"), click: function () { d.close(); }},
847 {text: _t("Save default"), click: function () {
848 var $defaults = d.$element.find('#formview_default_fields');
849 var field_to_set = $defaults.val();
851 $defaults.parent().addClass('oe_form_invalid');
854 var condition = d.$element.find('#formview_default_conditions').val(),
855 all_users = d.$element.find('#formview_default_all').is(':checked');
856 new instance.web.DataSet(self, 'ir.values').call(
860 self.fields[field_to_set].get_value(),
864 ]).then(function () { d.close(); });
868 d.template = 'FormView.set_default';
871 register_field: function(field, name) {
872 this.fields[name] = field;
873 this.fields_order.push(name);
874 if (this.get_field(name).translate) {
875 this.translatable_fields.push(field);
877 field.on('changed_value', this, function() {
878 field._dirty_flag = true;
879 if (field.is_syntax_valid()) {
880 this.do_onchange(field);
881 this.on_form_changed(true);
882 this.do_notify_change();
886 get_field: function(field_name) {
887 return this.fields_view.fields[field_name];
889 is_create_mode: function() {
890 return !this.datarecord.id;
895 * Interface to be implemented by rendering engines for the form view.
897 instance.web.form.FormRenderingEngineInterface = instance.web.Class.extend({
898 set_fields_view: function(fields_view) {},
899 set_fields_registry: function(fields_registry) {},
900 render_to: function($element) {},
904 * Default rendering engine for the form view.
906 * It is necessary to set the view using set_view() before usage.
908 instance.web.form.FormRenderingEngine = instance.web.form.FormRenderingEngineInterface.extend({
909 init: function(view) {
912 set_fields_view: function(fvg) {
915 set_tags_registry: function(tags_registry) {
916 this.tags_registry = tags_registry;
918 set_fields_registry: function(fields_registry) {
919 this.fields_registry = fields_registry;
921 render_to: function($target) {
923 this.$target = $target;
925 // TODO: I know this will save the world and all the kitten for a moment,
926 // but one day, we will have to get rid of xml2json
927 var xml = instance.web.json_node_to_xml(this.fvg.arch);
928 this.$form = $('<div class="oe_form">' + xml + '</div>');
929 if (this.fvg.arch.attrs && this.fvg.arch.attrs['layout'] !== 'manual') {
930 this.$form.attr('layout', 'auto');
933 this.fields_to_init = [];
934 this.tags_to_init = [];
936 this.process(this.$form);
938 this.$form.appendTo(this.$target);
940 _.each(this.fields_to_init, function($elem) {
941 var name = $elem.attr("name");
942 if (!self.fvg.fields[name]) {
943 throw new Error("Field '" + name + "' specified in view could not be found.");
945 var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
947 throw new Error("Widget type '"+ key + "' is not implemented");
949 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
950 var $label = self.labels[$elem.attr("name")];
952 w.set_input_id($label.attr("for"));
955 self.view.register_field(w, $elem.attr("name"));
958 _.each(this.tags_to_init, function($elem) {
959 var tag_name = $elem[0].tagName.toLowerCase();
960 var obj = self.tags_registry.get_object(tag_name);
961 var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
964 // TODO: return a deferred
966 render_element: function(template, layout/* dictionaries */) {
967 var dicts = [].slice.call(arguments).slice(2);
968 dicts.unshift({ 'layout' : layout });
969 var dict = _.extend.apply(_, dicts);
970 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
971 var alt_template = template + '.' + layout;
972 template = QWeb.has_template(alt_template) ? alt_template : template;
973 return $(QWeb.render(template, dict));
975 alter_field: function(field) {
977 toggle_layout_debugging: function() {
978 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
979 this.$target.find('[title]').removeAttr('title');
980 this.$target.find('.oe_form_group_cell').each(function() {
981 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
982 $(this).attr('title', text);
985 this.$target.toggleClass('oe_layout_debugging');
987 process: function($tag, layout) {
989 if ($tag.attr('layout') === 'auto') {
990 $tag.addClass('oe_form_autolayout');
992 layout = $tag.attr('layout') || layout || 'auto';
993 $tag.removeAttr('layout');
994 var tagname = $tag[0].nodeName.toLowerCase();
995 if (this.tags_registry.contains(tagname)) {
996 this.tags_to_init.push($tag);
999 var fn = self['process_' + tagname];
1001 var args = [].slice.call(arguments);
1004 return fn.apply(self, args);
1006 // generic tag handling, just process children
1007 $tag.children().each(function() {
1008 self.process($(this), layout);
1010 self.handle_common_properties($tag, $tag);
1011 $tag.removeAttr("modifiers");
1015 process_sheet: function($sheet, layout) {
1016 var $new_sheet = this.render_element('FormRenderingSheet', layout, $sheet.getAttributes());
1017 this.handle_common_properties($new_sheet, $sheet);
1018 var $dst = (layout === 'auto') ? $new_sheet.find('group:first') : $new_sheet.find('.oe_form_sheet');
1019 $sheet.children().appendTo($dst);
1020 $sheet.before($new_sheet).remove();
1021 this.process($new_sheet, layout);
1023 process_form: function($form, layout) {
1024 var $new_form = this.render_element('FormRenderingForm', layout, $form.getAttributes());
1025 this.handle_common_properties($new_form, $form);
1026 var $dst = (layout === 'auto') ? $new_form.find('group:first') : $new_form;
1027 $form.children().appendTo($dst);
1028 if ($form[0] === this.$form[0]) {
1029 // If root element, replace it
1030 this.$form = $new_form;
1032 $form.before($new_form).remove();
1034 this.process($new_form, layout);
1036 preprocess_field: function($field) {
1038 var name = $field.attr('name'),
1039 field_colspan = parseInt($field.attr('colspan'), 10),
1040 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1042 if ($field.attr('nolabel') === '1')
1044 $field.attr('nolabel', '1');
1046 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1047 $(el).parents().each(function(unused, tag) {
1048 var name = tag.tagName.toLowerCase();
1049 if (name === "field" || name in self.tags_registry.map)
1056 $label = $('<label/>').attr({
1058 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1059 "string": $field.attr('string'),
1060 "help": $field.attr('help'),
1062 $label.insertBefore($field);
1063 if (field_colspan > 1) {
1064 $field.attr('colspan', field_colspan - 1);
1068 process_field: function($field, layout) {
1069 var $label = this.preprocess_field($field);
1071 this.process($label, layout);
1072 this.fields_to_init.push($field);
1075 process_group: function($group, layout) {
1077 if ($group.parent().is('.oe_form_group_cell')) {
1078 $group.parent().addClass('oe_form_group_nested');
1080 $group.children('field').each(function() {
1081 self.preprocess_field($(this));
1083 var $new_group = this.render_element('FormRenderingGroup', layout, $group.getAttributes()),
1085 if ($new_group.is('table')) {
1086 $table = $new_group;
1088 $table = $new_group.find('table:first');
1090 $table.addClass('oe_form_group');
1092 cols = parseInt($group.attr('col') || 4, 10),
1096 $group.children().each(function(a,b,c) {
1097 var $child = $(this);
1098 var colspan = parseInt($child.attr('colspan') || 1, 10);
1099 var tagName = $child[0].tagName.toLowerCase();
1100 var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1101 var newline = tagName === 'newline';
1102 if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1103 $tr.addClass('oe_form_group_row_incomplete');
1105 $tr.addClass('oe_form_group_row_newline');
1112 if (!$tr || row_cols < colspan) {
1113 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1116 row_cols -= colspan;
1118 // invisibility transfer
1119 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1120 var invisible = field_modifiers.invisible;
1121 field_modifiers.invisible = undefined;
1122 $child.attr('modifiers', JSON.stringify(field_modifiers));
1123 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1125 $tr.append($td.append($child));
1126 children.push($child[0]);
1128 if (row_cols && $td) {
1129 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1131 $group.before($new_group).remove();
1133 // Now compute width of cells
1134 $table.find('> tbody > tr').each(function() {
1135 var to_compute = [],
1138 $(this).children().each(function() {
1140 $child = $td.children(':first');
1141 switch ($child[0].tagName.toLowerCase()) {
1143 if ($child.attr('orientation') === 'vertical') {
1144 $td.addClass('oe_vertical_separator').attr('width', '1');
1150 if ($child.attr('for')) {
1151 $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1157 var width = _.str.trim($child.attr('width') || ''),
1158 iwidth = parseInt(width, 10);
1160 if (width.substr(-1) === '%') {
1162 width = iwidth + '%';
1164 $td.attr('width', width);
1165 $child.removeAttr('width');
1168 to_compute.push($td);
1173 var unit = Math.floor(total / row_cols);
1174 if (!$(this).is('.oe_form_group_row_incomplete')) {
1175 _.each(to_compute, function($td, i) {
1176 var width = parseInt($td.attr('colspan'), 10) * unit;
1177 $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
1182 _.each(children, function(el) {
1183 self.process($(el));
1185 this.handle_common_properties($new_group, $group);
1188 process_notebook: function($notebook, layout) {
1191 $notebook.find('> page').each(function() {
1192 var $page = $(this);
1193 var page_attrs = $page.getAttributes();
1194 page_attrs.id = _.uniqueId('notebook_page_');
1195 pages.push(page_attrs);
1196 var $new_page = self.render_element('FormRenderingNotebookPage', layout, page_attrs);
1197 var $dst = (layout === 'auto') ? $new_page.find('group:first') : $new_page;
1198 $page.children().appendTo($dst);
1199 $page.before($new_page).remove();
1200 self.handle_common_properties($new_page, $page);
1202 var $new_notebook = this.render_element('FormRenderingNotebook', layout, { pages : pages });
1203 $notebook.children().appendTo($new_notebook);
1204 $notebook.before($new_notebook).remove();
1205 $new_notebook.children().each(function() {
1206 self.process($(this));
1208 $new_notebook.tabs();
1209 this.handle_common_properties($new_notebook, $notebook);
1210 return $new_notebook;
1212 process_separator: function($separator, layout) {
1213 var $new_separator = this.render_element('FormRenderingSeparator', layout, $separator.getAttributes());
1214 $separator.before($new_separator).remove();
1215 this.handle_common_properties($new_separator, $separator);
1216 return $new_separator;
1218 process_label: function($label, layout) {
1219 var name = $label.attr("for"),
1220 field_orm = this.fvg.fields[name];
1222 string: $label.attr('string') || (field_orm || {}).string || '',
1223 help: $label.attr('help') || (field_orm || {}).help || '',
1224 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1226 var align = parseFloat(dict.align);
1227 if (isNaN(align) || align === 1) {
1229 } else if (align === 0) {
1235 var $new_label = this.render_element('FormRenderingLabel', layout, dict);
1236 $label.before($new_label).remove();
1237 this.handle_common_properties($new_label, $label);
1239 this.labels[name] = $new_label;
1243 handle_common_properties: function($new_element, $node) {
1244 var str_modifiers = $node.attr("modifiers") || "{}"
1245 var modifiers = JSON.parse(str_modifiers);
1246 if (modifiers.invisible !== undefined)
1247 new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1248 $new_element.addClass($node.attr("class") || "");
1249 $new_element.attr('style', $node.attr('style'));
1253 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1254 alter_field: function(field) {
1255 field.set({"force_readonly": true});
1259 instance.web.form.FormDialog = instance.web.Dialog.extend({
1260 init: function(parent, options, view_id, dataset) {
1261 this._super(parent, options);
1262 this.dataset = dataset;
1263 this.view_id = view_id;
1268 this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1271 this.form.appendTo(this.$element);
1272 this.form.on_created.add_last(this.on_form_dialog_saved);
1273 this.form.on_saved.add_last(this.on_form_dialog_saved);
1276 select_id: function(id) {
1277 if (this.form.dataset.select_id(id)) {
1278 return this.form.do_show();
1280 this.do_warn("Could not find id in dataset");
1281 return $.Deferred().reject();
1284 on_form_dialog_saved: function(r) {
1289 instance.web.form.compute_domain = function(expr, fields) {
1291 for (var i = expr.length - 1; i >= 0; i--) {
1293 if (ex.length == 1) {
1294 var top = stack.pop();
1297 stack.push(stack.pop() || top);
1300 stack.push(stack.pop() && top);
1306 throw new Error(_.str.sprintf(
1307 _t("Unknown operator %s in domain %s"),
1308 ex, JSON.stringify(expr)));
1312 var field = fields[ex[0]];
1314 throw new Error(_.str.sprintf(
1315 _t("Unknown field %s in domain %s"),
1316 ex[0], JSON.stringify(expr)));
1318 var field_value = field.get_value ? field.get_value() : field.value;
1322 switch (op.toLowerCase()) {
1325 stack.push(field_value == val);
1329 stack.push(field_value != val);
1332 stack.push(field_value < val);
1335 stack.push(field_value > val);
1338 stack.push(field_value <= val);
1341 stack.push(field_value >= val);
1344 if (!_.isArray(val)) val = [val];
1345 stack.push(_(val).contains(field_value));
1348 if (!_.isArray(val)) val = [val];
1349 stack.push(!_(val).contains(field_value));
1353 _t("Unsupported operator %s in domain %s"),
1354 op, JSON.stringify(expr));
1357 return _.all(stack, _.identity);
1361 * Must be applied over an class already possessing the PropertiesMixin.
1363 * Apply the result of the "invisible" domain to this.$element.
1365 instance.web.form.InvisibilityChangerMixin = {
1366 init: function(field_manager, invisible_domain) {
1367 this._ic_field_manager = field_manager
1368 this._ic_invisible_modifier = invisible_domain;
1369 this._ic_field_manager.on("view_content_has_changed", this, function() {
1370 var result = this._ic_invisible_modifier === undefined ? false :
1371 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1372 this.set({"invisible": result});
1374 this.set({invisible: this._ic_invisible_modifier === true});
1377 var check_visibility = function() {
1378 if (this.get("invisible")) {
1379 this.$element.hide();
1381 this.$element.show();
1384 this.on("change:invisible", this, check_visibility);
1385 _.bind(check_visibility, this)();
1389 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1390 init: function(parent, field_manager, invisible_domain, $element) {
1391 this.setParent(parent);
1392 instance.web.PropertiesMixin.init.call(this);
1393 instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1394 this.$element = $element;
1399 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1401 * @constructs instance.web.form.FormWidget
1402 * @extends instance.web.Widget
1407 init: function(view, node) {
1411 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1412 instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1414 this.view.on("view_content_has_changed", this, this.process_modifiers);
1416 renderElement: function() {
1418 this.$element.addClass(this.node.attrs["class"] || "");
1420 destroy: function() {
1422 this._super.apply(this, arguments);
1424 process_modifiers: function() {
1425 var compute_domain = instance.web.form.compute_domain;
1427 for (var a in this.modifiers) {
1428 if (!_.include(["invisible"], a)) {
1429 var val = compute_domain(this.modifiers[a], this.view.fields);
1435 do_attach_tooltip: function(widget, trigger, options) {
1436 widget = widget || this;
1437 trigger = trigger || this.$element;
1438 options = _.extend({
1443 var template = widget.template + '.tooltip';
1444 if (!QWeb.has_template(template)) {
1445 template = 'WidgetLabel.tooltip';
1447 return QWeb.render(template, {
1448 debug: instance.connection.debug,
1451 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1456 $(trigger).tipsy(options);
1458 _build_view_fields_values: function(blacklist) {
1459 var a_dataset = this.view.dataset;
1460 var fields_values = this.view.get_fields_values(blacklist);
1461 var active_id = a_dataset.ids[a_dataset.index];
1462 _.extend(fields_values, {
1463 active_id: active_id || false,
1464 active_ids: active_id ? [active_id] : [],
1465 active_model: a_dataset.model,
1468 if (a_dataset.parent_view) {
1469 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1471 return fields_values;
1473 _build_eval_context: function(blacklist) {
1474 var a_dataset = this.view.dataset;
1475 return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1478 * Builds a new context usable for operations related to fields by merging
1479 * the fields'context with the action's context.
1481 build_context: function(blacklist) {
1482 // only use the model's context if there is not context on the node
1483 var v_context = this.node.attrs.context;
1485 v_context = (this.field || {}).context || {};
1488 if (v_context.__ref || true) { //TODO: remove true
1489 var fields_values = this._build_eval_context(blacklist);
1490 v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1494 build_domain: function() {
1495 var f_domain = this.field.domain || [];
1496 var n_domain = this.node.attrs.domain || null;
1497 // if there is a domain on the node, overrides the model's domain
1498 var final_domain = n_domain !== null ? n_domain : f_domain;
1499 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1500 var fields_values = this._build_eval_context();
1501 final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1503 return final_domain;
1507 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1508 template: 'WidgetButton',
1509 init: function(view, node) {
1510 this._super(view, node);
1511 this.force_disabled = false;
1512 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1513 if (this.node.attrs.default_focus == '1') {
1514 // TODO fme: provide enter key binding to widgets
1515 this.view.default_focus_button = this;
1517 this.view.on('view_content_has_changed', this, this.check_disable);
1520 this._super.apply(this, arguments);
1521 this.$element.click(this.on_click);
1522 if (this.node.attrs.help || instance.connection.debug) {
1523 this.do_attach_tooltip();
1526 on_click: function() {
1528 this.force_disabled = true;
1529 this.check_disable();
1530 this.execute_action().always(function() {
1531 self.force_disabled = false;
1532 self.check_disable();
1535 execute_action: function() {
1537 var exec_action = function() {
1538 if (self.node.attrs.confirm) {
1539 var def = $.Deferred();
1540 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1541 title: _t('Confirm'),
1544 {text: _t("Cancel"), click: function() {
1546 $(this).dialog("close");
1549 {text: _t("Ok"), click: function() {
1550 self.on_confirmed().then(function() {
1553 $(this).dialog("close");
1558 return def.promise();
1560 return self.on_confirmed();
1563 if (!this.node.attrs.special) {
1564 this.view.force_dirty = true;
1565 return this.view.recursive_save().pipe(exec_action);
1567 return exec_action();
1570 on_confirmed: function() {
1573 var context = this.node.attrs.context;
1574 if (context && context.__ref) {
1575 context = new instance.web.CompoundContext(context);
1576 context.set_eval_context(this._build_eval_context());
1579 return this.view.do_execute_action(
1580 _.extend({}, this.node.attrs, {context: context}),
1581 this.view.dataset, this.view.datarecord.id, function () {
1585 check_disable: function() {
1586 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1587 this.$element.prop('disabled', disabled);
1588 this.$element.css('color', disabled ? 'grey' : '');
1593 * Interface to be implemented by fields.
1596 * - readonly: boolean. If set to true the field should appear in readonly mode.
1597 * - force_readonly: boolean, When it is true, the field should always appear
1598 * in read only mode, no matter what the value of the "readonly" property can be.
1600 * - changed_value: triggered to inform the view to check on_changes
1603 instance.web.form.FieldMixin = {
1605 * Constructor takes 2 arguments:
1606 * - field_manager: Implements FieldManagerMixin
1607 * - node: the "<field>" node in json form
1609 init: function(field_manager, node) {},
1611 * Called by the form view to indicate the value of the field.
1613 * set_value() may return an object that can be passed to $.when() that represents the moment when
1614 * the field has finished all operations necessary before the user can effectively use the widget.
1616 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1617 * regardless of any asynchronous operation currently running and the status of any promise that a
1618 * previous call to set_value() could have returned.
1620 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1621 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1622 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1623 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1624 * no information is ever given to know which format is used.
1626 set_value: function(value_) {},
1628 * Get the current value of the widget.
1630 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1631 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1632 * For example if the field is marqued as "required", a call to get_value() can return false.
1634 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1635 * return a defaut value according to the type of field.
1637 * This method is always assumed to perform synchronously, it can not return a promise.
1639 * If there was no user interaction to modify the value of the field, it is always assumed that
1640 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1641 * altough the syntax can be different. This can be the case for type of fields that have a different
1642 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1644 get_value: function() {},
1646 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1649 set_input_id: function(id) {},
1651 * Returns true if is_syntax_valid() returns true and the value is semantically
1652 * valid too according to the semantic restrictions applied to the field.
1654 is_valid: function() {},
1656 * Returns true if the field holds a value which is syntaxically correct, ignoring
1657 * the potential semantic restrictions applied to the field.
1659 is_syntax_valid: function() {},
1661 * Must set the focus on the field.
1663 focus: function() {},
1667 * Abstract class for classes implementing FieldMixin.
1670 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1671 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1672 * - value: useful property to hold the value of the field. By default, set_value() and get_value()
1673 * set and retrieve the value property. Changing the value property also triggers automatically
1674 * a 'changed_value' event that inform the view to trigger on_changes.
1677 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1679 * @constructs instance.web.form.AbstractField
1680 * @extends instance.web.form.FormWidget
1682 * @param field_manager
1685 init: function(field_manager, node) {
1686 this._super(field_manager, node);
1687 this.field_manager = field_manager;
1688 this.name = this.node.attrs.name;
1689 this.set({'value': false});
1690 this.field = this.field_manager.get_field(this.name);
1691 this.set({required: this.modifiers['required'] === true});
1693 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1695 this.set({"readonly": this.modifiers['readonly'] === true});
1696 var test_effective_readonly = function() {
1697 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1699 this.on("change:readonly", this, test_effective_readonly);
1700 this.on("change:force_readonly", this, test_effective_readonly);
1701 _.bind(test_effective_readonly, this)();
1703 this.on("change:value", this, function() {
1704 if (! this._inhibit_on_change)
1705 this.trigger('changed_value');
1706 this._check_css_flags();
1709 renderElement: function() {
1711 if (this.field.translate) {
1712 this.$element.addClass('oe_form_field_translatable');
1713 this.$element.find('.oe_field_translate').click(_.bind(function() {
1714 this.field_manager.open_translate_dialog(this);
1717 if (instance.connection.debug) {
1718 this.do_attach_tooltip(this, this.view.$element.find('label[for=' + this.id_for_label + ']')[0] || this.$element);
1720 if (!this.disable_utility_classes) {
1721 this.off("change:required", this, this._set_required);
1722 this.on("change:required", this, this._set_required);
1723 this._set_required();
1727 * Private. Do not use.
1729 _set_required: function() {
1730 this.$element.toggleClass('oe_form_required', this.get("required"));
1732 set_value: function(value_) {
1733 this._inhibit_on_change = true;
1734 this.set({'value': value_});
1735 this._inhibit_on_change = false;
1737 get_value: function() {
1738 return this.get('value');
1740 is_valid: function() {
1741 return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1743 is_syntax_valid: function() {
1747 * Method useful to implement to ease validity testing. Must return true if the current
1748 * value is similar to false in OpenERP.
1750 is_false: function() {
1751 return this.get('value') === false;
1753 _check_css_flags: function(show_invalid) {
1754 if (this.field.translate) {
1755 this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1757 if (!this.disable_utility_classes) {
1758 if (this.field_manager.get('display_invalid_fields')) {
1759 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1766 * Utility method to focus an element, but only after a small amount of time.
1768 delay_focus: function($elem) {
1769 setTimeout(function() {
1774 * Utility method to get the widget options defined in the field xml description.
1776 get_definition_options: function() {
1777 if (!this.definition_options) {
1778 var str = this.node.attrs.options || '{}';
1779 this.definition_options = JSON.parse(str);
1781 return this.definition_options;
1783 set_input_id: function(id) {
1784 this.id_for_label = id;
1789 * A mixin to apply on any field that has to completely re-render when its readonly state
1792 instance.web.form.ReinitializeFieldMixin = {
1794 * Default implementation of start(), use it or call explicitly initialize_field().
1798 this.initialize_field();
1800 initialize_field: function() {
1801 this.on("change:effective_readonly", this, function() {
1802 this.destroy_content();
1803 this.renderElement();
1804 this.initialize_content();
1805 this.render_value();
1807 this.initialize_content();
1808 this.render_value();
1811 * Called to destroy anything that could have been created previously, called before a
1812 * re-initialization.
1814 destroy_content: function() {},
1816 * Called to initialize the content.
1818 initialize_content: function() {},
1820 * Called to render the value. Should also be explicitly called at the end of a set_value().
1822 render_value: function() {},
1825 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1826 template: 'FieldChar',
1827 init: function (field_manager, node) {
1828 this._super(field_manager, node);
1829 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1831 initialize_content: function() {
1833 this.$element.find('input').change(function() {
1834 self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1837 set_value: function(value_) {
1838 this._super(value_);
1839 this.render_value();
1841 render_value: function() {
1842 var show_value = instance.web.format_value(this.get('value'), this, '');
1843 if (!this.get("effective_readonly")) {
1844 this.$element.find('input').val(show_value);
1846 if (this.password) {
1847 show_value = new Array(show_value.length + 1).join('*');
1849 this.$element.text(show_value);
1852 is_syntax_valid: function() {
1853 if (!this.get("effective_readonly")) {
1855 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1863 is_false: function() {
1864 return this.get('value') === '';
1867 this.delay_focus(this.$element.find('input:first'));
1871 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1875 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1876 template: 'FieldEmail',
1877 initialize_content: function() {
1879 this.$element.find('button').click(this.on_button_clicked);
1881 render_value: function() {
1882 if (!this.get("effective_readonly")) {
1885 this.$element.find('a')
1886 .attr('href', 'mailto:' + this.get('value'))
1887 .text(this.get('value'));
1890 on_button_clicked: function() {
1891 if (!this.get('value') || !this.is_syntax_valid()) {
1892 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1894 location.href = 'mailto:' + this.get('value');
1899 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1900 template: 'FieldUrl',
1901 initialize_content: function() {
1903 this.$element.find('button').click(this.on_button_clicked);
1905 render_value: function() {
1906 if (!this.get("effective_readonly")) {
1909 var tmp = this.get('value');
1910 var s = /(\w+):(.+)/.exec(tmp);
1912 tmp = "http://" + this.get('value');
1914 this.$element.find('a').attr('href', tmp).text(tmp);
1917 on_button_clicked: function() {
1918 if (!this.get('value')) {
1919 this.do_warn("Resource error", "This resource is empty");
1921 var url = $.trim(this.get('value'));
1922 if(/^www\./i.test(url))
1923 url = 'http://'+url;
1929 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1930 is_field_number: true,
1931 init: function (field_manager, node) {
1932 this._super(field_manager, node);
1933 this.set({'value': 0});
1934 if (this.node.attrs.digits) {
1935 this.digits = py.eval(node.attrs.digits);
1937 this.digits = this.field.digits;
1940 set_value: function(value_) {
1941 if (value_ === false || value_ === undefined) {
1942 // As in GTK client, floats default to 0
1945 this._super.apply(this, [value_]);
1949 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
1950 template: "web.datetimepicker",
1951 jqueryui_object: 'datetimepicker',
1952 type_of_date: "datetime",
1953 init: function(parent) {
1954 this._super(parent);
1955 this.name = parent.name;
1959 this.$input = this.$element.find('input.oe_datepicker_master');
1960 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1961 this.$input.change(this.on_change);
1963 onSelect: this.on_picker_select,
1967 showButtonPanel: true
1969 this.$element.find('img.oe_datepicker_trigger').click(function() {
1970 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1971 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
1972 self.$input_picker.show();
1973 self.picker('show');
1974 self.$input_picker.hide();
1977 this.set_readonly(false);
1978 this.set({'value': false});
1980 picker: function() {
1981 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1983 on_picker_select: function(text, instance_) {
1984 var date = this.picker('getDate');
1985 this.$input.val(date ? this.format_client(date) : '').change();
1987 set_value: function(value_) {
1988 this.set({'value': value_});
1989 this.$input.val(value_ ? this.format_client(value_) : '');
1991 get_value: function() {
1992 return this.get('value');
1994 set_value_from_ui_: function() {
1995 var value_ = this.$input.val() || false;
1996 this.set({'value': this.parse_client(value_)});
1998 set_readonly: function(readonly) {
1999 this.readonly = readonly;
2000 this.$input.prop('readonly', this.readonly);
2001 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2003 is_valid_: function() {
2004 var value_ = this.$input.val();
2005 if (value_ === "") {
2009 this.parse_client(value_);
2016 parse_client: function(v) {
2017 return instance.web.parse_value(v, {"widget": this.type_of_date});
2019 format_client: function(v) {
2020 return instance.web.format_value(v, {"widget": this.type_of_date});
2022 on_change: function() {
2023 if (this.is_valid_()) {
2024 this.set_value_from_ui_();
2029 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2030 jqueryui_object: 'datepicker',
2031 type_of_date: "date"
2034 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2035 template: "EmptyComponent",
2036 build_widget: function() {
2037 return new instance.web.DateTimeWidget(this);
2039 destroy_content: function() {
2040 if (this.datewidget) {
2041 this.datewidget.destroy();
2042 this.datewidget = undefined;
2045 initialize_content: function() {
2046 if (!this.get("effective_readonly")) {
2047 this.datewidget = this.build_widget();
2048 this.datewidget.on_change.add_last(_.bind(function() {
2049 this.set({'value': this.datewidget.get_value()});
2051 this.datewidget.appendTo(this.$element);
2054 set_value: function(value_) {
2055 this._super(value_);
2056 this.render_value();
2058 render_value: function() {
2059 if (!this.get("effective_readonly")) {
2060 this.datewidget.set_value(this.get('value'));
2062 this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2065 is_syntax_valid: function() {
2066 if (!this.get("effective_readonly")) {
2067 return this.datewidget.is_valid_();
2071 is_false: function() {
2072 return this.get('value') === '';
2075 if (this.datewidget && this.datewidget.$input)
2076 this.delay_focus(this.datewidget.$input);
2080 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2081 build_widget: function() {
2082 return new instance.web.DateWidget(this);
2086 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2087 template: 'FieldText',
2088 initialize_content: function() {
2089 this.$textarea = this.$element.find('textarea');
2090 if (!this.get("effective_readonly")) {
2091 this.$textarea.change(_.bind(function() {
2092 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2095 this.$textarea.attr('disabled', 'disabled');
2098 set_value: function(value_) {
2099 this._super.apply(this, arguments);
2100 this.render_value();
2102 render_value: function() {
2103 var show_value = instance.web.format_value(this.get('value'), this, '');
2104 this.$textarea.val(show_value);
2105 if (show_value && this.view.options.resize_textareas) {
2106 this.do_resize(this.view.options.resize_textareas);
2109 is_syntax_valid: function() {
2110 if (!this.get("effective_readonly")) {
2112 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2120 is_false: function() {
2121 return this.get('value') === '';
2123 focus: function($element) {
2124 this.delay_focus(this.$textarea);
2126 do_resize: function(max_height) {
2127 max_height = parseInt(max_height, 10);
2128 var $input = this.$textarea,
2129 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2131 $div.text($input.val());
2132 _.each('font-family,font-size,white-space'.split(','), function(style) {
2133 $div.css(style, $input.css(style));
2135 $div.appendTo($('body'));
2136 new_height = $div.height();
2137 if (new_height < 90) {
2140 if (!isNaN(max_height) && new_height > max_height) {
2141 new_height = max_height;
2144 $input.height(new_height);
2148 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2149 template: 'FieldBoolean',
2151 this._super.apply(this, arguments);
2152 this.$checkbox = $("input", this.$element);
2153 this.$element.click(_.bind(function() {
2154 this.set({'value': this.$checkbox.is(':checked')});
2156 var check_readonly = function() {
2157 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2159 this.on("change:effective_readonly", this, check_readonly);
2160 _.bind(check_readonly, this)();
2162 set_value: function(value_) {
2163 this._super.apply(this, arguments);
2164 this.$checkbox[0].checked = value_;
2167 this.delay_focus(this.$checkbox);
2171 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2172 template: 'FieldProgressBar',
2174 this._super.apply(this, arguments);
2175 this.$element.progressbar({
2176 value: this.get('value'),
2177 disabled: this.get("effective_readonly")
2180 set_value: function(value_) {
2181 this._super.apply(this, arguments);
2182 var show_value = Number(value_);
2183 if (isNaN(show_value)) {
2186 var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2187 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2191 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2192 // to replace view editor
2195 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2196 template: 'FieldSelection',
2197 init: function(field_manager, node) {
2199 this._super(field_manager, node);
2200 this.values = _.clone(this.field.selection);
2201 _.each(this.values, function(v, i) {
2202 if (v[0] === false && v[1] === '') {
2203 self.values.splice(i, 1);
2206 this.values.unshift([false, '']);
2208 initialize_content: function() {
2209 // Flag indicating whether we're in an event chain containing a change
2210 // event on the select, in order to know what to do on keyup[RETURN]:
2211 // * If the user presses [RETURN] as part of changing the value of a
2212 // selection, we should just let the value change and not let the
2213 // event broadcast further (e.g. to validating the current state of
2214 // the form in editable list view, which would lead to saving the
2215 // current row or switching to the next one)
2216 // * If the user presses [RETURN] with a select closed (side-effect:
2217 // also if the user opened the select and pressed [RETURN] without
2218 // changing the selected value), takes the action as validating the
2220 var ischanging = false;
2221 this.$element.find('select')
2222 .change(_.bind(function() {
2223 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2225 .change(function () { ischanging = true; })
2226 .click(function () { ischanging = false; })
2227 .keyup(function (e) {
2228 if (e.which !== 13 || !ischanging) { return; }
2229 e.stopPropagation();
2233 set_value: function(value_) {
2234 value_ = value_ === null ? false : value_;
2235 value_ = value_ instanceof Array ? value_[0] : value_;
2236 this._super(value_);
2237 this.render_value();
2239 render_value: function() {
2240 if (!this.get("effective_readonly")) {
2242 for (var i = 0, ii = this.values.length; i < ii; i++) {
2243 if (this.values[i][0] === this.get('value')) index = i;
2245 this.$element.find('select')[0].selectedIndex = index;
2248 var option = _(this.values)
2249 .detect(function (record) { return record[0] === self.get('value'); });
2250 this.$element.text(option ? option[1] : this.values[0][1]);
2253 is_syntax_valid: function() {
2254 if (this.get("effective_readonly")) {
2257 var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2261 this.delay_focus(this.$element.find('select:first'));
2265 // jquery autocomplete tweak to allow html
2267 var proto = $.ui.autocomplete.prototype,
2268 initSource = proto._initSource;
2270 function filter( array, term ) {
2271 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2272 return $.grep( array, function(value_) {
2273 return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2278 _initSource: function() {
2279 if ( this.options.html && $.isArray(this.options.source) ) {
2280 this.source = function( request, response ) {
2281 response( filter( this.options.source, request.term ) );
2284 initSource.call( this );
2288 _renderItem: function( ul, item) {
2289 return $( "<li></li>" )
2290 .data( "item.autocomplete", item )
2291 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2297 instance.web.form.dialog = function(content, options) {
2298 options = _.extend({
2303 var dialog = new instance.web.Dialog(null, options, content).open();
2304 return dialog.$element;
2308 * A mixin containing some useful methods to handle completion inputs.
2310 instance.web.form.CompletionFieldMixin = {
2313 this.orderer = new instance.web.DropMisordered();
2316 * Call this method to search using a string.
2318 get_search_result: function(search_val) {
2321 var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2323 return this.orderer.add(dataset.name_search(
2324 search_val, self.build_domain(), 'ilike', this.limit + 1)).pipe(function(data) {
2325 self.last_search = data;
2326 // possible selections for the m2o
2327 var values = _.map(data, function(x) {
2329 label: _.str.escapeHTML(x[1]),
2336 // search more... if more results that max
2337 if (values.length > self.limit) {
2338 values = values.slice(0, self.limit);
2339 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2340 dataset.name_search(search_val, self.build_domain(), 'ilike'
2341 , false, function(data) {
2342 self._search_create_popup("search", data);
2347 var raw_result = _(data.result).map(function(x) {return x[1];});
2348 if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2349 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2350 $('<span />').text(search_val).html()), action: function() {
2351 self._quick_create(search_val);
2355 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2356 self._search_create_popup("form", undefined, {"default_name": search_val});
2362 _quick_create: function(name) {
2364 var slow_create = function () {
2365 self._search_create_popup("form", undefined, {"default_name": name});
2367 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2368 new instance.web.DataSet(this, this.field.relation, self.build_context())
2369 .name_create(name, function(data) {
2370 self.add_id(data[0]);
2371 }).fail(function(error, event) {
2372 event.preventDefault();
2378 // all search/create popup handling
2379 _search_create_popup: function(view, ids, context) {
2381 var pop = new instance.web.form.SelectCreatePopup(this);
2383 self.field.relation,
2385 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2386 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2388 disable_multiple_selection: true
2390 self.build_domain(),
2391 new instance.web.CompoundContext(self.build_context(), context || {})
2393 pop.on_select_elements.add(function(element_ids) {
2394 self.add_id(element_ids[0]);
2400 add_id: function(id) {},
2403 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2404 instance.web.form.CompletionFieldMixin, {
2405 template: "FieldMany2One",
2406 init: function(field_manager, node) {
2407 this._super(field_manager, node);
2408 instance.web.form.CompletionFieldMixin.init.call(this);
2409 this.set({'value': false});
2410 this.display_value = {};
2411 this.last_search = [];
2412 this.floating = false;
2413 this.inhibit_on_change = false;
2417 instance.web.form.ReinitializeFieldMixin.start.call(this);
2418 this.on("change:value", this, function() {
2419 this.floating = false;
2420 this.render_value();
2423 initialize_content: function() {
2424 if (!this.get("effective_readonly"))
2425 this.render_editable();
2426 this.render_value();
2428 render_editable: function() {
2430 this.$input = this.$element.find("input");
2434 return "No element was selected, you should create or select one from the dropdown list.";
2440 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2441 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2443 this.$follow_button.click(function() {
2444 if (!self.get('value')) {
2447 var pop = new instance.web.form.FormOpenPopup(self.view);
2449 self.field.relation,
2451 self.build_context(),
2453 title: _t("Open: ") + (self.string || self.name)
2456 pop.on_write_completed.add_last(function() {
2457 self.display_value = {};
2458 self.render_value();
2462 // some behavior for input
2463 this.$input.keyup(function() {
2464 if (self.$input.val() === "") {
2465 self.set({value: false});
2467 self.floating = true;
2470 this.$drop_down.click(function() {
2471 if (self.$input.autocomplete("widget").is(":visible")) {
2472 self.$input.autocomplete("close");
2474 if (self.get("value") && ! self.floating) {
2475 self.$input.autocomplete("search", "");
2477 self.$input.autocomplete("search");
2479 self.$input.focus();
2482 var tip_def = $.Deferred();
2483 var untip_def = $.Deferred();
2484 var tip_delay = 200;
2485 var tip_duration = 3000;
2486 var anyoneLoosesFocus = function() {
2487 if (self.floating) {
2488 if (self.last_search.length > 0) {
2489 if (self.last_search[0][0] != self.get("value")) {
2490 self.display_value = {};
2491 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2492 self.set({value: self.last_search[0][0]});
2494 self.render_value();
2497 self.set({value: false});
2500 if (! self.get("value")) {
2503 tip_def = $.Deferred();
2504 tip_def.then(function() {
2505 self.$input.tipsy("show");
2507 setTimeout(function() {
2510 untip_def = $.Deferred();
2511 untip_def.then(function() {
2512 self.$input.tipsy("hide");
2514 setTimeout(function() {untip_def.resolve();}, tip_duration);
2520 this.$input.focusout(anyoneLoosesFocus);
2522 var isSelecting = false;
2524 this.$input.autocomplete({
2525 source: function(req, resp) {
2526 self.get_search_result(req.term).then(function(result) {
2530 select: function(event, ui) {
2534 self.display_value = {};
2535 self.display_value["" + item.id] = item.name;
2536 self.set({value: item.id});
2537 } else if (item.action) {
2538 self.floating = true;
2543 focus: function(e, ui) {
2547 close: anyoneLoosesFocus,
2551 this.$input.autocomplete("widget").addClass("openerp");
2552 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2553 this.$input.keyup(function(e) {
2554 if (e.which === 13) {
2556 e.stopPropagation();
2558 isSelecting = false;
2562 render_value: function(no_recurse) {
2564 if (! this.get("value")) {
2565 this.display_string("");
2568 var display = this.display_value["" + this.get("value")];
2570 this.display_string(display);
2574 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2575 dataset.name_get([self.get("value")], function(data) {
2576 self.display_value["" + self.get("value")] = data[0][1];
2577 self.render_value(true);
2581 display_string: function(str) {
2583 if (!this.get("effective_readonly")) {
2584 this.$input.val(str);
2586 this.$element.find('a')
2589 .click(function () {
2591 type: 'ir.actions.act_window',
2592 res_model: self.field.relation,
2593 res_id: self.get("value"),
2594 context: self.build_context(),
2595 views: [[false, 'form']],
2602 set_value: function(value_) {
2604 if (value_ instanceof Array) {
2605 this.display_value = {};
2606 this.display_value["" + value_[0]] = value_[1];
2609 value_ = value_ || false;
2610 this.inhibit_on_change = true;
2611 this._super(value_);
2612 this.inhibit_on_change = false;
2614 add_id: function(id) {
2615 this.display_value = {};
2616 this.set({value: id});
2618 is_false: function() {
2619 return ! this.get("value");
2621 focus: function () {
2622 this.delay_focus(this.$input);
2627 # Values: (0, 0, { fields }) create
2628 # (1, ID, { fields }) update
2629 # (2, ID) remove (delete)
2630 # (3, ID) unlink one (target id or target of relation)
2632 # (5) unlink all (only valid for one2many)
2637 'create': function (values) {
2638 return [commands.CREATE, false, values];
2640 // (1, id, {values})
2642 'update': function (id, values) {
2643 return [commands.UPDATE, id, values];
2647 'delete': function (id) {
2648 return [commands.DELETE, id, false];
2650 // (3, id[, _]) removes relation, but not linked record itself
2652 'forget': function (id) {
2653 return [commands.FORGET, id, false];
2657 'link_to': function (id) {
2658 return [commands.LINK_TO, id, false];
2662 'delete_all': function () {
2663 return [5, false, false];
2665 // (6, _, ids) replaces all linked records with provided ids
2667 'replace_with': function (ids) {
2668 return [6, false, ids];
2671 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2672 multi_selection: false,
2673 disable_utility_classes: true,
2674 init: function(field_manager, node) {
2675 this._super(field_manager, node);
2676 lazy_build_o2m_kanban_view();
2677 this.is_loaded = $.Deferred();
2678 this.initial_is_loaded = this.is_loaded;
2679 this.is_setted = $.Deferred();
2680 this.form_last_update = $.Deferred();
2681 this.init_form_last_update = this.form_last_update;
2684 this._super.apply(this, arguments);
2688 this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2689 this.dataset.o2m = this;
2690 this.dataset.parent_view = this.view;
2691 this.dataset.child_name = this.name;
2692 //this.dataset.child_name =
2693 this.dataset.on_change.add_last(function() {
2694 self.trigger_on_change();
2697 this.is_setted.then(function() {
2700 this.is_loaded.then(function() {
2701 self.on("change:effective_readonly", self, function() {
2702 self.is_loaded = self.is_loaded.pipe(function() {
2703 self.viewmanager.destroy();
2704 return $.when(self.load_views()).then(function() {
2705 self.reload_current_view();
2711 trigger_on_change: function() {
2712 var tmp = this.doing_on_change;
2713 this.doing_on_change = true;
2714 this.trigger('changed_value');
2715 this.doing_on_change = tmp;
2717 load_views: function() {
2720 var modes = this.node.attrs.mode;
2721 modes = !!modes ? modes.split(",") : ["tree"];
2723 _.each(modes, function(mode) {
2726 view_type: mode == "tree" ? "list" : mode,
2729 if (self.field.views && self.field.views[mode]) {
2730 view.embedded_view = self.field.views[mode];
2732 if(view.view_type === "list") {
2733 view.options.selectable = self.multi_selection;
2734 if (self.get("effective_readonly")) {
2735 view.options.addable = null;
2736 view.options.deletable = null;
2737 view.options.isClarkGable = false;
2739 } else if (view.view_type === "form") {
2740 if (self.get("effective_readonly")) {
2741 view.view_type = 'form';
2743 view.options.not_interactible_on_create = true;
2749 this.viewmanager = new instance.web.ViewManager(this, this.dataset, views, {
2752 this.viewmanager.template = 'One2Many.viewmanager';
2753 this.viewmanager.registry = instance.web.views.extend({
2754 list: 'instance.web.form.One2ManyListView',
2755 form: 'instance.web.form.One2ManyFormView',
2756 kanban: 'instance.web.form.One2ManyKanbanView',
2758 var once = $.Deferred().then(function() {
2759 self.init_form_last_update.resolve();
2761 var def = $.Deferred().then(function() {
2762 self.initial_is_loaded.resolve();
2764 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2765 controller.o2m = self;
2766 if (view_type == "list") {
2767 if (self.get("effective_readonly"))
2768 controller.set_editable(false);
2769 } else if (view_type === "form") {
2770 if (self.get("effective_readonly")) {
2771 $(".oe_form_buttons", controller.$element).children().remove();
2773 controller.on_record_loaded.add_last(function() {
2776 controller.on_pager_action.add_first(function() {
2777 self.save_any_view();
2779 } else if (view_type == "graph") {
2780 self.reload_current_view()
2784 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2785 $.when(self.save_any_view()).then(function() {
2786 if(n_mode === "list")
2787 $.async_when().then(function() {self.reload_current_view();});
2790 this.is_setted.then(function() {
2791 $.async_when().then(function () {
2792 self.viewmanager.appendTo(self.$element);
2797 reload_current_view: function() {
2799 return self.is_loaded = self.is_loaded.pipe(function() {
2800 var active_view = self.viewmanager.active_view;
2801 var view = self.viewmanager.views[active_view].controller;
2802 if(active_view === "list") {
2803 return view.reload_content();
2804 } else if (active_view === "form") {
2805 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2806 self.dataset.index = 0;
2808 var act = function() {
2809 return view.do_show();
2811 self.form_last_update = self.form_last_update.pipe(act, act);
2812 return self.form_last_update;
2813 } else if (view.do_search) {
2814 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2818 set_value: function(value_) {
2819 value_ = value_ || [];
2821 this.dataset.reset_ids([]);
2822 if(value_.length >= 1 && value_[0] instanceof Array) {
2824 _.each(value_, function(command) {
2825 var obj = {values: command[2]};
2826 switch (command[0]) {
2827 case commands.CREATE:
2828 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2830 self.dataset.to_create.push(obj);
2831 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2834 case commands.UPDATE:
2835 obj['id'] = command[1];
2836 self.dataset.to_write.push(obj);
2837 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2840 case commands.DELETE:
2841 self.dataset.to_delete.push({id: command[1]});
2843 case commands.LINK_TO:
2844 ids.push(command[1]);
2846 case commands.DELETE_ALL:
2847 self.dataset.delete_all = true;
2852 this.dataset.set_ids(ids);
2853 } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2855 this.dataset.delete_all = true;
2856 _.each(value_, function(command) {
2857 var obj = {values: command};
2858 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2860 self.dataset.to_create.push(obj);
2861 self.dataset.cache.push(_.clone(obj));
2865 this.dataset.set_ids(ids);
2867 this._super(value_);
2868 this.dataset.reset_ids(value_);
2870 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2871 this.dataset.index = 0;
2873 self.is_setted.resolve();
2874 return self.reload_current_view();
2876 get_value: function() {
2880 this.save_any_view();
2881 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2882 val = val.concat(_.map(this.dataset.ids, function(id) {
2883 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2885 return commands.create(alter_order.values);
2887 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2889 return commands.update(alter_order.id, alter_order.values);
2891 return commands.link_to(id);
2893 return val.concat(_.map(
2894 this.dataset.to_delete, function(x) {
2895 return commands['delete'](x.id);}));
2897 save_any_view: function() {
2898 if (this.doing_on_change)
2900 return this.session.synchronized_mode(_.bind(function() {
2901 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2902 this.viewmanager.views[this.viewmanager.active_view] &&
2903 this.viewmanager.views[this.viewmanager.active_view].controller) {
2904 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2905 if (this.viewmanager.active_view === "form") {
2906 if (!view.is_initialized.isResolved()) {
2909 var res = $.when(view.do_save());
2910 if (!res.isResolved() && !res.isRejected()) {
2911 console.warn("Asynchronous get_value() is not supported in form view.");
2914 } else if (this.viewmanager.active_view === "list") {
2915 var res = $.when(view.ensure_saved());
2916 if (!res.isResolved() && !res.isRejected()) {
2917 console.warn("Asynchronous get_value() is not supported in list view.");
2925 is_syntax_valid: function() {
2926 if (!this.viewmanager.views[this.viewmanager.active_view])
2928 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2929 if (this.viewmanager.active_view === "form") {
2930 for (var f in view.fields) {
2932 if (!f.is_valid()) {
2941 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
2942 get_context: function() {
2943 this.context = this.o2m.build_context([this.o2m.name]);
2944 return this.context;
2948 instance.web.form.One2ManyListView = instance.web.ListView.extend({
2949 _template: 'One2Many.listview',
2950 do_add_record: function () {
2951 if (this.options.editable) {
2952 this._super.apply(this, arguments);
2955 var pop = new instance.web.form.SelectCreatePopup(this);
2956 pop.on_default_get.add(self.dataset.on_default_get);
2958 self.o2m.field.relation,
2960 title: _t("Create: ") + self.name,
2961 initial_view: "form",
2962 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2963 create_function: function(data, callback, error_callback) {
2964 return self.o2m.dataset.create(data).then(function(r) {
2965 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2966 self.o2m.dataset.on_change();
2967 }).then(callback, error_callback);
2969 read_function: function() {
2970 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2972 parent_view: self.o2m.view,
2973 child_name: self.o2m.name,
2974 form_view_options: {'not_interactible_on_create':true}
2976 self.o2m.build_domain(),
2977 self.o2m.build_context()
2979 pop.on_select_elements.add_last(function() {
2980 self.o2m.reload_current_view();
2984 do_activate_record: function(index, id) {
2986 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
2987 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2988 title: _t("Open: ") + self.name,
2990 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2991 parent_view: self.o2m.view,
2992 child_name: self.o2m.name,
2993 read_function: function() {
2994 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2996 form_view_options: {'not_interactible_on_create':true},
2997 readonly: self.o2m.get("effective_readonly")
2999 pop.on_write.add(function(id, data) {
3000 self.o2m.dataset.write(id, data, {}, function(r) {
3001 self.o2m.reload_current_view();
3005 do_button_action: function (name, id, callback) {
3007 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3008 return this._super(name, id, _.bind(def.resolve, def));
3012 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3013 form_template: 'One2Many.formview',
3014 on_loaded: function(data) {
3017 this.$buttons.find('button.oe_form_button_create').click(function() {
3018 self.do_save().then(self.on_button_new);
3021 do_notify_change: function() {
3022 if (this.dataset.parent_view) {
3023 this.dataset.parent_view.do_notify_change();
3025 this._super.apply(this, arguments);
3030 var lazy_build_o2m_kanban_view = function() {
3031 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3033 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3034 open_record: function(id) {
3036 var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3037 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3038 title: _t("Open: ") + self.name,
3040 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3041 parent_view: self.o2m.view,
3042 child_name: self.o2m.name,
3043 read_function: function() {
3044 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3046 form_view_options: {'not_interactible_on_create':true},
3047 readonly: self.o2m.get("effective_readonly"),
3049 pop.on_write.add(function(id, data) {
3050 self.o2m.dataset.write(id, data, {}, function(r) {
3051 self.o2m.reload_current_view();
3059 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3060 instance.web.form.ReinitializeFieldMixin, {
3061 template: "FieldMany2ManyTags",
3063 this._super.apply(this, arguments);
3064 instance.web.form.CompletionFieldMixin.init.call(this);
3065 this.set({"value": []});
3066 this._display_orderer = new instance.web.DropMisordered();
3067 this._drop_shown = false;
3071 instance.web.form.ReinitializeFieldMixin.start.call(this);
3072 this.on("change:value", this, this.render_value);
3074 initialize_content: function() {
3075 if (this.get("effective_readonly"))
3078 self. $text = $("textarea", this.$element);
3079 self.$text.textext({
3080 plugins : 'tags arrow autocomplete',
3082 render: function(suggestion) {
3083 return $('<span class="text-label"/>').
3084 data('index', suggestion['index']).html(suggestion['label']);
3089 selectFromDropdown: function() {
3090 $(this).trigger('hideDropdown');
3091 var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3092 var data = self.search_result[index];
3094 self.add_id(data.id);
3101 isTagAllowed: function(tag) {
3106 removeTag: function(tag) {
3107 var id = tag.data("id");
3108 self.set({"value": _.without(self.get("value"), id)});
3110 renderTag: function(stuff) {
3111 return $.fn.textext.TextExtTags.prototype.renderTag.
3112 call(this, stuff).data("id", stuff.id);
3116 itemToString: function(item) {
3121 }).bind('getSuggestions', function(e, data) {
3123 var str = !!data ? data.query || '' : '';
3124 self.get_search_result(str).then(function(result) {
3125 self.search_result = result;
3126 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3127 return _.extend(el, {index:i});
3130 }).bind('tagClick', function(e, tag, value, callback) {
3131 var pop = new instance.web.form.FormOpenPopup(self.view);
3133 self.field.relation,
3135 self.build_context(),
3137 title: _t("Open: ") + (self.string || self.name)
3140 pop.on_write_completed.add_last(function() {
3141 self.render_value();
3143 }).bind('hideDropdown', function() {
3144 self._drop_shown = false;
3145 }).bind('hideDropdown', function() {
3146 self._drop_shown = true;
3148 self.tags = self.$text.textext()[0].tags();
3149 $("textarea", this.$element).focusout(function() {
3150 $("textarea", this.$element).val("");
3151 }).keydown(function(e) {
3152 if (event.keyCode === 9 && self._drop_shown) {
3153 self.$text.textext()[0].autocomplete().selectFromDropdown();
3157 set_value: function(value_) {
3158 value_ = value_ || [];
3159 if (value_.length >= 1 && value_[0] instanceof Array) {
3160 value_ = value_[0][2];
3162 this._super(value_);
3164 get_value: function() {
3165 var tmp = [commands.replace_with(this.get("value"))];
3168 render_value: function() {
3170 var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3171 var handle_names = function(data) {
3173 _.each(data, function(el) {
3174 indexed[el[0]] = el;
3176 data = _.map(self.get("value"), function(el) { return indexed[el]; });
3177 if (! self.get("effective_readonly")) {
3178 self.tags.containerElement().children().remove();
3179 $("textarea", self.$element).css("padding-left", "3px");
3180 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3182 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3183 $(".oe_form_field_many2manytags_box", self.$element).click(function() {
3184 var index = Number($(this).data("index"));
3186 type: 'ir.actions.act_window',
3187 res_model: self.field.relation,
3188 res_id: self.get("value")[index],
3189 context: self.build_context(),
3190 views: [[false, 'form']],
3196 if (! self.get('values') || self.get('values').length > 0) {
3197 this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3202 add_id: function(id) {
3203 this.set({'value': _.uniq(this.get('value').concat([id]))});
3208 * TODO niv: clean those deferred stuff, it could be better
3210 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3211 multi_selection: false,
3212 disable_utility_classes: true,
3213 init: function(field_manager, node) {
3214 this._super(field_manager, node);
3215 this.is_loaded = $.Deferred();
3216 this.initial_is_loaded = this.is_loaded;
3217 this.is_setted = $.Deferred();
3220 this._super.apply(this, arguments);
3224 this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3225 this.dataset.m2m = this;
3226 this.dataset.on_unlink.add_last(function(ids) {
3227 self.dataset_changed();
3230 this.is_setted.then(function() {
3233 this.is_loaded.then(function() {
3234 self.on("change:effective_readonly", self, function() {
3235 self.is_loaded = self.is_loaded.pipe(function() {
3236 self.list_view.destroy();
3237 return $.when(self.load_view()).then(function() {
3238 self.reload_content();
3244 set_value: function(value_) {
3245 value_ = value_ || [];
3246 if (value_.length >= 1 && value_[0] instanceof Array) {
3247 value_ = value_[0][2];
3249 this._super(value_);
3250 this.dataset.set_ids(value_);
3252 self.reload_content();
3253 this.is_setted.resolve();
3255 load_view: function() {
3257 this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3258 'addable': self.get("effective_readonly") ? null : _t("Add"),
3259 'deletable': self.get("effective_readonly") ? false : true,
3260 'selectable': self.multi_selection,
3261 'isClarkGable': self.get("effective_readonly") ? false : true
3263 var embedded = (this.field.views || {}).tree;
3265 this.list_view.set_embedded_view(embedded);
3267 this.list_view.m2m_field = this;
3268 var loaded = $.Deferred();
3269 this.list_view.on_loaded.add_last(function() {
3270 self.initial_is_loaded.resolve();
3273 $.async_when().then(function () {
3274 self.list_view.appendTo(self.$element);
3278 reload_content: function() {
3280 this.is_loaded = this.is_loaded.pipe(function() {
3281 return self.list_view.reload_content();
3284 dataset_changed: function() {
3285 this.set({'value': [commands.replace_with(this.dataset.ids)]});
3289 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3290 get_context: function() {
3291 this.context = this.m2m.build_context();
3292 return this.context;
3298 * @extends instance.web.ListView
3300 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3301 do_add_record: function () {
3302 var pop = new instance.web.form.SelectCreatePopup(this);
3306 title: _t("Add: ") + this.name
3308 new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3309 this.m2m_field.build_context()
3312 pop.on_select_elements.add(function(element_ids) {
3313 _.each(element_ids, function(one_id) {
3314 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3315 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3316 self.m2m_field.dataset_changed();
3317 self.reload_content();
3322 do_activate_record: function(index, id) {
3324 var pop = new instance.web.form.FormOpenPopup(this);
3325 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3326 title: _t("Open: ") + this.name,
3327 readonly: this.getParent().get("effective_readonly")
3329 pop.on_write_completed.add_last(function() {
3330 self.reload_content();
3337 * @extends instance.web.OldWidget
3339 instance.web.form.SelectCreatePopup = instance.web.OldWidget.extend(/** @lends instance.web.form.SelectCreatePopup# */{
3340 template: "SelectCreatePopup",
3344 * - initial_view: form or search (default search)
3345 * - disable_multiple_selection
3346 * - alternative_form_view
3347 * - create_function (defaults to a naive saving behavior)
3350 * - form_view_options
3351 * - list_view_options
3354 select_element: function(model, options, domain, context) {
3357 this.domain = domain || [];
3358 this.context = context || {};
3359 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
3360 return self.create_row.apply(self, arguments);
3361 }, read_function: null});
3362 this.initial_ids = this.options.initial_ids;
3363 this.created_elements = [];
3364 this.renderElement();
3365 instance.web.form.dialog(this.$element, {
3369 title: options.title || ""
3376 this.dataset = new instance.web.ProxyDataSet(this, this.model,
3378 this.dataset.create_function = function() {
3379 return self.options.create_function.apply(null, arguments).then(function(r) {
3380 self.created_elements.push(r.result);
3383 this.dataset.write_function = function() {
3384 return self.write_row.apply(self, arguments);
3386 this.dataset.read_function = this.options.read_function;
3387 this.dataset.parent_view = this.options.parent_view;
3388 this.dataset.child_name = this.options.child_name;
3389 this.dataset.on_default_get.add(this.on_default_get);
3390 if (this.options.initial_view == "search") {
3391 self.rpc('/web/session/eval_domain_and_context', {
3393 contexts: [this.context]
3394 }, function (results) {
3395 var search_defaults = {};
3396 _.each(results.context, function (value_, key) {
3397 var match = /^search_default_(.*)$/.exec(key);
3399 search_defaults[match[1]] = value_;
3402 self.setup_search_view(search_defaults);
3409 this.$element.dialog('close');
3412 setup_search_view: function(search_defaults) {
3414 if (this.searchview) {
3415 this.searchview.destroy();
3417 this.searchview = new instance.web.SearchView(this,
3418 this.dataset, false, search_defaults);
3419 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3420 if (self.initial_ids) {
3421 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3422 contexts, groupbys);
3423 self.initial_ids = undefined;
3425 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3428 this.searchview.on_loaded.add_last(function () {
3429 self.view_list = new instance.web.form.SelectCreateListView(self,
3430 self.dataset, false,
3431 _.extend({'deletable': false,
3432 'selectable': !self.options.disable_multiple_selection
3433 }, self.options.list_view_options || {}));
3434 self.view_list.popup = self;
3435 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3436 self.view_list.do_show();
3437 }).pipe(function() {
3438 self.searchview.do_search();
3440 self.view_list.on_loaded.add_last(function() {
3441 var $buttons = self.view_list.$element.find(".oe-actions");
3442 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3443 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3444 $cbutton.click(function() {
3447 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3448 if(self.options.disable_multiple_selection) {
3451 $sbutton.click(function() {
3452 self.on_select_elements(self.selected_ids);
3457 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3459 do_search: function(domains, contexts, groupbys) {
3461 this.rpc('/web/session/eval_domain_and_context', {
3462 domains: domains || [],
3463 contexts: contexts || [],
3464 group_by_seq: groupbys || []
3465 }, function (results) {
3466 self.view_list.do_search(results.domain, results.context, results.group_by);
3469 create_row: function() {
3471 var wdataset = new instance.web.DataSetSearch(this, this.model, this.context, this.domain);
3472 wdataset.parent_view = this.options.parent_view;
3473 wdataset.child_name = this.options.child_name;
3474 return wdataset.create.apply(wdataset, arguments);
3476 write_row: function() {
3478 var wdataset = new instance.web.DataSetSearch(this, this.model, this.context, this.domain);
3479 wdataset.parent_view = this.options.parent_view;
3480 wdataset.child_name = this.options.child_name;
3481 return wdataset.write.apply(wdataset, arguments);
3483 on_select_elements: function(element_ids) {
3485 on_click_element: function(ids) {
3486 this.selected_ids = ids || [];
3487 if(this.selected_ids.length > 0) {
3488 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3490 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3493 new_object: function() {
3495 if (this.searchview) {
3496 this.searchview.hide();
3498 if (this.view_list) {
3499 this.view_list.$element.hide();
3501 this.dataset.index = null;
3502 this.view_form = new instance.web.FormView(this, this.dataset, false, self.options.form_view_options);
3503 if (this.options.alternative_form_view) {
3504 this.view_form.set_embedded_view(this.options.alternative_form_view);
3506 this.view_form.appendTo(this.$element.find(".oe-select-create-popup-view-form"));
3507 this.view_form.on_loaded.add_last(function() {
3508 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3509 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
3510 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
3511 $nbutton.click(function() {
3512 $.when(self.view_form.do_save()).then(function() {
3513 self.view_form.reload_mutex.exec(function() {
3514 self.view_form.on_button_new();
3518 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
3519 $nbutton.click(function() {
3520 $.when(self.view_form.do_save()).then(function() {
3521 self.view_form.reload_mutex.exec(function() {
3526 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
3527 $cbutton.click(function() {
3531 this.view_form.do_show();
3533 check_exit: function() {
3534 if (this.created_elements.length > 0) {
3535 this.on_select_elements(this.created_elements);
3539 on_default_get: function(res) {}
3542 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3543 do_add_record: function () {
3544 this.popup.new_object();
3546 select_record: function(index) {
3547 this.popup.on_select_elements([this.dataset.ids[index]]);
3548 this.popup.destroy();
3550 do_select: function(ids, records) {
3551 this._super(ids, records);
3552 this.popup.on_click_element(ids);
3558 * @extends instance.web.OldWidget
3560 instance.web.form.FormOpenPopup = instance.web.OldWidget.extend(/** @lends instance.web.form.FormOpenPopup# */{
3561 template: "FormOpenPopup",
3564 * - alternative_form_view
3565 * - auto_write (default true)
3569 * - form_view_options
3572 show_element: function(model, row_id, context, options) {
3574 this.row_id = row_id;
3575 this.context = context || {};
3576 this.options = _.defaults(options || {}, {"auto_write": true});
3577 this.renderElement();
3578 instance.web.dialog(this.$element, {
3579 title: options.title || '',
3588 this.dataset = new instance.web.form.FormOpenDataset(this, this.model, this.context);
3589 this.dataset.fop = this;
3590 this.dataset.ids = [this.row_id];
3591 this.dataset.index = 0;
3592 this.dataset.parent_view = this.options.parent_view;
3593 this.dataset.child_name = this.options.child_name;
3594 this.setup_form_view();
3596 on_write: function(id, data) {
3597 if (!this.options.auto_write)
3600 var wdataset = new instance.web.DataSetSearch(this, this.model, this.context, this.domain);
3601 wdataset.parent_view = this.options.parent_view;
3602 wdataset.child_name = this.options.child_name;
3603 wdataset.write(id, data, {}, function(r) {
3604 self.on_write_completed();
3607 on_write_completed: function() {},
3608 setup_form_view: function() {
3610 var FormClass = instance.web.views.get_object('form');
3611 var options = _.clone(self.options.form_view_options) || {};
3612 options.initial_mode = this.options.readonly ? "view" : "edit";
3613 this.view_form = new FormClass(this, this.dataset, false, options);
3614 if (this.options.alternative_form_view) {
3615 this.view_form.set_embedded_view(this.options.alternative_form_view);
3617 this.view_form.appendTo(this.$element.find(".oe-form-open-popup-form-view"));
3618 this.view_form.on_loaded.add_last(function() {
3619 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3620 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3621 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3622 $nbutton.click(function() {
3623 self.view_form.do_save().then(function() {
3627 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3628 $cbutton.click(function() {
3631 if (self.options.readonly) {
3633 $cbutton.text(_t("Close"));
3635 self.view_form.do_show();
3637 this.dataset.on_write.add(this.on_write);
3641 instance.web.form.FormOpenDataset = instance.web.ProxyDataSet.extend({
3642 read_ids: function() {
3643 if (this.fop.options.read_function) {
3644 return this.fop.options.read_function.apply(null, arguments);
3646 return this._super.apply(this, arguments);
3651 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3652 template: 'FieldReference',
3653 init: function(field_manager, node) {
3654 this._super(field_manager, node);
3655 this.reference_ready = true;
3657 on_nop: function() {
3659 on_selection_changed: function() {
3660 if (this.reference_ready) {
3661 var sel = this.selection.get_value();
3662 this.m2o.field.relation = sel;
3663 this.m2o.set_value(false);
3664 this.m2o.$element.toggle(sel !== false);
3667 destroy_content: function() {
3668 if (this.selection) {
3669 this.selection.destroy();
3670 this.selection = undefined;
3674 this.m2o = undefined;
3677 initialize_content: function() {
3678 this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3681 this.selection.view = this.view;
3682 this.selection.set({force_readonly: this.get('effective_readonly')});
3683 this.selection.on("change:value", this, this.on_selection_changed);
3684 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3685 this.selection.renderElement();
3686 this.selection.start();
3688 this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3691 this.m2o.view = this.view;
3692 this.m2o.set({force_readonly: this.get("effective_readonly")});
3693 this.m2o.on("change:value", this, this.data_changed);
3694 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3695 this.m2o.renderElement();
3698 is_false: function() {
3699 return typeof(this.get_value()) !== 'string';
3701 set_value: function(value_) {
3702 this._super(value_);
3703 this.render_value();
3705 render_value: function() {
3706 this.reference_ready = false;
3707 var vals = [], sel_val, m2o_val;
3708 if (typeof(this.get('value')) === 'string') {
3709 vals = this.get('value').split(',');
3711 sel_val = vals[0] || false;
3712 m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3713 if (!this.get("effective_readonly")) {
3714 this.selection.set_value(sel_val);
3716 this.m2o.field.relation = sel_val;
3717 this.m2o.set_value(m2o_val);
3718 this.reference_ready = true;
3720 data_changed: function() {
3721 var model = this.selection.get_value(),
3722 id = this.m2o.get_value();
3723 if (typeof(model) === 'string' && typeof(id) === 'number') {
3724 this.set({'value': model + ',' + id});
3726 this.set({'value': false});
3729 get_field: function(name) {
3730 if (name === "selection") {
3732 selection: this.view.fields_view.fields[this.name].selection,
3735 } else if (name === "m2o") {
3741 throw Exception("Should not happen");
3745 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3746 init: function(field_manager, node) {
3747 this._super(field_manager, node);
3748 this.iframe = this.element_id + '_iframe';
3749 this.binary_value = false;
3751 initialize_content: function() {
3752 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3753 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3754 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3756 human_filesize : function(size) {
3757 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3759 while (size >= 1024) {
3763 return size.toFixed(2) + ' ' + units[i];
3765 on_file_change: function(e) {
3766 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3767 // http://www.html5rocks.com/tutorials/file/dndfiles/
3768 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3769 window[this.iframe] = this.on_file_uploaded;
3770 if ($(e.target).val() != '') {
3771 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3772 this.$element.find('form.oe-binary-form').submit();
3773 this.$element.find('.oe-binary-progress').show();
3774 this.$element.find('.oe-binary').hide();
3777 on_file_uploaded: function(size, name, content_type, file_base64) {
3778 delete(window[this.iframe]);
3779 if (size === false) {
3780 this.do_warn("File Upload", "There was a problem while uploading your file");
3781 // TODO: use openerp web crashmanager
3782 console.warn("Error while uploading file : ", name);
3784 this.on_file_uploaded_and_valid.apply(this, arguments);
3786 this.$element.find('.oe-binary-progress').hide();
3787 this.$element.find('.oe-binary').show();
3789 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3791 on_save_as: function() {
3793 this.session.get_file({
3794 url: '/web/binary/saveas_ajax',
3795 data: {data: JSON.stringify({
3796 model: this.view.dataset.model,
3797 id: (this.view.datarecord.id || ''),
3799 filename_field: (this.node.attrs.filename || ''),
3800 context: this.view.dataset.get_context()
3802 complete: $.unblockUI,
3803 error: instance.webclient.crashmanager.on_rpc_error
3806 on_clear: function() {
3807 if (this.get('value') !== false) {
3808 this.binary_value = false;
3809 this.set({'value': false});
3815 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
3816 template: 'FieldBinaryFile',
3817 initialize_content: function() {
3819 if (this.get("effective_readonly")) {
3821 this.$element.find('a').click(function() {
3822 if (self.get('value')) {
3829 set_value: function(value_) {
3830 this._super.apply(this, arguments);
3831 this.render_value();
3833 render_value: function() {
3834 if (!this.get("effective_readonly")) {
3836 if (this.node.attrs.filename) {
3837 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3839 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
3841 this.$element.find('input').eq(0).val(show_value);
3843 this.$element.find('a').show(!!this.get('value'));
3844 if (this.get('value')) {
3845 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
3846 this.$element.find('a').text(show_value);
3850 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3851 this.binary_value = true;
3852 this.set({'value': file_base64});
3853 var show_value = name + " (" + this.human_filesize(size) + ")";
3854 this.$element.find('input').eq(0).val(show_value);
3855 this.set_filename(name);
3857 set_filename: function(value_) {
3858 var filename = this.node.attrs.filename;
3859 if (this.view.fields[filename]) {
3860 this.view.fields[filename].set({value: value_});
3863 on_clear: function() {
3864 this._super.apply(this, arguments);
3865 this.$element.find('input').eq(0).val('');
3866 this.set_filename('');
3870 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
3871 template: 'FieldBinaryImage',
3872 initialize_content: function() {
3874 this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
3875 if (!this.get("effective_readonly"))
3876 this.$element.find('.oe-binary').show();
3878 this.$element.find('.oe-binary').hide();
3880 set_value: function(value_) {
3881 this._super.apply(this, arguments);
3882 this.render_value();
3884 render_value: function() {
3886 if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
3887 url = 'data:image/png;base64,' + this.get('value');
3888 } else if (this.get('value')) {
3889 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3890 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3892 url = "/web/static/src/img/placeholder.png";
3894 var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
3895 this.$placeholder.html(rendered);
3897 on_file_change: function() {
3898 this.render_value();
3899 this._super.apply(this, arguments);
3901 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3902 this.set({'value': file_base64});
3903 this.binary_value = true;
3904 this.render_value();
3906 on_clear: function() {
3907 this._super.apply(this, arguments);
3908 this.render_value();
3912 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
3913 template: "EmptyComponent",
3916 this.selected_value = null;
3920 set_value: function(value_) {
3921 this._super(value_);
3922 this.selected_value = value_;
3926 render_list: function() {
3928 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3929 function(x) { return _.str.trim(x); });
3930 shown = _.select(shown, function(x) { return x.length > 0; });
3932 if (shown.length == 0) {
3933 this.to_show = this.field.selection;
3935 this.to_show = _.select(this.field.selection, function(x) {
3936 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3940 var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3941 this.$element.html(content);
3943 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3944 var color = colors[this.selected_value];
3946 var elem = this.$element.find("li.oe-arrow-list-selected span");
3947 elem.css("border-color", color);
3948 if (this.check_white(color))
3949 elem.css("color", "white");
3950 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3951 elem.css("border-left-color", "rgba(0,0,0,0)");
3952 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3953 elem.css("border-color", "rgba(0,0,0,0)");
3954 elem.css("border-left-color", color);
3957 check_white: function(color) {
3958 var div = $("<div></div>");
3959 div.css("display", "none");
3960 div.css("color", color);
3961 div.appendTo($("body"));
3962 var ncolor = div.css("color");
3964 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3968 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3969 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3978 * Registry of form fields, called by :js:`instance.web.FormView`.
3980 * All referenced classes must implement FieldMixin. Those represent the classes whose instances
3981 * will substitute to the <field> tags as defined in OpenERP's views.
3983 instance.web.form.widgets = new instance.web.Registry({
3984 'char' : 'instance.web.form.FieldChar',
3985 'id' : 'instance.web.form.FieldID',
3986 'email' : 'instance.web.form.FieldEmail',
3987 'url' : 'instance.web.form.FieldUrl',
3988 'text' : 'instance.web.form.FieldText',
3989 'date' : 'instance.web.form.FieldDate',
3990 'datetime' : 'instance.web.form.FieldDatetime',
3991 'selection' : 'instance.web.form.FieldSelection',
3992 'many2one' : 'instance.web.form.FieldMany2One',
3993 'many2many' : 'instance.web.form.FieldMany2Many',
3994 'many2manytags' : 'instance.web.form.FieldMany2ManyTags',
3995 'one2many' : 'instance.web.form.FieldOne2Many',
3996 'one2many_list' : 'instance.web.form.FieldOne2Many',
3997 'reference' : 'instance.web.form.FieldReference',
3998 'boolean' : 'instance.web.form.FieldBoolean',
3999 'float' : 'instance.web.form.FieldFloat',
4000 'integer': 'instance.web.form.FieldFloat',
4001 'float_time': 'instance.web.form.FieldFloat',
4002 'progressbar': 'instance.web.form.FieldProgressBar',
4003 'image': 'instance.web.form.FieldBinaryImage',
4004 'binary': 'instance.web.form.FieldBinaryFile',
4005 'statusbar': 'instance.web.form.FieldStatus'
4009 * Registry of widgets usable in the form view that can substitute to any possible
4010 * tags defined in OpenERP's form views.
4012 * Every referenced class should extend FormWidget.
4014 instance.web.form.tags = new instance.web.Registry({
4015 'button' : 'instance.web.form.WidgetButton',
4020 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: