1 openerp.web.form = function (openerp) {
2 var _t = openerp.web._t,
4 var QWeb = openerp.web.qweb;
9 openerp.web.views.add('form', 'openerp.web.FormView');
10 openerp.web.FormView = openerp.web.View.extend({
12 * Indicates that this view is not searchable, and thus that no search
13 * view should be displayed (if there is one active).
17 display_name: _lt('Form'),
20 * @constructs openerp.web.FormView
21 * @extends openerp.web.View
23 * @param {openerp.web.Session} session the current openerp session
24 * @param {openerp.web.DataSet} dataset the dataset this view will work with
25 * @param {String} view_id the identifier of the OpenERP view object
26 * @param {Object} options
27 * - sidebar : [true|false]
28 * - resize_textareas : [true|false|max_height]
30 * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
32 init: function(parent, dataset, view_id, options) {
34 this.set_default_options(options);
35 this.dataset = dataset;
36 this.model = dataset.model;
37 this.view_id = view_id || false;
38 this.fields_view = {};
40 this.fields_order = [];
42 this.default_focus_field = null;
43 this.default_focus_button = null;
44 this.fields_registry = openerp.web.form.widgets;
45 this.tags_registry = openerp.web.form.tags;
46 this.has_been_loaded = $.Deferred();
47 this.translatable_fields = [];
48 _.defaults(this.options, {
49 "not_interactible_on_create": false,
50 "initial_mode": "view",
52 this.is_initialized = $.Deferred();
53 this.mutating_mutex = new $.Mutex();
54 this.on_change_mutex = new $.Mutex();
55 this.reload_mutex = new $.Mutex();
57 this.rendering_engine = new openerp.web.form.FormRenderingEngineReadonly(this);
60 _.each(this.get_widgets(), function(w) {
65 on_loaded: function(data) {
68 throw new Error("No data provided.");
71 throw "Form view does not support multiple calls to on_loaded";
73 this.fields_order = [];
74 this.fields_view = data;
76 this.rendering_engine.set_fields_view(data);
77 this.rendering_engine.set_fields_registry(this.fields_registry);
78 this.rendering_engine.set_tags_registry(this.tags_registry);
79 var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
80 this.rendering_engine.render_to($dest);
82 this.$sidebar = this.options.$sidebar || this.$element.find('.oe_form_sidebar');
84 var buttons_html = QWeb.render("FormView.buttons", {'widget':self});
85 this.$buttons = $(_.str.isBlank(buttons_html) ? '<div>' : buttons_html);
86 if (this.options.$buttons) {
87 this.$buttons.appendTo(this.options.$buttons);
89 this.$element.find('.oe_form_buttons').replaceWith(this.$buttons);
92 .on('click','button.oe_form_button_save',this.on_button_save)
93 .on('click','button.oe_form_button_cancel',this.on_button_cancel)
94 .on('click','button.oe_form_button_edit',this.on_button_edit)
95 .on('click','button.oe_form_button_create',this.on_button_create)
96 .on('click','button.oe_form_button_duplicate',this.on_button_duplicate)
97 .on('click','button.oe_form_button_delete',this.on_button_delete);
99 var pager_html = QWeb.render("FormView.pager", {'widget':self});
100 this.$pager = $(_.str.isBlank(pager_html) ? '<div>' : pager_html);
101 if (this.options.$pager) {
102 this.$pager.appendTo(this.options.$pager);
104 this.$element.find('.oe_form_pager').replaceWith(this.$pager);
106 this.$pager.on('click','a[data-pager-action]',function() {
107 var action = $(this).data('pager-action');
108 self.on_pager_action(action);
111 if (!this.sidebar && this.options.sidebar) {
112 this.sidebar = new openerp.web.Sidebar(this);
113 this.sidebar.appendTo(this.$sidebar);
114 //this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
115 this.sidebar.add_toolbar(this.fields_view.toolbar);
116 this.sidebar.add_items('other', [{
117 label: _t('Set Default'),
119 callback: function (item) {
120 item.form.open_defaults_dialog();
124 this.on("change:mode", this, this.switch_mode);
125 this.set({mode: this.options.initial_mode});
126 this.has_been_loaded.resolve();
129 do_load_state: function(state, warm) {
130 if (state.id && this.datarecord.id != state.id) {
131 if (!this.dataset.get_id_index(state.id)) {
132 this.dataset.ids.push(state.id);
134 this.dataset.select_id(state.id);
140 do_show: function () {
143 this.sidebar.$element.show();
146 this.$buttons.show();
147 this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
152 this.$element.show().css('visibility', 'hidden');
153 this.$element.removeClass('oe_form_dirty');
154 return this.has_been_loaded.pipe(function() {
156 if (self.dataset.index === null) {
157 // null index means we should start a new record
158 result = self.on_button_new();
160 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
161 context : { 'bin_size' : true }
162 }).pipe(self.on_record_loaded);
164 result.pipe(function() {
165 self.$element.css('visibility', 'visible');
170 do_hide: function () {
172 this.sidebar.$element.hide();
175 this.$buttons.hide();
182 on_record_loaded: function(record) {
183 var self = this, set_values = [];
185 this.do_warn("Form", "The record could not be found in the database.", true);
186 return $.Deferred().reject();
188 this.datarecord = record;
190 _(this.fields).each(function (field, f) {
192 var result = field.set_value(self.datarecord[f] || false);
193 set_values.push(result);
194 $.when(result).then(function() {
198 return $.when.apply(null, set_values).pipe(function() {
200 // New record: Second pass in order to trigger the onchanges
201 // respecting the fields order defined in the view
202 _.each(self.fields_order, function(field_name) {
203 if (record[field_name] !== undefined) {
204 var field = self.fields[field_name];
206 self.do_onchange(field);
210 self.on_form_changed();
211 self.is_initialized.resolve();
212 self.do_update_pager(record.id == null);
214 // self.sidebar.attachments.do_update();
216 if (self.default_focus_field) {
217 self.default_focus_field.focus();
220 self.do_push_state({id:record.id});
222 self.$element.removeClass('oe_form_dirty');
223 self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
226 on_form_changed: function() {
227 this.trigger("view_content_has_changed");
228 _.each(this.get_widgets(), function(w) {
235 do_notify_change: function() {
236 this.$element.addClass('oe_form_dirty');
237 this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
239 on_pager_action: function(action) {
240 if (this.can_be_discarded()) {
243 this.dataset.index = 0;
246 this.dataset.previous();
252 this.dataset.index = this.dataset.ids.length - 1;
258 do_update_pager: function(hide_index) {
259 var index = hide_index ? '-' : this.dataset.index + 1;
260 this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
261 .find('span.oe_pager_index').html(index).end()
262 .find('span.oe_pager_count').html(this.dataset.ids.length);
264 parse_on_change: function (on_change, widget) {
266 var onchange = _.str.trim(on_change);
267 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
272 var method = call[1];
273 if (!_.str.trim(call[2])) {
274 return {method: method, args: [], context_index: null}
277 var argument_replacement = {
278 'False': function () {return false;},
279 'True': function () {return true;},
280 'None': function () {return null;},
281 'context': function (i) {
283 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
287 var parent_fields = null, context_index = null;
288 var args = _.map(call[2].split(','), function (a, i) {
289 var field = _.str.trim(a);
291 // literal constant or context
292 if (field in argument_replacement) {
293 return argument_replacement[field](i);
296 if (/^-?\d+(\.\d+)?$/.test(field)) {
297 return Number(field);
300 if (self.fields[field]) {
301 var value = self.fields[field].get_value();
302 return value == null ? false : value;
305 var splitted = field.split('.');
306 if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
307 if (parent_fields === null) {
308 parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
310 var p_val = parent_fields[_.str.trim(splitted[1])];
311 if (p_val !== undefined) {
312 return p_val == null ? false : p_val;
316 var first_char = field[0], last_char = field[field.length-1];
317 if ((first_char === '"' && last_char === '"')
318 || (first_char === "'" && last_char === "'")) {
319 return field.slice(1, -1);
322 throw new Error("Could not get field with name '" + field +
323 "' for onchange '" + onchange + "'");
329 context_index: context_index
332 do_onchange: function(widget, processed) {
334 return this.on_change_mutex.exec(function() {
336 var response = {}, can_process_onchange = $.Deferred();
337 processed = processed || [];
338 processed.push(widget.name);
339 var on_change = widget.node.attrs.on_change;
341 var change_spec = self.parse_on_change(on_change, widget);
344 url: '/web/dataset/onchange',
347 can_process_onchange = self.rpc(ajax, {
348 model: self.dataset.model,
349 method: change_spec.method,
350 args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
351 context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
352 }).then(function(r) {
353 _.extend(response, r);
356 console.warn("Wrong on_change format", on_change);
359 // fail if onchange failed
360 if (can_process_onchange.isRejected()) {
361 return can_process_onchange;
364 if (widget.field['change_default']) {
365 var fieldname = widget.name, value;
366 if (response.value && (fieldname in response.value)) {
367 // Use value from onchange if onchange executed
368 value = response.value[fieldname];
370 // otherwise get form value for field
371 value = self.fields[fieldname].get_value();
373 var condition = fieldname + '=' + value;
376 can_process_onchange = self.rpc({
377 url: '/web/dataset/call',
381 method: 'get_defaults',
382 args: [self.model, condition]
383 }).then(function (results) {
384 if (!results.length) { return; }
385 if (!response.value) {
388 for(var i=0; i<results.length; ++i) {
389 // [whatever, key, value]
390 var triplet = results[i];
391 response.value[triplet[1]] = triplet[2];
396 if (can_process_onchange.isRejected()) {
397 return can_process_onchange;
400 return self.on_processed_onchange(response, processed);
403 return $.Deferred().reject();
407 on_processed_onchange: function(response, processed) {
409 var result = response;
411 for (var f in result.value) {
412 if (!result.value.hasOwnProperty(f)) { continue; }
413 var field = this.fields[f];
414 // If field is not defined in the view, just ignore it
416 var value = result.value[f];
417 if (field.get_value() != value) {
418 field.set_value(value);
420 if (!_.contains(processed, field.name)) {
421 this.do_onchange(field, processed);
426 this.on_form_changed();
428 if (!_.isEmpty(result.warning)) {
429 openerp.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
432 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
437 function edit_domain(node) {
438 var new_domain = result.domain[node.attrs.name];
440 node.attrs.domain = new_domain;
442 _(node.children).each(edit_domain);
444 edit_domain(this.fields_view.arch);
446 return $.Deferred().resolve();
449 return $.Deferred().reject();
452 switch_mode: function() {
453 var mode = this.get("mode");
456 self.$buttons.find('.oe_form_buttons_edit').hide();
457 self.$buttons.find('.oe_form_buttons_view').show();
458 _.each(this.fields,function(field){
459 field.set({"force_readonly": true});
462 self.$buttons.find('.oe_form_buttons_edit').show();
463 self.$buttons.find('.oe_form_buttons_view').hide();
464 _.each(this.fields,function(field){
465 field.set({"force_readonly": false});
470 on_button_save: function() {
472 return this.do_save().then(function(result) {
473 self.set({mode: "view"});
476 on_button_cancel: function() {
477 if (this.can_be_discarded()) {
478 this.set({mode: "view"});
481 on_button_new: function() {
483 this.set({mode: "edit"});
484 var def = $.Deferred();
485 $.when(this.has_been_loaded).then(function() {
486 if (self.can_be_discarded()) {
487 var keys = _.keys(self.fields_view.fields);
489 self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
493 self.on_record_loaded({}).then(function() {
499 return def.promise();
501 on_button_edit: function() {
502 return this.set({mode: "edit"});
504 on_button_create: function() {
505 this.dataset.index = null;
508 on_button_duplicate: function() {
510 var def = $.Deferred();
511 $.when(this.has_been_loaded).then(function() {
512 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
513 return self.on_created({ result : new_id });
515 return self.set({mode: "edit"});
520 return def.promise();
522 on_button_delete: function() {
524 var def = $.Deferred();
525 $.when(this.has_been_loaded).then(function() {
526 if (self.datarecord.id && confirm(_t("Do you really want to delete this record?"))) {
527 self.dataset.unlink([self.datarecord.id]).then(function() {
528 self.on_pager_action('next');
532 $.async_when().then(function () {
537 return def.promise();
539 can_be_discarded: function() {
540 return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
543 * Triggers saving the form's record. Chooses between creating a new
544 * record or saving an existing one depending on whether the record
545 * already has an id property.
547 * @param {Function} success callback on save success
548 * @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)
550 do_save: function(success, prepend_on_create) {
552 return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
554 var form_invalid = false,
556 first_invalid_field = null;
557 for (var f in self.fields) {
562 if (!first_invalid_field) {
563 first_invalid_field = f;
565 } else if (f.name !== 'id' && !f.get("readonly") && (!self.datarecord.id || f.is_dirty())) {
566 // Special case 'id' field, do not save this field
567 // on 'create' : save all non readonly fields
568 // on 'edit' : save non readonly modified fields
569 values[f.name] = f.get_value();
573 first_invalid_field.focus();
575 return $.Deferred().reject();
578 if (!self.datarecord.id) {
579 //console.log("FormView(", self, ") : About to create", values);
580 save_deferral = self.dataset.create(values).pipe(function(r) {
581 return self.on_created(r, undefined, prepend_on_create);
583 } else if (_.isEmpty(values)) {
584 //console.log("FormView(", self, ") : Nothing to save");
585 save_deferral = $.Deferred().resolve({}).promise();
587 //console.log("FormView(", self, ") : About to save", values);
588 save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
589 return self.on_saved(r);
592 return save_deferral.then(success);
596 return $.Deferred().reject();
600 on_invalid: function() {
602 _.each(this.fields, function(f) {
604 msg += "<li>" + f.node.attrs.string + "</li>";
608 this.do_warn("The following fields are invalid :", msg);
610 on_saved: function(r, success) {
612 // should not happen in the server, but may happen for internal purpose
613 return $.Deferred().reject();
615 return $.when(this.reload()).pipe(function () {
616 return $.when(r).then(success); }, null);
620 * Updates the form' dataset to contain the new record:
622 * * Adds the newly created record to the current dataset (at the end by
624 * * Selects that record (sets the dataset's index to point to the new
626 * * Updates the pager and sidebar displays
629 * @param {Function} success callback to execute after having updated the dataset
630 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
632 on_created: function(r, success, prepend_on_create) {
634 // should not happen in the server, but may happen for internal purpose
635 return $.Deferred().reject();
637 this.datarecord.id = r.result;
638 if (!prepend_on_create) {
639 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
640 this.dataset.index = this.dataset.ids.length - 1;
642 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
643 this.dataset.index = 0;
645 this.do_update_pager();
647 // this.sidebar.attachments.do_update();
649 //openerp.log("The record has been created with id #" + this.datarecord.id);
651 return $.when(_.extend(r, {created: true})).then(success);
654 on_action: function (action) {
655 console.debug('Executing action', action);
659 return this.reload_mutex.exec(function() {
660 if (self.dataset.index == null) {
662 return $.Deferred().reject().promise();
664 if (self.dataset.index == null || self.dataset.index < 0) {
665 return $.when(self.on_button_new());
667 return self.dataset.read_index(_.keys(self.fields_view.fields), {
668 context : { 'bin_size' : true }
669 }).pipe(self.on_record_loaded);
673 get_widgets: function() {
674 return _.filter(this.getChildren(), function(obj) {
675 return obj instanceof openerp.web.form.Widget;
678 get_fields_values: function(blacklist) {
679 blacklist = blacklist || [];
681 var ids = this.get_selected_ids();
682 values["id"] = ids.length > 0 ? ids[0] : false;
683 _.each(this.fields, function(value, key) {
684 if (_.include(blacklist, key))
686 var val = value.get_value();
691 get_selected_ids: function() {
692 var id = this.dataset.ids[this.dataset.index];
693 return id ? [id] : [];
695 recursive_save: function() {
697 return $.when(this.do_save()).pipe(function(res) {
698 if (self.dataset.parent_view)
699 return self.dataset.parent_view.recursive_save();
702 is_dirty: function() {
703 return _.any(this.fields, function (value) {
704 return value.is_dirty();
707 is_interactible_record: function() {
708 var id = this.datarecord.id;
710 if (this.options.not_interactible_on_create)
712 } else if (typeof(id) === "string") {
713 if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
718 sidebar_context: function () {
719 return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
721 open_defaults_dialog: function () {
723 var fields = _.chain(this.fields)
724 .map(function (field, name) {
725 var value = field.get_value();
726 // ignore fields which are empty, invisible, readonly, o2m
729 || field.get('invisible')
730 || field.get("readonly")
731 || field.field.type === 'one2many'
732 || field.field.type === 'many2many') {
736 switch(field.field.type) {
738 displayed = _(field.values).find(function (option) {
739 return option[0] === value;
743 displayed = field.value[1] || value;
751 string: field.node_atts.string,
753 displayed: displayed,
754 // convert undefined to false
755 change_default: !!field.field.change_default
759 .sortBy(function (field) { return field.node_atts.string; })
761 var conditions = _.chain(fields)
762 .filter(function (field) { return field.change_default; })
765 var d = new openerp.web.Dialog(this, {
766 title: _t("Set Default"),
769 conditions: conditions
772 {text: _t("Close"), click: function () { d.close(); }},
773 {text: _t("Save default"), click: function () {
774 var $defaults = d.$element.find('#formview_default_fields');
775 var field_to_set = $defaults.val();
777 $defaults.parent().addClass('oe_form_invalid');
780 var condition = d.$element.find('#formview_default_conditions').val(),
781 all_users = d.$element.find('#formview_default_all').is(':checked');
782 new openerp.web.DataSet(self, 'ir.values').call(
786 self.fields[field_to_set].get_value(),
790 ]).then(function () { d.close(); });
794 d.template = 'FormView.set_default';
800 * Interface to be implemented by rendering engines for the form view.
802 openerp.web.form.FormRenderingEngineInterface = {
803 set_fields_view: function(fields_view) {},
804 set_fields_registry: function(fields_registry) {},
805 render_to: function($element) {},
809 * Default rendering engine for the form view.
811 * It is necessary to set the view using set_view() before usage.
813 openerp.web.form.FormRenderingEngine = openerp.web.Class.extend({
814 init: function(view) {
817 set_fields_view: function(fvg) {
820 set_tags_registry: function(tags_registry) {
821 this.tags_registry = tags_registry;
823 set_fields_registry: function(fields_registry) {
824 this.fields_registry = fields_registry;
826 render_to: function($target) {
828 this.$target = $target;
830 // TODO: I know this will save the world and all the kitten for a moment,
831 // but one day, we will have to get rid of xml2json
832 var xml = openerp.web.json_node_to_xml(this.fvg.arch);
833 this.$form = $('<div class="oe_form">' + xml + '</div>');
834 if (this.fvg.arch.attrs && this.fvg.arch.attrs['layout'] !== 'manual') {
835 this.$form.attr('layout', 'auto');
838 this.fields_to_init = [];
839 this.tags_to_init = [];
841 this.process(this.$form);
843 this.$form.appendTo(this.$target);
845 _.each(this.fields_to_init, function($elem) {
846 var name = $elem.attr("name");
847 if (!self.fvg.fields[name]) {
848 throw new Error("Field '" + name + "' specified in view could not be found.");
850 var key = $elem.attr('widget') || self.fvg.fields[name].type;
851 if (!self.fields_registry.contains(key)) {
852 throw new Error("Widget type '"+ key + "' is not implemented");
854 var obj = self.fields_registry.get_object(key);
855 var w = new (obj)(self.view, openerp.web.xml_to_json($elem[0]));
856 var $label = self.labels[$elem.attr("name")];
858 w.set_input_id($label.attr("for"));
863 _.each(this.tags_to_init, function($elem) {
864 var tag_name = $elem[0].tagName.toLowerCase();
865 var obj = self.tags_registry.get_object(tag_name);
866 var w = new (obj)(self.view, openerp.web.xml_to_json($elem[0]));
870 render_element: function(template, layout/* dictionaries */) {
871 var dicts = [].slice.call(arguments).slice(2);
872 dicts.unshift({ 'layout' : layout });
873 var dict = _.extend.apply(_, dicts);
874 dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
875 var alt_template = template + '.' + layout;
876 template = QWeb.has_template(alt_template) ? alt_template : template;
877 return $(QWeb.render(template, dict));
879 alter_field: function(field) {
881 toggle_layout_debugging: function() {
882 if (!this.$target.has('.oe_layout_debug_cell:first').length) {
883 this.$target.find('.oe_form_group_cell').each(function() {
884 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan'),
885 $span = $('<span class="oe_layout_debug_cell"/>').text(text);
886 $span.prependTo($(this));
889 this.$target.toggleClass('oe_layout_debugging');
891 process: function($tag, layout) {
893 if ($tag.attr('layout') === 'auto') {
894 $tag.addClass('oe_form_autolayout');
896 layout = $tag.attr('layout') || layout || 'auto';
897 $tag.removeAttr('layout');
898 var tagname = $tag[0].nodeName.toLowerCase();
899 if (this.tags_registry.contains(tagname)) {
900 this.tags_to_init.push($tag);
903 var fn = self['process_' + tagname];
905 var args = [].slice.call(arguments);
908 return fn.apply(self, args);
910 // generic tag handling, just process children
911 $tag.children().each(function() {
912 self.process($(this), layout);
914 self.handle_common_properties($tag, $tag);
915 $tag.removeAttr("modifiers");
919 process_sheet: function() {
920 this.process_form.apply(this, arguments);
922 process_form: function($form, layout) {
923 var $new_form = this.render_element('FormRenderingForm', layout, $form.getAttributes());
924 var $dst = (layout === 'auto') ? $new_form.find('group:first') : $new_form;
925 $new_form.attr("modifiers", $form.attr("modifiers"));
926 $form.children().appendTo($dst);
927 if ($form[0] === this.$form[0]) {
928 // If root element, replace it
929 this.$form = $new_form;
931 $form.before($new_form).remove();
933 this.process($new_form);
935 preprocess_field: function($field) {
937 var name = $field.attr('name'),
938 field_colspan = parseInt($field.attr('colspan'), 10),
939 field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
941 if ($field.attr('nolabel') === '1')
943 $field.attr('nolabel', '1');
945 this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
946 $(el).parents().each(function(unused, tag) {
947 var name = tag.tagName.toLowerCase();
948 if (name === "field" || name in self.tags_registry.map)
955 $label = $('<label/>').attr({
957 "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
958 "string": $field.attr('string'),
959 "help": $field.attr('help'),
961 $label.insertBefore($field);
962 if (field_colspan > 1) {
963 $field.attr('colspan', field_colspan - 1);
967 process_field: function($field, layout) {
968 var $label = this.preprocess_field($field);
970 this.process($label, layout);
971 this.fields_to_init.push($field);
974 process_group: function($group, layout) {
976 if ($group.parent().is('.oe_form_group_cell')) {
977 $group.parent().addClass('oe_form_group_nested');
979 $group.children('field').each(function() {
980 self.preprocess_field($(this));
982 var $new_group = this.render_element('FormRenderingGroup', layout, $group.getAttributes()),
984 if ($new_group.is('table')) {
987 $table = $new_group.find('table:first');
989 $table.addClass('oe_form_group');
991 cols = parseInt($group.attr('col') || 4, 10),
995 $group.children().each(function(a,b,c) {
996 var $child = $(this),
997 colspan = parseInt($child.attr('colspan') || 1, 10),
998 tagName = $child[0].tagName.toLowerCase();
999 if (tagName === 'newline') {
1003 if (!$tr || row_cols < colspan) {
1004 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1007 row_cols -= colspan;
1009 $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1010 // invisibility transfer
1011 var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1012 var invisible = field_modifiers.invisible;
1013 field_modifiers.invisible = undefined;
1014 $child.attr('modifiers', JSON.stringify(field_modifiers));
1015 self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1017 $tr.append($td.append($child));
1018 children.push($child[0]);
1020 if (row_cols && $td) {
1021 $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1023 $group.before($new_group).remove();
1025 // Now compute width of cells
1026 $table.find('> tbody > tr').each(function() {
1027 var to_compute = [],
1030 $(this).children().each(function() {
1032 $child = $td.children(':first');
1033 switch ($child[0].tagName.toLowerCase()) {
1035 if ($child.attr('orientation') === 'vertical') {
1036 $td.addClass('oe_vertical_separator').attr('width', '1');
1042 if ($child.attr('for')) {
1043 $td.attr('width', '1%');
1049 to_compute.push($td);
1052 var unit = Math.floor(total / row_cols);
1053 _.each(to_compute, function($td, i) {
1054 var width = parseInt($td.attr('colspan'), 10) * unit;
1055 $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
1059 _.each(children, function(el) {
1060 self.process($(el));
1062 this.handle_common_properties($new_group, $group);
1065 process_notebook: function($notebook, layout) {
1068 $notebook.find('> page').each(function() {
1069 var $page = $(this);
1070 var page_attrs = $page.getAttributes();
1071 page_attrs.id = _.uniqueId('notebook_page_');
1072 pages.push(page_attrs);
1073 var $new_page = self.render_element('FormRenderingNotebookPage', layout, page_attrs);
1074 var $dst = (layout === 'auto') ? $new_page.find('group:first') : $new_page;
1075 $page.children().appendTo($dst);
1076 $page.before($new_page).remove();
1077 self.handle_common_properties($new_page, $page);
1079 var $new_notebook = this.render_element('FormRenderingNotebook', layout, { pages : pages });
1080 $notebook.children().appendTo($new_notebook);
1081 $notebook.before($new_notebook).remove();
1082 $new_notebook.children().each(function() {
1083 self.process($(this));
1085 $new_notebook.tabs();
1086 this.handle_common_properties($new_notebook, $notebook);
1087 return $new_notebook;
1089 process_separator: function($separator, layout) {
1090 var $new_separator = this.render_element('FormRenderingSeparator', layout, $separator.getAttributes());
1091 $separator.before($new_separator).remove();
1092 this.handle_common_properties($new_separator, $separator);
1093 return $new_separator;
1095 process_label: function($label, layout) {
1096 var name = $label.attr("for"),
1097 field_orm = this.fvg.fields[name];
1099 string: $label.attr('string') || (field_orm || {}).string || '',
1100 help: $label.attr('help') || (field_orm || {}).help || '',
1101 _for: name ? _.uniqueId('oe-field-input-') : undefined,
1103 var align = parseFloat(dict.align);
1104 if (isNaN(align) || align === 1) {
1106 } else if (align === 0) {
1112 var $new_label = this.render_element('FormRenderingLabel', layout, dict);
1113 $label.before($new_label).remove();
1114 this.handle_common_properties($new_label, $label);
1116 this.labels[name] = $new_label;
1120 handle_common_properties: function($new_element, $node) {
1121 var str_modifiers = $node.attr("modifiers") || "{}"
1122 var modifiers = JSON.parse(str_modifiers);
1123 if (modifiers.invisible !== undefined)
1124 new openerp.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1125 $new_element.addClass($node.attr("class") || "");
1129 openerp.web.form.FormRenderingEngineReadonly = openerp.web.form.FormRenderingEngine.extend({
1130 alter_field: function(field) {
1131 field.set({"force_readonly": true});
1135 openerp.web.form.FormDialog = openerp.web.Dialog.extend({
1136 init: function(parent, options, view_id, dataset) {
1137 this._super(parent, options);
1138 this.dataset = dataset;
1139 this.view_id = view_id;
1144 this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
1148 this.form.appendTo(this.$element);
1149 this.form.on_created.add_last(this.on_form_dialog_saved);
1150 this.form.on_saved.add_last(this.on_form_dialog_saved);
1153 select_id: function(id) {
1154 if (this.form.dataset.select_id(id)) {
1155 return this.form.do_show();
1157 this.do_warn("Could not find id in dataset");
1158 return $.Deferred().reject();
1161 on_form_dialog_saved: function(r) {
1167 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
1168 init: function(parent, form_view) {
1169 //var $section = parent.add_section(_t('Attachments'), 'attachments');
1170 //this.$div = $('<div class="oe-sidebar-attachments"></div>');
1171 //$section.append(this.$div);
1172 this._super(parent);
1173 this.view = form_view;
1175 do_update: function() {
1177 if (!this.view.datarecord.id) {
1178 this.on_attachments_loaded([]);
1180 (new openerp.web.DataSetSearch(
1181 this, 'ir.attachment', this.view.dataset.get_context(),
1183 ['res_model', '=', this.view.dataset.model],
1184 ['res_id', '=', this.view.datarecord.id],
1185 ['type', 'in', ['binary', 'url']]
1186 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
1189 on_attachments_loaded: function(attachments) {
1191 this.attachments = attachments;
1192 this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
1193 this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
1194 this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
1196 on_attachment_changed: function(e) {
1198 window[this.element_id + '_iframe'] = this.do_update;
1199 var $e = $(e.target);
1200 if ($e.val() != '') {
1201 this.$element.find('form.oe-binary-form').submit();
1202 $e.parent().find('input[type=file]').prop('disabled', true);
1203 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1206 on_attachment_delete: function(e) {
1208 var self = this, $e = $(e.currentTarget);
1209 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
1210 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
1211 this.rpc('/web/dataset/unlink', {
1212 model: 'ir.attachment',
1213 ids: [parseInt($e.attr('data-id'))]
1215 $e.parent().remove();
1216 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
1222 openerp.web.form.compute_domain = function(expr, fields) {
1224 for (var i = expr.length - 1; i >= 0; i--) {
1226 if (ex.length == 1) {
1227 var top = stack.pop();
1230 stack.push(stack.pop() || top);
1233 stack.push(stack.pop() && top);
1239 throw new Error(_.str.sprintf(
1240 _t("Unknown operator %s in domain %s"),
1241 ex, JSON.stringify(expr)));
1245 var field = fields[ex[0]];
1247 throw new Error(_.str.sprintf(
1248 _t("Unknown field %s in domain %s"),
1249 ex[0], JSON.stringify(expr)));
1251 var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
1255 switch (op.toLowerCase()) {
1258 stack.push(field_value == val);
1262 stack.push(field_value != val);
1265 stack.push(field_value < val);
1268 stack.push(field_value > val);
1271 stack.push(field_value <= val);
1274 stack.push(field_value >= val);
1277 if (!_.isArray(val)) val = [val];
1278 stack.push(_(val).contains(field_value));
1281 if (!_.isArray(val)) val = [val];
1282 stack.push(!_(val).contains(field_value));
1286 _t("Unsupported operator %s in domain %s"),
1287 op, JSON.stringify(expr));
1290 return _.all(stack, _.identity);
1294 * Must be applied over an class already possessing the GetterSetterMixin.
1296 * Apply the result of the "invisible" domain to this.$element.
1298 openerp.web.form.InvisibilityChangerMixin = {
1299 init: function(field_manager, invisible_domain) {
1300 this._ic_field_manager = field_manager
1301 this._ic_invisible_modifier = invisible_domain;
1302 this._ic_field_manager.on("view_content_has_changed", this, function() {
1303 var result = this._ic_invisible_modifier === undefined ? false :
1304 openerp.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1305 this.set({"invisible": result});
1307 this.set({invisible: this._ic_invisible_modifier === true});
1310 var check_visibility = function() {
1311 if (this.get("invisible")) {
1312 this.$element.hide();
1314 this.$element.show();
1317 this.on("change:invisible", this, check_visibility);
1318 _.bind(check_visibility, this)();
1322 openerp.web.form.InvisibilityChanger = openerp.web.Class.extend(_.extend({}, openerp.web.GetterSetterMixin, openerp.web.form.InvisibilityChangerMixin, {
1323 init: function(parent, field_manager, invisible_domain, $element) {
1324 this.setParent(parent);
1325 openerp.web.GetterSetterMixin.init.call(this);
1326 openerp.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1327 this.$element = $element;
1332 openerp.web.form.Widget = openerp.web.Widget.extend(_.extend({}, openerp.web.form.InvisibilityChangerMixin, {
1334 * @constructs openerp.web.form.Widget
1335 * @extends openerp.web.Widget
1340 init: function(view, node) {
1344 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1345 openerp.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1347 this.view.on("view_content_has_changed", this, this.process_modifiers);
1349 renderElement: function() {
1351 this.$element.addClass(this.node.attrs["class"] || "");
1355 openerp.web.form.InvisibilityChangerMixin.start.call(this);
1357 destroy: function() {
1359 this._super.apply(this, arguments);
1361 process_modifiers: function() {
1362 var compute_domain = openerp.web.form.compute_domain;
1364 for (var a in this.modifiers) {
1365 if (!_.include(["invisible"], a)) {
1366 var val = compute_domain(this.modifiers[a], this.view.fields);
1372 update_dom: function() {
1374 do_attach_tooltip: function(widget, trigger, options) {
1375 widget = widget || this;
1376 trigger = trigger || this.$element;
1377 options = _.extend({
1382 var template = widget.template + '.tooltip';
1383 if (!QWeb.has_template(template)) {
1384 template = 'WidgetLabel.tooltip';
1386 return QWeb.render(template, {
1387 debug: openerp.connection.debug,
1390 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1395 trigger.tipsy(options);
1397 _build_view_fields_values: function(blacklist) {
1398 var a_dataset = this.view.dataset;
1399 var fields_values = this.view.get_fields_values(blacklist);
1400 var active_id = a_dataset.ids[a_dataset.index];
1401 _.extend(fields_values, {
1402 active_id: active_id || false,
1403 active_ids: active_id ? [active_id] : [],
1404 active_model: a_dataset.model,
1407 if (a_dataset.parent_view) {
1408 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1410 return fields_values;
1412 _build_eval_context: function(blacklist) {
1413 var a_dataset = this.view.dataset;
1414 return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1417 * Builds a new context usable for operations related to fields by merging
1418 * the fields'context with the action's context.
1420 build_context: function(blacklist) {
1421 // only use the model's context if there is not context on the node
1422 var v_context = this.node.attrs.context;
1424 v_context = (this.field || {}).context || {};
1427 if (v_context.__ref || true) { //TODO: remove true
1428 var fields_values = this._build_eval_context(blacklist);
1429 v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1433 build_domain: function() {
1434 var f_domain = this.field.domain || [];
1435 var n_domain = this.node.attrs.domain || null;
1436 // if there is a domain on the node, overrides the model's domain
1437 var final_domain = n_domain !== null ? n_domain : f_domain;
1438 if (!(final_domain instanceof Array) || true) { //TODO: remove true
1439 var fields_values = this._build_eval_context();
1440 final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1442 return final_domain;
1446 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1447 template: 'WidgetButton',
1448 init: function(view, node) {
1449 this._super(view, node);
1450 this.force_disabled = false;
1451 this.string = (this.node.attrs.string || '').replace(/_/g, '');
1452 if (this.node.attrs.default_focus == '1') {
1453 // TODO fme: provide enter key binding to widgets
1454 this.view.default_focus_button = this;
1458 this._super.apply(this, arguments);
1459 this.$element.click(this.on_click);
1460 if (this.node.attrs.help || openerp.connection.debug) {
1461 this.do_attach_tooltip();
1464 on_click: function() {
1466 this.force_disabled = true;
1467 this.check_disable();
1468 this.execute_action().always(function() {
1469 self.force_disabled = false;
1470 self.check_disable();
1473 execute_action: function() {
1475 var exec_action = function() {
1476 if (self.node.attrs.confirm) {
1477 var def = $.Deferred();
1478 var dialog = openerp.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1479 title: _t('Confirm'),
1482 {text: _t("Cancel"), click: function() {
1484 $(this).dialog("close");
1487 {text: _t("Ok"), click: function() {
1488 self.on_confirmed().then(function() {
1491 $(this).dialog("close");
1496 return def.promise();
1498 return self.on_confirmed();
1501 if (!this.node.attrs.special) {
1502 return this.view.recursive_save().pipe(exec_action);
1504 return exec_action();
1507 on_confirmed: function() {
1510 var context = this.node.attrs.context;
1511 if (context && context.__ref) {
1512 context = new openerp.web.CompoundContext(context);
1513 context.set_eval_context(this._build_eval_context());
1516 return this.view.do_execute_action(
1517 _.extend({}, this.node.attrs, {context: context}),
1518 this.view.dataset, this.view.datarecord.id, function () {
1522 update_dom: function() {
1523 this._super.apply(this, arguments);
1524 this.check_disable();
1526 check_disable: function() {
1527 var disabled = (this.force_disabled || !this.view.is_interactible_record());
1528 this.$element.prop('disabled', disabled);
1529 this.$element.css('color', disabled ? 'grey' : '');
1534 * Interface implemented by the form view or any other object
1535 * able to provide the features necessary for the fields to work.
1540 * - view_content_has_changed : when the values of the fields have changed. When
1541 * this event is triggered all fields should reprocess their modifiers.
1543 openerp.web.form.FieldManagerInterface = {
1548 * Interface to be implemented by fields.
1551 * - readonly: boolean. If set to true the field should appear in readonly mode.
1552 * - force_readonly: boolean, When it is true, the field should always appear
1553 * in read only mode, no matter what the value of the "readonly" property can be.
1558 openerp.web.form.FieldInterface = {
1560 * Constructor takes 2 arguments:
1561 * - field_manager: Implements FieldManagerInterface
1562 * - node: the "<field>" node in json form
1564 init: function(field_manager, node) {},
1566 * Called by the form view to indicate the value of the field.
1568 * set_value() may return an object that can be passed to $.when() that represents the moment when
1569 * the field has finished all operations necessary before the user can effectively use the widget.
1571 * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1572 * regardless of any asynchronous operation currently running and the status of any promise that a
1573 * previous call to set_value() could have returned.
1575 * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1576 * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1577 * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1578 * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1579 * no information is ever given to know which format is used.
1581 set_value: function(value) {},
1583 * Get the current value of the widget.
1585 * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1586 * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1587 * For example if the field is marqued as "required", a call to get_value() can return false.
1589 * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1590 * return a defaut value according to the type of field.
1592 * This method is always assumed to perform synchronously, it can not return a promise.
1594 * If there was no user interaction to modify the value of the field, it is always assumed that
1595 * get_value() return the same semantic value than the one passed in the last call to set_value(),
1596 * altough the syntax can be different. This can be the case for type of fields that have a different
1597 * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1599 get_value: function() {},
1601 * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1604 set_input_id: function(id) {}
1608 * Abstract class for classes implementing FieldInterface.
1611 * - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1612 * the values of the "readonly" property and the "force_readonly" property on the field manager.
1615 openerp.web.form.AbstractField = openerp.web.form.Widget.extend(/** @lends openerp.web.form.AbstractField# */{
1617 * @constructs openerp.web.form.AbstractField
1618 * @extends openerp.web.form.Widget
1620 * @param field_manager
1623 init: function(field_manager, node) {
1624 this._super(field_manager, node);
1625 this.name = this.node.attrs.name;
1627 this.view.fields[this.name] = this;
1628 this.view.fields_order.push(this.name);
1629 this.field = this.view.fields_view.fields[this.name] || {};
1630 this.set({required: this.modifiers['required'] === true});
1631 this.invalid = this.dirty = false;
1633 // some events to make the property "effective_readonly" sync automatically with "readonly" and
1635 this.set({"readonly": this.modifiers['readonly'] === true});
1636 var test_effective_readonly = function() {
1637 this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1639 this.on("change:readonly", this, test_effective_readonly);
1640 this.on("change:force_readonly", this, test_effective_readonly);
1641 _.bind(test_effective_readonly, this)();
1644 this._super.apply(this, arguments);
1645 if (this.field.translate) {
1646 this.view.translatable_fields.push(this);
1647 this.$element.addClass('oe_form_field_translatable');
1648 this.$element.find('.oe_field_translate').click(this.on_translate);
1650 if (this.node.attrs.nolabel && openerp.connection.debug) {
1651 this.do_attach_tooltip(this, this.$label || this.$element);
1653 if (!this.disable_utility_classes) {
1654 var set_required = function() {
1655 this.$element.toggleClass('oe_form_required', this.get("required"));
1657 this.on("change:required", this, set_required);
1658 _.bind(set_required, this)();
1661 set_value: function(value) {
1663 this.invalid = false;
1665 this.on_value_changed();
1667 set_value_from_ui: function() {
1668 this.on_value_changed();
1670 on_value_changed: function() {
1672 on_translate: function() {
1673 this.view.open_translate_dialog(this);
1675 get_value: function() {
1678 is_valid: function() {
1679 return !this.invalid;
1681 is_dirty: function() {
1682 return this.dirty && !this.get("effective_readonly");
1684 update_dom: function(show_invalid) {
1685 this._super.apply(this, arguments);
1686 if (this.field.translate) {
1687 this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1689 if (!this.disable_utility_classes) {
1691 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1695 on_ui_change: function() {
1698 if (this.is_valid()) {
1699 this.set_value_from_ui();
1700 this.view.do_onchange(this);
1701 this.view.on_form_changed(true);
1702 this.view.do_notify_change();
1704 this.update_dom(true);
1707 validate: function() {
1708 this.invalid = false;
1710 focus: function($element) {
1712 setTimeout(function() {
1720 get_definition_options: function() {
1721 if (!this.definition_options) {
1722 var str = this.node.attrs.options || '{}';
1723 this.definition_options = JSON.parse(str);
1725 return this.definition_options;
1727 set_input_id: function(id) {
1728 this.id_for_label = id;
1733 * A mixin to apply on any field that has to completely re-render when its readonly state
1736 openerp.web.form.ReinitializeFieldMixin = {
1738 * Default implementation of start(), use it or call explicitly initialize_field().
1742 this.initialize_field();
1744 initialize_field: function() {
1745 this.on("change:effective_readonly", this, function() {
1746 this.destroy_content();
1747 this.renderElement();
1748 this.initialize_content();
1749 this.render_value();
1751 this.initialize_content();
1752 this.render_value();
1755 * Called to destroy anything that could have been created previously, called before a
1756 * re-initialization.
1758 destroy_content: function() {},
1760 * Called to initialize the content.
1762 initialize_content: function() {},
1764 * Called to render the value. Should also be explicitly called at the end of a set_value().
1766 render_value: function() {},
1769 openerp.web.form.FieldChar = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
1770 template: 'FieldChar',
1771 init: function (view, node) {
1772 this._super(view, node);
1773 this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1775 initialize_content: function() {
1776 this.$element.find('input').change(this.on_ui_change);
1778 set_value: function(value) {
1779 this._super.apply(this, arguments);
1780 this.render_value();
1782 render_value: function() {
1783 var show_value = openerp.web.format_value(this.value, this, '');
1784 if (!this.get("effective_readonly")) {
1785 this.$element.find('input').val(show_value);
1787 if (this.password) {
1788 show_value = new Array(show_value.length + 1).join('*');
1790 this.$element.text(show_value);
1793 set_value_from_ui: function() {
1794 this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1797 validate: function() {
1798 this.invalid = false;
1799 if (!this.get("effective_readonly")) {
1801 var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1802 this.invalid = this.get("required") && value === '';
1804 this.invalid = true;
1808 focus: function($element) {
1809 this._super($element || this.$element.find('input:first'));
1813 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1817 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1818 template: 'FieldEmail',
1819 initialize_content: function() {
1821 this.$element.find('button').click(this.on_button_clicked);
1823 render_value: function() {
1824 if (!this.get("effective_readonly")) {
1827 this.$element.find('a')
1828 .attr('href', 'mailto:' + this.value)
1832 on_button_clicked: function() {
1833 if (!this.value || !this.is_valid()) {
1834 this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1836 location.href = 'mailto:' + this.value;
1841 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1842 template: 'FieldUrl',
1843 initialize_content: function() {
1845 this.$element.find('button').click(this.on_button_clicked);
1847 render_value: function() {
1848 if (!this.get("effective_readonly")) {
1851 var tmp = this.value;
1852 var s = /(\w+):(.+)/.exec(tmp);
1854 tmp = "http://" + this.value;
1856 this.$element.find('a').attr('href', tmp).text(tmp);
1859 on_button_clicked: function() {
1861 this.do_warn("Resource error", "This resource is empty");
1863 window.open(this.value);
1868 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1869 is_field_number: true,
1870 init: function (view, node) {
1871 this._super(view, node);
1873 if (this.node.attrs.digits) {
1874 this.digits = py.eval(node.attrs.digits);
1876 this.digits = this.field.digits;
1879 set_value: function(value) {
1880 if (value === false || value === undefined) {
1881 // As in GTK client, floats default to 0
1884 this._super.apply(this, [value]);
1888 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1889 template: "web.datetimepicker",
1890 jqueryui_object: 'datetimepicker',
1891 type_of_date: "datetime",
1892 init: function(parent) {
1893 this._super(parent);
1894 this.name = parent.name;
1898 this.$input = this.$element.find('input.oe_datepicker_master');
1899 this.$input_picker = this.$element.find('input.oe_datepicker_container');
1900 this.$input.change(this.on_change);
1902 onSelect: this.on_picker_select,
1906 showButtonPanel: true
1908 this.$element.find('img.oe_datepicker_trigger').click(function() {
1909 if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1910 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1911 self.$input_picker.show();
1912 self.picker('show');
1913 self.$input_picker.hide();
1916 this.set_readonly(false);
1919 picker: function() {
1920 return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1922 on_picker_select: function(text, instance) {
1923 var date = this.picker('getDate');
1924 this.$input.val(date ? this.format_client(date) : '').change();
1926 set_value: function(value) {
1928 this.$input.val(value ? this.format_client(value) : '');
1930 get_value: function() {
1933 set_value_from_ui: function() {
1934 var value = this.$input.val() || false;
1935 this.value = this.parse_client(value);
1937 set_readonly: function(readonly) {
1938 this.readonly = readonly;
1939 this.$input.prop('readonly', this.readonly);
1940 this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1942 is_valid: function() {
1943 var value = this.$input.val();
1948 this.parse_client(value);
1955 parse_client: function(v) {
1956 return openerp.web.parse_value(v, {"widget": this.type_of_date});
1958 format_client: function(v) {
1959 return openerp.web.format_value(v, {"widget": this.type_of_date});
1961 on_change: function() {
1962 if (this.is_valid()) {
1963 this.set_value_from_ui();
1968 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1969 jqueryui_object: 'datepicker',
1970 type_of_date: "date"
1973 openerp.web.form.FieldDatetime = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
1974 template: "EmptyComponent",
1975 build_widget: function() {
1976 return new openerp.web.DateTimeWidget(this);
1978 destroy_content: function() {
1979 if (this.datewidget) {
1980 this.datewidget.destroy();
1981 this.datewidget = undefined;
1984 initialize_content: function() {
1985 if (!this.get("effective_readonly")) {
1986 this.datewidget = this.build_widget();
1987 this.datewidget.on_change.add_last(this.on_ui_change);
1988 this.datewidget.appendTo(this.$element);
1991 set_value: function(value) {
1993 this.render_value();
1995 render_value: function() {
1996 if (!this.get("effective_readonly")) {
1997 this.datewidget.set_value(this.value);
1999 this.$element.text(openerp.web.format_value(this.value, this, ''));
2002 get_value: function() {
2003 if (!this.get("effective_readonly")) {
2004 return this.datewidget.get_value();
2009 validate: function() {
2010 this.invalid = false;
2011 if (!this.get("effective_readonly")) {
2012 this.invalid = !this.datewidget.is_valid() || (this.get("required") && !this.datewidget.get_value());
2015 focus: function($element) {
2016 this._super($element || (this.datewidget && this.datewidget.$input));
2020 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
2021 build_widget: function() {
2022 return new openerp.web.DateWidget(this);
2026 openerp.web.form.FieldText = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
2027 template: 'FieldText',
2028 initialize_content: function() {
2029 this.$textarea = undefined;
2030 if (!this.get("effective_readonly")) {
2031 this.$textarea = this.$element.find('textarea').change(this.on_ui_change);
2032 this.resized = false;
2035 set_value: function(value) {
2036 this._super.apply(this, arguments);
2037 this.render_value();
2039 render_value: function() {
2040 var show_value = openerp.web.format_value(this.value, this, '');
2041 if (!this.get("effective_readonly")) {
2042 this.$textarea.val(show_value);
2043 if (!this.resized && this.view.options.resize_textareas) {
2044 this.do_resize(this.view.options.resize_textareas);
2045 this.resized = true;
2048 this.$element.text(show_value);
2051 set_value_from_ui: function() {
2052 this.value = openerp.web.parse_value(this.$textarea.val(), this);
2055 validate: function() {
2056 this.invalid = false;
2057 if (!this.get("effective_readonly")) {
2059 var value = openerp.web.parse_value(this.$textarea.val(), this, '');
2060 this.invalid = this.get("required") && value === '';
2062 this.invalid = true;
2066 focus: function($element) {
2067 this._super($element || this.$textarea);
2069 do_resize: function(max_height) {
2070 max_height = parseInt(max_height, 10);
2071 var $input = this.$textarea,
2072 $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2074 $div.text($input.val());
2075 _.each('font-family,font-size,white-space'.split(','), function(style) {
2076 $div.css(style, $input.css(style));
2078 $div.appendTo($('body'));
2079 new_height = $div.height();
2080 if (new_height < 90) {
2083 if (!isNaN(max_height) && new_height > max_height) {
2084 new_height = max_height;
2087 $input.height(new_height);
2090 this.resized = false;
2094 openerp.web.form.FieldBoolean = openerp.web.form.AbstractField.extend({
2095 template: 'FieldBoolean',
2097 this._super.apply(this, arguments);
2098 this.$checkbox = $("input", this.$element);
2099 this.$element.click(this.on_ui_change);
2100 var check_readonly = function() {
2101 this.$checkbox.prop('disabled', this.get("effective_readonly"));
2103 this.on("change:effective_readonly", this, check_readonly);
2104 _.bind(check_readonly, this)();
2106 set_value: function(value) {
2107 this._super.apply(this, arguments);
2108 this.$checkbox[0].checked = value;
2110 set_value_from_ui: function() {
2111 this.value = this.$checkbox.is(':checked');
2112 this._super.apply(this, arguments);
2114 focus: function($element) {
2115 this._super($element || this.$checkbox);
2119 openerp.web.form.FieldProgressBar = openerp.web.form.AbstractField.extend({
2120 template: 'FieldProgressBar',
2122 this._super.apply(this, arguments);
2123 this.$element.progressbar({
2125 disabled: this.get("effective_readonly")
2128 set_value: function(value) {
2129 this._super.apply(this, arguments);
2130 var show_value = Number(value);
2131 if (isNaN(show_value)) {
2134 var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
2135 this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2139 openerp.web.form.FieldTextXml = openerp.web.form.AbstractField.extend({
2140 // to replace view editor
2143 openerp.web.form.FieldSelection = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
2144 template: 'FieldSelection',
2145 init: function(view, node) {
2147 this._super(view, node);
2148 this.values = _.clone(this.field.selection);
2149 _.each(this.values, function(v, i) {
2150 if (v[0] === false && v[1] === '') {
2151 self.values.splice(i, 1);
2154 this.values.unshift([false, '']);
2156 initialize_content: function() {
2157 // Flag indicating whether we're in an event chain containing a change
2158 // event on the select, in order to know what to do on keyup[RETURN]:
2159 // * If the user presses [RETURN] as part of changing the value of a
2160 // selection, we should just let the value change and not let the
2161 // event broadcast further (e.g. to validating the current state of
2162 // the form in editable list view, which would lead to saving the
2163 // current row or switching to the next one)
2164 // * If the user presses [RETURN] with a select closed (side-effect:
2165 // also if the user opened the select and pressed [RETURN] without
2166 // changing the selected value), takes the action as validating the
2168 var ischanging = false;
2169 this.$element.find('select')
2170 .change(this.on_ui_change)
2171 .change(function () { ischanging = true; })
2172 .click(function () { ischanging = false; })
2173 .keyup(function (e) {
2174 if (e.which !== 13 || !ischanging) { return; }
2175 e.stopPropagation();
2179 set_value: function(value) {
2180 value = value === null ? false : value;
2181 value = value instanceof Array ? value[0] : value;
2183 this.render_value();
2185 render_value: function() {
2186 if (!this.get("effective_readonly")) {
2188 for (var i = 0, ii = this.values.length; i < ii; i++) {
2189 if (this.values[i][0] === this.value) index = i;
2191 this.$element.find('select')[0].selectedIndex = index;
2194 var option = _(this.values)
2195 .detect(function (record) { return record[0] === self.value; });
2196 this.$element.text(option ? option[1] : this.values[0][1]);
2199 set_value_from_ui: function() {
2200 this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
2203 validate: function() {
2204 if (this.get("effective_readonly")) {
2205 this.invalid = false;
2208 var value = this.values[this.$element.find('select')[0].selectedIndex];
2209 this.invalid = !(value && !(this.get("required") && value[0] === false));
2211 focus: function($element) {
2212 this._super($element || this.$element.find('select:first'));
2216 // jquery autocomplete tweak to allow html
2218 var proto = $.ui.autocomplete.prototype,
2219 initSource = proto._initSource;
2221 function filter( array, term ) {
2222 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2223 return $.grep( array, function(value) {
2224 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
2229 _initSource: function() {
2230 if ( this.options.html && $.isArray(this.options.source) ) {
2231 this.source = function( request, response ) {
2232 response( filter( this.options.source, request.term ) );
2235 initSource.call( this );
2239 _renderItem: function( ul, item) {
2240 return $( "<li></li>" )
2241 .data( "item.autocomplete", item )
2242 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2248 openerp.web.form.dialog = function(content, options) {
2249 options = _.extend({
2254 var dialog = new openerp.web.Dialog(null, options, content).open();
2255 return dialog.$element;
2258 openerp.web.form.FieldMany2One = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
2259 template: "FieldMany2One",
2260 init: function(view, node) {
2261 this._super(view, node);
2263 this.set({value: false});
2264 this.display_value = {};
2265 this.last_search = [];
2266 this.floating = false;
2267 this.inhibit_on_change = false;
2271 openerp.web.form.ReinitializeFieldMixin.start.call(this);
2272 this.on("change:value", this, function() {
2273 this.floating = false;
2274 this.render_value();
2275 if (! this.inhibit_on_change) {
2276 this.on_ui_change();
2280 initialize_content: function() {
2281 if (!this.get("effective_readonly"))
2282 this.render_editable();
2283 this.render_value();
2285 render_editable: function() {
2287 this.$input = this.$element.find("input");
2291 return "No element was selected, you should create or select one from the dropdown list.";
2297 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2298 this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2300 this.$follow_button.click(function() {
2301 if (!self.get('value')) {
2304 var pop = new openerp.web.form.FormOpenPopup(self.view);
2306 self.field.relation,
2308 self.build_context(),
2310 title: _t("Open: ") + (self.string || self.name)
2313 pop.on_write_completed.add_last(function() {
2314 self.display_value = {};
2315 self.render_value();
2319 // some behavior for input
2320 this.$input.keyup(function() {
2321 if (self.$input.val() === "") {
2322 self.set({value: false});
2324 self.floating = true;
2327 this.$drop_down.click(function() {
2328 if (self.$input.autocomplete("widget").is(":visible")) {
2329 self.$input.autocomplete("close");
2331 if (self.get("value") && ! self.floating) {
2332 self.$input.autocomplete("search", "");
2334 self.$input.autocomplete("search");
2336 self.$input.focus();
2339 var tip_def = $.Deferred();
2340 var untip_def = $.Deferred();
2341 var tip_delay = 200;
2342 var tip_duration = 3000;
2343 var anyoneLoosesFocus = function() {
2344 if (self.floating) {
2345 if (self.last_search.length > 0) {
2346 if (self.last_search[0][0] != self.get("value")) {
2347 self.display_value = {};
2348 self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2349 self.set({value: self.last_search[0][0]});
2351 self.render_value();
2354 self.set({value: false});
2357 if (! self.get("value")) {
2360 tip_def = $.Deferred();
2361 tip_def.then(function() {
2362 self.$input.tipsy("show");
2364 setTimeout(function() {
2367 untip_def = $.Deferred();
2368 untip_def.then(function() {
2369 self.$input.tipsy("hide");
2371 setTimeout(function() {untip_def.resolve();}, tip_duration);
2377 this.$input.focusout(anyoneLoosesFocus);
2379 var isSelecting = false;
2381 this.$input.autocomplete({
2382 source: function(req, resp) { self.get_search_result(req, resp); },
2383 select: function(event, ui) {
2387 self.display_value = {};
2388 self.display_value["" + item.id] = item.name;
2389 self.set({value: item.id});
2390 } else if (item.action) {
2391 self.floating = true;
2396 focus: function(e, ui) {
2400 close: anyoneLoosesFocus,
2404 this.$input.autocomplete("widget").addClass("openerp");
2405 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2406 this.$input.keyup(function(e) {
2407 if (e.which === 13) {
2409 e.stopPropagation();
2411 isSelecting = false;
2414 // autocomplete component content handling
2415 get_search_result: function(request, response) {
2416 var search_val = request.term;
2419 if (this.abort_last) {
2421 delete this.abort_last;
2423 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2425 dataset.name_search(search_val, self.build_domain(), 'ilike',
2426 this.limit + 1, function(data) {
2427 self.last_search = data;
2428 // possible selections for the m2o
2429 var values = _.map(data, function(x) {
2431 label: _.str.escapeHTML(x[1]),
2438 // search more... if more results that max
2439 if (values.length > self.limit) {
2440 values = values.slice(0, self.limit);
2441 values.push({label: _t("<em>Â Â Â Search More...</em>"), action: function() {
2442 dataset.name_search(search_val, self.build_domain(), 'ilike'
2443 , false, function(data) {
2444 self._search_create_popup("search", data);
2449 var raw_result = _(data.result).map(function(x) {return x[1];});
2450 if (search_val.length > 0 &&
2451 !_.include(raw_result, search_val) &&
2452 (!self.get("value") || self.floating)) {
2453 values.push({label: _.str.sprintf(_t('<em>Â Â Â Create "<strong>%s</strong>"</em>'),
2454 $('<span />').text(search_val).html()), action: function() {
2455 self._quick_create(search_val);
2459 values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
2460 self._search_create_popup("form", undefined, {"default_name": search_val});
2465 this.abort_last = dataset.abort_last;
2467 _quick_create: function(name) {
2469 var slow_create = function () {
2470 self._search_create_popup("form", undefined, {"default_name": name});
2472 if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2473 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2474 dataset.name_create(name, function(data) {
2475 self.display_value = {};
2476 self.display_value["" + data[0]] = data[1];
2477 self.set({value: data[0]});
2478 }).fail(function(error, event) {
2479 event.preventDefault();
2485 // all search/create popup handling
2486 _search_create_popup: function(view, ids, context) {
2488 var pop = new openerp.web.form.SelectCreatePopup(this);
2490 self.field.relation,
2492 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2493 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2495 disable_multiple_selection: true
2497 self.build_domain(),
2498 new openerp.web.CompoundContext(self.build_context(), context || {})
2500 pop.on_select_elements.add(function(element_ids) {
2501 self.set({value: element_ids[0]});
2504 render_value: function(no_recurse) {
2506 if (! this.get("value")) {
2507 this.display_string("");
2510 var display = this.display_value["" + this.get("value")];
2512 this.display_string(display);
2516 var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2517 dataset.name_get([self.get("value")], function(data) {
2518 self.display_value["" + self.get("value")] = data[0][1];
2519 self.render_value(true);
2523 display_string: function(str) {
2525 if (!this.get("effective_readonly")) {
2526 this.$input.val(str);
2528 this.$element.find('a')
2531 .click(function () {
2533 type: 'ir.actions.act_window',
2534 res_model: self.field.relation,
2535 res_id: self.get("value"),
2536 context: self.build_context(),
2537 views: [[false, 'form']],
2544 set_value: function(value) {
2546 if (value instanceof Array) {
2547 this.display_value = {};
2548 this.display_value["" + value[0]] = value[1];
2551 value = value || false;
2552 this.inhibit_on_change = true;
2553 this.set({value: value});
2554 this.inhibit_on_change = false;
2557 get_value: function() {
2558 return this.get("value");
2560 validate: function() {
2561 this.invalid = this.get("required") && ! this.get("value");
2563 focus: function ($element) {
2564 this._super($element || this.$input);
2569 # Values: (0, 0, { fields }) create
2570 # (1, ID, { fields }) update
2571 # (2, ID) remove (delete)
2572 # (3, ID) unlink one (target id or target of relation)
2574 # (5) unlink all (only valid for one2many)
2579 'create': function (values) {
2580 return [commands.CREATE, false, values];
2582 // (1, id, {values})
2584 'update': function (id, values) {
2585 return [commands.UPDATE, id, values];
2589 'delete': function (id) {
2590 return [commands.DELETE, id, false];
2592 // (3, id[, _]) removes relation, but not linked record itself
2594 'forget': function (id) {
2595 return [commands.FORGET, id, false];
2599 'link_to': function (id) {
2600 return [commands.LINK_TO, id, false];
2604 'delete_all': function () {
2605 return [5, false, false];
2607 // (6, _, ids) replaces all linked records with provided ids
2609 'replace_with': function (ids) {
2610 return [6, false, ids];
2613 openerp.web.form.FieldOne2Many = openerp.web.form.AbstractField.extend({
2614 multi_selection: false,
2615 disable_utility_classes: true,
2616 init: function(view, node) {
2617 this._super(view, node);
2618 lazy_build_o2m_kanban_view();
2619 this.is_loaded = $.Deferred();
2620 this.initial_is_loaded = this.is_loaded;
2621 this.is_setted = $.Deferred();
2622 this.form_last_update = $.Deferred();
2623 this.init_form_last_update = this.form_last_update;
2626 this._super.apply(this, arguments);
2630 this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2631 this.dataset.o2m = this;
2632 this.dataset.parent_view = this.view;
2633 this.dataset.child_name = this.name;
2634 //this.dataset.child_name =
2635 this.dataset.on_change.add_last(function() {
2636 self.trigger_on_change();
2639 this.is_setted.then(function() {
2642 this.is_loaded.then(function() {
2643 self.on("change:effective_readonly", self, function() {
2644 self.is_loaded = self.is_loaded.pipe(function() {
2645 self.viewmanager.destroy();
2646 return $.when(self.load_views()).then(function() {
2647 self.reload_current_view();
2653 trigger_on_change: function() {
2654 var tmp = this.doing_on_change;
2655 this.doing_on_change = true;
2656 this.on_ui_change();
2657 this.doing_on_change = tmp;
2659 load_views: function() {
2662 var modes = this.node.attrs.mode;
2663 modes = !!modes ? modes.split(",") : ["tree"];
2665 _.each(modes, function(mode) {
2668 view_type: mode == "tree" ? "list" : mode,
2669 options: { sidebar : false }
2671 if (self.field.views && self.field.views[mode]) {
2672 view.embedded_view = self.field.views[mode];
2674 if(view.view_type === "list") {
2675 view.options.selectable = self.multi_selection;
2676 if (self.get("effective_readonly")) {
2677 view.options.addable = null;
2678 view.options.deletable = null;
2679 view.options.isClarkGable = false;
2681 } else if (view.view_type === "form") {
2682 if (self.get("effective_readonly")) {
2683 view.view_type = 'form';
2685 view.options.not_interactible_on_create = true;
2691 this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2692 this.viewmanager.template = 'One2Many.viewmanager';
2693 this.viewmanager.fields_registry = openerp.web.views.extend({
2694 list: 'openerp.web.form.One2ManyListView',
2695 form: 'openerp.web.form.One2ManyFormView',
2696 page: 'openerp.web.PageView',
2697 kanban: 'openerp.web.form.One2ManyKanbanView',
2699 var once = $.Deferred().then(function() {
2700 self.init_form_last_update.resolve();
2702 var def = $.Deferred().then(function() {
2703 self.initial_is_loaded.resolve();
2705 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2706 controller.o2m = self;
2707 if (view_type == "list") {
2708 if (self.get("effective_readonly"))
2709 controller.set_editable(false);
2710 } else if (view_type == "form" || view_type == 'form') {
2711 if (view_type == 'page' || self.get("effective_readonly")) {
2712 $(".oe_form_buttons", controller.$element).children().remove();
2714 controller.on_record_loaded.add_last(function() {
2717 controller.on_pager_action.add_first(function() {
2718 self.save_any_view();
2720 } else if (view_type == "graph") {
2721 self.reload_current_view()
2725 this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2726 $.when(self.save_any_view()).then(function() {
2727 if(n_mode === "list")
2728 $.async_when().then(function() {self.reload_current_view();});
2731 this.is_setted.then(function() {
2732 $.async_when().then(function () {
2733 self.viewmanager.appendTo(self.$element);
2738 reload_current_view: function() {
2740 return self.is_loaded = self.is_loaded.pipe(function() {
2741 var active_view = self.viewmanager.active_view;
2742 var view = self.viewmanager.views[active_view].controller;
2743 if(active_view === "list") {
2744 return view.reload_content();
2745 } else if (active_view === "form" || active_view === 'page') {
2746 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2747 self.dataset.index = 0;
2749 var act = function() {
2750 return view.do_show();
2752 self.form_last_update = self.form_last_update.pipe(act, act);
2753 return self.form_last_update;
2754 } else if (view.do_search) {
2755 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2759 set_value: function(value) {
2760 value = value || [];
2762 this.dataset.reset_ids([]);
2763 if(value.length >= 1 && value[0] instanceof Array) {
2765 _.each(value, function(command) {
2766 var obj = {values: command[2]};
2767 switch (command[0]) {
2768 case commands.CREATE:
2769 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2771 self.dataset.to_create.push(obj);
2772 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2775 case commands.UPDATE:
2776 obj['id'] = command[1];
2777 self.dataset.to_write.push(obj);
2778 self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2781 case commands.DELETE:
2782 self.dataset.to_delete.push({id: command[1]});
2784 case commands.LINK_TO:
2785 ids.push(command[1]);
2787 case commands.DELETE_ALL:
2788 self.dataset.delete_all = true;
2793 this.dataset.set_ids(ids);
2794 } else if (value.length >= 1 && typeof(value[0]) === "object") {
2796 this.dataset.delete_all = true;
2797 _.each(value, function(command) {
2798 var obj = {values: command};
2799 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2801 self.dataset.to_create.push(obj);
2802 self.dataset.cache.push(_.clone(obj));
2806 this.dataset.set_ids(ids);
2809 this.dataset.reset_ids(value);
2811 if (this.dataset.index === null && this.dataset.ids.length > 0) {
2812 this.dataset.index = 0;
2814 self.is_setted.resolve();
2815 return self.reload_current_view();
2817 get_value: function() {
2821 this.save_any_view();
2822 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2823 val = val.concat(_.map(this.dataset.ids, function(id) {
2824 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2826 return commands.create(alter_order.values);
2828 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2830 return commands.update(alter_order.id, alter_order.values);
2832 return commands.link_to(id);
2834 return val.concat(_.map(
2835 this.dataset.to_delete, function(x) {
2836 return commands['delete'](x.id);}));
2838 save_any_view: function() {
2839 if (this.doing_on_change)
2841 return this.session.synchronized_mode(_.bind(function() {
2842 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2843 this.viewmanager.views[this.viewmanager.active_view] &&
2844 this.viewmanager.views[this.viewmanager.active_view].controller) {
2845 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2846 if (this.viewmanager.active_view === "form") {
2847 if (!view.is_initialized.isResolved()) {
2850 var res = $.when(view.do_save());
2851 if (!res.isResolved() && !res.isRejected()) {
2852 console.warn("Asynchronous get_value() is not supported in form view.");
2855 } else if (this.viewmanager.active_view === "list") {
2856 var res = $.when(view.ensure_saved());
2857 if (!res.isResolved() && !res.isRejected()) {
2858 console.warn("Asynchronous get_value() is not supported in list view.");
2866 is_valid: function() {
2868 return this._super();
2870 validate: function() {
2871 this.invalid = false;
2872 if (!this.viewmanager.views[this.viewmanager.active_view])
2874 var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2875 if (this.viewmanager.active_view === "form") {
2876 for (var f in view.fields) {
2878 if (!f.is_valid()) {
2879 this.invalid = true;
2885 is_dirty: function() {
2886 this.save_any_view();
2887 return this._super();
2891 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2892 get_context: function() {
2893 this.context = this.o2m.build_context([this.o2m.name]);
2894 return this.context;
2898 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2899 _template: 'One2Many.listview',
2900 do_add_record: function () {
2901 if (this.options.editable) {
2902 this._super.apply(this, arguments);
2905 var pop = new openerp.web.form.SelectCreatePopup(this);
2906 pop.on_default_get.add(self.dataset.on_default_get);
2908 self.o2m.field.relation,
2910 title: _t("Create: ") + self.name,
2911 initial_view: "form",
2912 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2913 create_function: function(data, callback, error_callback) {
2914 return self.o2m.dataset.create(data).then(function(r) {
2915 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2916 self.o2m.dataset.on_change();
2917 }).then(callback, error_callback);
2919 read_function: function() {
2920 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2922 parent_view: self.o2m.view,
2923 child_name: self.o2m.name,
2924 form_view_options: {'not_interactible_on_create':true}
2926 self.o2m.build_domain(),
2927 self.o2m.build_context()
2929 pop.on_select_elements.add_last(function() {
2930 self.o2m.reload_current_view();
2934 do_activate_record: function(index, id) {
2936 var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2937 pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2938 title: _t("Open: ") + self.name,
2940 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2941 parent_view: self.o2m.view,
2942 child_name: self.o2m.name,
2943 read_function: function() {
2944 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2946 form_view_options: {'not_interactible_on_create':true},
2947 readonly: self.o2m.get("effective_readonly")
2949 pop.on_write.add(function(id, data) {
2950 self.o2m.dataset.write(id, data, {}, function(r) {
2951 self.o2m.reload_current_view();
2955 do_button_action: function (name, id, callback) {
2957 var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2958 return this._super(name, id, _.bind(def.resolve, def));
2962 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2963 form_template: 'One2Many.formview',
2964 on_loaded: function(data) {
2967 this.$form_header.find('button.oe_form_button_create').click(function() {
2968 self.do_save().then(self.on_button_new);
2971 do_notify_change: function() {
2972 if (this.dataset.parent_view) {
2973 this.dataset.parent_view.do_notify_change();
2975 this._super.apply(this, arguments);
2980 var lazy_build_o2m_kanban_view = function() {
2981 if (! openerp.web_kanban || openerp.web.form.One2ManyKanbanView)
2983 openerp.web.form.One2ManyKanbanView = openerp.web_kanban.KanbanView.extend({
2984 open_record: function(id) {
2986 var pop = new openerp.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();
3010 * TODO niv: clean those deferred stuff, it could be better
3012 openerp.web.form.FieldMany2Many = openerp.web.form.AbstractField.extend({
3013 multi_selection: false,
3014 disable_utility_classes: true,
3015 init: function(view, node) {
3016 this._super(view, node);
3017 this.is_loaded = $.Deferred();
3018 this.initial_is_loaded = this.is_loaded;
3019 this.is_setted = $.Deferred();
3022 this._super.apply(this, arguments);
3026 this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
3027 this.dataset.m2m = this;
3028 this.dataset.on_unlink.add_last(function(ids) {
3029 self.on_ui_change();
3032 this.is_setted.then(function() {
3035 this.is_loaded.then(function() {
3036 self.on("change:effective_readonly", self, function() {
3037 self.is_loaded = self.is_loaded.pipe(function() {
3038 self.list_view.destroy();
3039 return $.when(self.load_view()).then(function() {
3040 self.reload_content();
3046 set_value: function(value) {
3047 value = value || [];
3048 if (value.length >= 1 && value[0] instanceof Array) {
3049 value = value[0][2];
3052 this.dataset.set_ids(value);
3054 self.reload_content();
3055 this.is_setted.resolve();
3057 get_value: function() {
3058 return [commands.replace_with(this.dataset.ids)];
3060 validate: function() {
3061 this.invalid = false;
3063 load_view: function() {
3065 this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
3066 'addable': self.get("effective_readonly") ? null : _t("Add"),
3067 'deletable': self.get("effective_readonly") ? false : true,
3068 'selectable': self.multi_selection,
3069 'isClarkGable': self.get("effective_readonly") ? false : true
3071 var embedded = (this.field.views || {}).tree;
3073 this.list_view.set_embedded_view(embedded);
3075 this.list_view.m2m_field = this;
3076 var loaded = $.Deferred();
3077 this.list_view.on_loaded.add_last(function() {
3078 self.initial_is_loaded.resolve();
3081 $.async_when().then(function () {
3082 self.list_view.appendTo(self.$element);
3086 reload_content: function() {
3088 this.is_loaded = this.is_loaded.pipe(function() {
3089 return self.list_view.reload_content();
3094 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
3095 get_context: function() {
3096 this.context = this.m2m.build_context();
3097 return this.context;
3103 * @extends openerp.web.ListView
3105 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
3106 do_add_record: function () {
3107 var pop = new openerp.web.form.SelectCreatePopup(this);
3111 title: _t("Add: ") + this.name
3113 new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3114 this.m2m_field.build_context()
3117 pop.on_select_elements.add(function(element_ids) {
3118 _.each(element_ids, function(one_id) {
3119 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3120 self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3121 self.m2m_field.on_ui_change();
3122 self.reload_content();
3127 do_activate_record: function(index, id) {
3129 var pop = new openerp.web.form.FormOpenPopup(this);
3130 pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3131 title: _t("Open: ") + this.name,
3132 readonly: this.getParent().get("effective_readonly")
3134 pop.on_write_completed.add_last(function() {
3135 self.reload_content();
3142 * @extends openerp.web.OldWidget
3144 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
3145 template: "SelectCreatePopup",
3149 * - initial_view: form or search (default search)
3150 * - disable_multiple_selection
3151 * - alternative_form_view
3152 * - create_function (defaults to a naive saving behavior)
3155 * - form_view_options
3156 * - list_view_options
3159 select_element: function(model, options, domain, context) {
3162 this.domain = domain || [];
3163 this.context = context || {};
3164 this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
3165 return self.create_row.apply(self, arguments);
3166 }, read_function: null});
3167 this.initial_ids = this.options.initial_ids;
3168 this.created_elements = [];
3169 this.renderElement();
3170 openerp.web.form.dialog(this.$element, {
3174 title: options.title || ""
3181 this.dataset = new openerp.web.ProxyDataSet(this, this.model,
3183 this.dataset.create_function = function() {
3184 return self.options.create_function.apply(null, arguments).then(function(r) {
3185 self.created_elements.push(r.result);
3188 this.dataset.write_function = function() {
3189 return self.write_row.apply(self, arguments);
3191 this.dataset.read_function = this.options.read_function;
3192 this.dataset.parent_view = this.options.parent_view;
3193 this.dataset.child_name = this.options.child_name;
3194 this.dataset.on_default_get.add(this.on_default_get);
3195 if (this.options.initial_view == "search") {
3196 self.rpc('/web/session/eval_domain_and_context', {
3198 contexts: [this.context]
3199 }, function (results) {
3200 var search_defaults = {};
3201 _.each(results.context, function (value, key) {
3202 var match = /^search_default_(.*)$/.exec(key);
3204 search_defaults[match[1]] = value;
3207 self.setup_search_view(search_defaults);
3214 this.$element.dialog('close');
3217 setup_search_view: function(search_defaults) {
3219 if (this.searchview) {
3220 this.searchview.destroy();
3222 this.searchview = new openerp.web.SearchView(this,
3223 this.dataset, false, search_defaults);
3224 this.searchview.on_search.add(function(domains, contexts, groupbys) {
3225 if (self.initial_ids) {
3226 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3227 contexts, groupbys);
3228 self.initial_ids = undefined;
3230 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3233 this.searchview.on_loaded.add_last(function () {
3234 self.view_list = new openerp.web.form.SelectCreateListView(self,
3235 self.dataset, false,
3236 _.extend({'deletable': false,
3237 'selectable': !self.options.disable_multiple_selection
3238 }, self.options.list_view_options || {}));
3239 self.view_list.popup = self;
3240 self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3241 self.view_list.do_show();
3242 }).pipe(function() {
3243 self.searchview.do_search();
3245 self.view_list.on_loaded.add_last(function() {
3246 var $buttons = self.view_list.$element.find(".oe-actions");
3247 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3248 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3249 $cbutton.click(function() {
3252 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3253 if(self.options.disable_multiple_selection) {
3256 $sbutton.click(function() {
3257 self.on_select_elements(self.selected_ids);
3262 this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3264 do_search: function(domains, contexts, groupbys) {
3266 this.rpc('/web/session/eval_domain_and_context', {
3267 domains: domains || [],
3268 contexts: contexts || [],
3269 group_by_seq: groupbys || []
3270 }, function (results) {
3271 self.view_list.do_search(results.domain, results.context, results.group_by);
3274 create_row: function() {
3276 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3277 wdataset.parent_view = this.options.parent_view;
3278 wdataset.child_name = this.options.child_name;
3279 return wdataset.create.apply(wdataset, arguments);
3281 write_row: function() {
3283 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3284 wdataset.parent_view = this.options.parent_view;
3285 wdataset.child_name = this.options.child_name;
3286 return wdataset.write.apply(wdataset, arguments);
3288 on_select_elements: function(element_ids) {
3290 on_click_element: function(ids) {
3291 this.selected_ids = ids || [];
3292 if(this.selected_ids.length > 0) {
3293 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3295 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3298 new_object: function() {
3300 if (this.searchview) {
3301 this.searchview.hide();
3303 if (this.view_list) {
3304 this.view_list.$element.hide();
3306 this.dataset.index = null;
3307 this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
3308 if (this.options.alternative_form_view) {
3309 this.view_form.set_embedded_view(this.options.alternative_form_view);
3311 this.view_form.appendTo(this.$element.find(".oe-select-create-popup-view-form"));
3312 this.view_form.on_loaded.add_last(function() {
3313 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3314 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
3315 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
3316 $nbutton.click(function() {
3317 $.when(self.view_form.do_save()).then(function() {
3318 self.view_form.reload_mutex.exec(function() {
3319 self.view_form.on_button_new();
3323 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
3324 $nbutton.click(function() {
3325 $.when(self.view_form.do_save()).then(function() {
3326 self.view_form.reload_mutex.exec(function() {
3331 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
3332 $cbutton.click(function() {
3336 this.view_form.do_show();
3338 check_exit: function() {
3339 if (this.created_elements.length > 0) {
3340 this.on_select_elements(this.created_elements);
3344 on_default_get: function(res) {}
3347 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
3348 do_add_record: function () {
3349 this.popup.new_object();
3351 select_record: function(index) {
3352 this.popup.on_select_elements([this.dataset.ids[index]]);
3353 this.popup.destroy();
3355 do_select: function(ids, records) {
3356 this._super(ids, records);
3357 this.popup.on_click_element(ids);
3363 * @extends openerp.web.OldWidget
3365 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
3366 template: "FormOpenPopup",
3369 * - alternative_form_view
3370 * - auto_write (default true)
3374 * - form_view_options
3377 show_element: function(model, row_id, context, options) {
3379 this.row_id = row_id;
3380 this.context = context || {};
3381 this.options = _.defaults(options || {}, {"auto_write": true});
3382 this.renderElement();
3383 openerp.web.dialog(this.$element, {
3384 title: options.title || '',
3393 this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3394 this.dataset.fop = this;
3395 this.dataset.ids = [this.row_id];
3396 this.dataset.index = 0;
3397 this.dataset.parent_view = this.options.parent_view;
3398 this.dataset.child_name = this.options.child_name;
3399 this.setup_form_view();
3401 on_write: function(id, data) {
3402 if (!this.options.auto_write)
3405 var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3406 wdataset.parent_view = this.options.parent_view;
3407 wdataset.child_name = this.options.child_name;
3408 wdataset.write(id, data, {}, function(r) {
3409 self.on_write_completed();
3412 on_write_completed: function() {},
3413 setup_form_view: function() {
3415 var FormClass = this.options.readonly
3416 ? openerp.web.views.get_object('page')
3417 : openerp.web.views.get_object('form');
3418 this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3419 if (this.options.alternative_form_view) {
3420 this.view_form.set_embedded_view(this.options.alternative_form_view);
3422 this.view_form.appendTo(this.$element.find(".oe-form-open-popup-form-view"));
3423 this.view_form.on_loaded.add_last(function() {
3424 var $buttons = self.view_form.$element.find(".oe_form_buttons");
3425 $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3426 var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3427 $nbutton.click(function() {
3428 self.view_form.do_save().then(function() {
3432 var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3433 $cbutton.click(function() {
3436 if (self.options.readonly) {
3438 $cbutton.text(_t("Close"));
3440 self.view_form.do_show();
3442 this.dataset.on_write.add(this.on_write);
3446 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3447 read_ids: function() {
3448 if (this.fop.options.read_function) {
3449 return this.fop.options.read_function.apply(null, arguments);
3451 return this._super.apply(this, arguments);
3456 openerp.web.form.FieldReference = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
3457 template: 'FieldReference',
3458 init: function(view, node) {
3459 this._super(view, node);
3460 this.fields_view = {
3463 selection: view.fields_view.fields[this.name].selection
3470 this.get_fields_values = view.get_fields_values;
3471 this.get_selected_ids = view.get_selected_ids;
3472 this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3473 this.dataset = this.view.dataset;
3474 this.view_id = 'reference_' + _.uniqueId();
3476 this.fields_order = [];
3477 this.reference_ready = true;
3479 on_nop: function() {
3481 on_selection_changed: function() {
3482 if (this.reference_ready) {
3483 var sel = this.selection.get_value();
3484 this.m2o.field.relation = sel;
3485 this.m2o.set_value(null);
3486 this.m2o.$element.toggle(sel !== false);
3489 destroy_content: function() {
3490 if (this.selection) {
3491 this.selection.destroy();
3492 this.selection = undefined;
3496 this.m2o = undefined;
3499 initialize_content: function() {
3500 this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3504 this.selection.set({readonly: this.get('effective_readonly')});
3505 this.selection.on_value_changed.add_last(this.on_selection_changed);
3506 this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3507 this.selection.renderElement();
3508 this.selection.start();
3510 this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3514 this.m2o.set({"readonly": this.get("effective_readonly")});
3515 this.m2o.on_ui_change.add_last(this.on_ui_change);
3516 this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3517 this.m2o.renderElement();
3520 is_valid: function() {
3521 return this.get("required") === false || typeof(this.get_value()) === 'string';
3523 is_dirty: function() {
3524 return this.selection.is_dirty() || this.m2o.is_dirty();
3526 set_value: function(value) {
3528 this.render_value();
3530 render_value: function() {
3531 this.reference_ready = false;
3532 var vals = [], sel_val, m2o_val;
3533 if (typeof(this.value) === 'string') {
3534 vals = this.value.split(',');
3536 sel_val = vals[0] || false;
3537 m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3538 if (!this.get("effective_readonly")) {
3539 this.selection.set_value(sel_val);
3541 this.m2o.field.relation = sel_val;
3542 this.m2o.set_value(m2o_val);
3543 this.m2o.$element.toggle(sel_val !== false);
3544 this.reference_ready = true;
3546 get_value: function() {
3547 var model = this.selection.get_value(),
3548 id = this.m2o.get_value();
3549 if (typeof(model) === 'string' && typeof(id) === 'number') {
3550 return model + ',' + id;
3557 openerp.web.form.FieldBinary = openerp.web.form.AbstractField.extend(_.extend({}, openerp.web.form.ReinitializeFieldMixin, {
3558 init: function(view, node) {
3559 this._super(view, node);
3560 this.iframe = this.element_id + '_iframe';
3561 this.binary_value = false;
3563 initialize_content: function() {
3564 this.$element.find('input.oe-binary-file').change(this.on_file_change);
3565 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3566 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3568 human_filesize : function(size) {
3569 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3571 while (size >= 1024) {
3575 return size.toFixed(2) + ' ' + units[i];
3577 on_file_change: function(e) {
3578 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3579 // http://www.html5rocks.com/tutorials/file/dndfiles/
3580 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3581 window[this.iframe] = this.on_file_uploaded;
3582 if ($(e.target).val() != '') {
3583 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3584 this.$element.find('form.oe-binary-form').submit();
3585 this.$element.find('.oe-binary-progress').show();
3586 this.$element.find('.oe-binary').hide();
3589 on_file_uploaded: function(size, name, content_type, file_base64) {
3590 delete(window[this.iframe]);
3591 if (size === false) {
3592 this.do_warn("File Upload", "There was a problem while uploading your file");
3593 // TODO: use openerp web crashmanager
3594 console.warn("Error while uploading file : ", name);
3596 this.on_file_uploaded_and_valid.apply(this, arguments);
3597 this.on_ui_change();
3599 this.$element.find('.oe-binary-progress').hide();
3600 this.$element.find('.oe-binary').show();
3602 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3604 on_save_as: function() {
3606 this.session.get_file({
3607 url: '/web/binary/saveas_ajax',
3608 data: {data: JSON.stringify({
3609 model: this.view.dataset.model,
3610 id: (this.view.datarecord.id || ''),
3612 filename_field: (this.node.attrs.filename || ''),
3613 context: this.view.dataset.get_context()
3615 complete: $.unblockUI,
3616 error: openerp.webclient.crashmanager.on_rpc_error
3619 on_clear: function() {
3620 if (this.value !== false) {
3622 this.binary_value = false;
3623 this.on_ui_change();
3629 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3630 template: 'FieldBinaryFile',
3631 initialize_content: function() {
3633 if (this.get("effective_readonly")) {
3635 this.$element.find('a').click(function() {
3643 set_value: function(value) {
3644 this._super.apply(this, arguments);
3645 this.render_value();
3647 render_value: function() {
3648 if (!this.get("effective_readonly")) {
3650 if (this.node.attrs.filename) {
3651 show_value = this.view.datarecord[this.node.attrs.filename] || '';
3653 show_value = (this.value != null && this.value !== false) ? this.value : '';
3655 this.$element.find('input').eq(0).val(show_value);
3657 this.$element.find('a').show(!!this.value);
3659 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
3660 this.$element.find('a').text(show_value);
3664 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3665 this.value = file_base64;
3666 this.binary_value = true;
3667 var show_value = name + " (" + this.human_filesize(size) + ")";
3668 this.$element.find('input').eq(0).val(show_value);
3669 this.set_filename(name);
3671 set_filename: function(value) {
3672 var filename = this.node.attrs.filename;
3673 if (this.view.fields[filename]) {
3674 this.view.fields[filename].set_value(value);
3675 this.view.fields[filename].on_ui_change();
3678 on_clear: function() {
3679 this._super.apply(this, arguments);
3680 this.$element.find('input').eq(0).val('');
3681 this.set_filename('');
3685 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3686 template: 'FieldBinaryImage',
3687 initialize_content: function() {
3689 this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
3690 if (!this.get("effective_readonly"))
3691 this.$element.find('.oe-binary').show();
3693 this.$element.find('.oe-binary').hide();
3695 set_value: function(value) {
3696 this._super.apply(this, arguments);
3697 this.render_value();
3699 render_value: function() {
3701 if (this.value && this.value.substr(0, 10).indexOf(' ') == -1) {
3702 url = 'data:image/png;base64,' + this.value;
3703 } else if (this.value) {
3704 url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3705 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3707 url = "/web/static/src/img/placeholder.png";
3709 var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
3710 this.$placeholder.html(rendered);
3712 on_file_change: function() {
3713 this.render_value();
3714 this._super.apply(this, arguments);
3716 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3717 this.value = file_base64;
3718 this.binary_value = true;
3719 this.render_value();
3721 on_clear: function() {
3722 this._super.apply(this, arguments);
3723 this.render_value();
3727 openerp.web.form.FieldStatus = openerp.web.form.AbstractField.extend({
3728 template: "EmptyComponent",
3731 this.selected_value = null;
3735 set_value: function(value) {
3737 this.selected_value = value;
3741 render_list: function() {
3743 var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3744 function(x) { return _.str.trim(x); });
3745 shown = _.select(shown, function(x) { return x.length > 0; });
3747 if (shown.length == 0) {
3748 this.to_show = this.field.selection;
3750 this.to_show = _.select(this.field.selection, function(x) {
3751 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3755 var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3756 this.$element.html(content);
3758 var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3759 var color = colors[this.selected_value];
3761 var elem = this.$element.find("li.oe-arrow-list-selected span");
3762 elem.css("border-color", color);
3763 if (this.check_white(color))
3764 elem.css("color", "white");
3765 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3766 elem.css("border-left-color", "rgba(0,0,0,0)");
3767 elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3768 elem.css("border-color", "rgba(0,0,0,0)");
3769 elem.css("border-left-color", color);
3772 check_white: function(color) {
3773 var div = $("<div></div>");
3774 div.css("display", "none");
3775 div.css("color", color);
3776 div.appendTo($("body"));
3777 var ncolor = div.css("color");
3779 var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3783 var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3784 var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3793 * Registry of form widgets, called by :js:`openerp.web.FormView`
3795 openerp.web.form.widgets = new openerp.web.Registry({
3796 'char' : 'openerp.web.form.FieldChar',
3797 'id' : 'openerp.web.form.FieldID',
3798 'email' : 'openerp.web.form.FieldEmail',
3799 'url' : 'openerp.web.form.FieldUrl',
3800 'text' : 'openerp.web.form.FieldText',
3801 'date' : 'openerp.web.form.FieldDate',
3802 'datetime' : 'openerp.web.form.FieldDatetime',
3803 'selection' : 'openerp.web.form.FieldSelection',
3804 'many2one' : 'openerp.web.form.FieldMany2One',
3805 'many2many' : 'openerp.web.form.FieldMany2Many',
3806 'one2many' : 'openerp.web.form.FieldOne2Many',
3807 'one2many_list' : 'openerp.web.form.FieldOne2Many',
3808 'reference' : 'openerp.web.form.FieldReference',
3809 'boolean' : 'openerp.web.form.FieldBoolean',
3810 'float' : 'openerp.web.form.FieldFloat',
3811 'integer': 'openerp.web.form.FieldFloat',
3812 'float_time': 'openerp.web.form.FieldFloat',
3813 'progressbar': 'openerp.web.form.FieldProgressBar',
3814 'image': 'openerp.web.form.FieldBinaryImage',
3815 'binary': 'openerp.web.form.FieldBinaryFile',
3816 'statusbar': 'openerp.web.form.FieldStatus'
3819 openerp.web.form.tags = new openerp.web.Registry({
3820 'button' : 'openerp.web.form.WidgetButton',
3825 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: