1 openerp.base.form = function (openerp) {
3 openerp.base.views.add('form', 'openerp.base.FormView');
4 openerp.base.FormView = openerp.base.View.extend( /** @lends openerp.base.FormView# */{
6 * Indicates that this view is not searchable, and thus that no search
7 * view should be displayed (if there is one active).
13 * @param {openerp.base.Session} session the current openerp session
14 * @param {String} element_id this view's root element id
15 * @param {openerp.base.DataSet} dataset the dataset this view will work with
16 * @param {String} view_id the identifier of the OpenERP view object
18 * @property {openerp.base.Registry} registry=openerp.base.form.widgets widgets registry for this form view instance
20 init: function(view_manager, session, element_id, dataset, view_id) {
21 this._super(session, element_id);
22 this.view_manager = view_manager || new openerp.base.NullViewManager();
23 this.dataset = dataset;
24 this.model = dataset.model;
25 this.view_id = view_id;
26 this.fields_view = {};
28 this.widgets_counter = 0;
32 this.show_invalid = true;
34 this.flags = this.view_manager.flags || {};
35 this.default_focus_field = null;
36 this.default_focus_button = null;
37 this.registry = openerp.base.form.widgets;
38 this.has_been_loaded = $.Deferred();
39 this.$form_header = null;
42 //this.log('Starting FormView '+this.model+this.view_id)
43 if (this.embedded_view) {
44 return $.Deferred().then(this.on_loaded).resolve({fields_view: this.embedded_view});
46 var context = new openerp.base.CompoundContext(this.dataset.context);
47 if (this.view_manager.action && this.view_manager.action.context) {
48 context.add(this.view_manager.action.context);
50 return this.rpc("/base/formview/load", {"model": this.model, "view_id": this.view_id,
51 toolbar:!!this.flags.sidebar, context: context}, this.on_loaded);
54 on_loaded: function(data) {
56 this.fields_view = data.fields_view;
57 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
59 this.$element.html(QWeb.render(this.template, { 'frame': frame, 'view': this }));
60 _.each(this.widgets, function(w) {
63 this.$form_header = this.$element.find('#' + this.element_id + '_header');
64 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
65 var action = $(this).data('pager-action');
66 self.on_pager_action(action);
69 this.$form_header.find('button.oe_form_button_save').click(this.do_save);
70 this.$form_header.find('button.oe_form_button_save_edit').click(this.do_save_edit);
71 this.$form_header.find('button.oe_form_button_cancel').click(this.do_cancel);
72 this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
74 this.view_manager.sidebar.set_toolbar(data.fields_view.toolbar);
75 this.has_been_loaded.resolve();
77 do_show: function () {
79 if (this.dataset.index === null) {
80 // null index means we should start a new record
83 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
86 this.view_manager.sidebar.do_refresh(true);
88 do_hide: function () {
91 on_record_loaded: function(record) {
93 throw("Form: No record received");
96 this.$form_header.find('.oe_form_on_create').show();
97 this.$form_header.find('.oe_form_on_update').hide();
98 this.$form_header.find('button.oe_form_button_new').hide();
100 this.$form_header.find('.oe_form_on_create').hide();
101 this.$form_header.find('.oe_form_on_update').show();
102 this.$form_header.find('button.oe_form_button_new').show();
104 this.touched = false;
105 this.datarecord = record;
106 for (var f in this.fields) {
107 var field = this.fields[f];
108 field.touched = false;
109 field.set_value(this.datarecord[f] || false);
113 // New record: Second pass in order to trigger the onchanges
115 this.show_invalid = false;
116 for (var f in record) {
117 var field = this.fields[f];
119 field.touched = true;
120 this.do_onchange(field);
124 this.on_form_changed();
125 this.show_invalid = this.ready = true;
126 this.do_update_pager(record.id == null);
127 this.do_update_sidebar();
128 if (this.default_focus_field) {
129 this.default_focus_field.focus();
132 on_form_changed: function() {
133 for (var w in this.widgets) {
139 on_pager_action: function(action) {
142 this.dataset.index = 0;
145 this.dataset.previous();
151 this.dataset.index = this.dataset.ids.length - 1;
156 do_update_pager: function(hide_index) {
157 var $pager = this.$element.find('#' + this.element_id + '_header div.oe_form_pager');
158 var index = hide_index ? '-' : this.dataset.index + 1;
159 $pager.find('span.oe_pager_index').html(index);
160 $pager.find('span.oe_pager_count').html(this.dataset.count);
162 do_onchange: function(widget, processed) {
163 processed = processed || [];
164 if (widget.node.attrs.on_change) {
167 var onchange = _.trim(widget.node.attrs.on_change);
168 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
169 console.log("Onchange triggered for field '%s' -> %s", widget.name, onchange);
171 var method = call[1], args = [];
172 var argument_replacement = {
177 _.each(call[2].split(','), function(a) {
178 var field = _.trim(a);
179 if (field in argument_replacement) {
180 args.push(argument_replacement[field]);
181 } else if (self.fields[field]) {
182 var value = self.fields[field].get_value();
183 args.push(value == null ? false : value);
186 self.log("warning : on_change can't find field " + field, onchange);
190 url: '/base/dataset/call',
193 return this.rpc(ajax, {
194 model: this.dataset.model,
196 args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args)
197 }, function(response) {
198 self.on_processed_onchange(response, processed);
201 this.log("Wrong on_change format", on_change);
205 on_processed_onchange: function(response, processed) {
206 var result = response.result;
208 console.log(" |-> Onchange Response :", result.value);
209 for (var f in result.value) {
210 var field = this.fields[f];
212 var value = result.value[f];
213 processed.push(field.name);
214 if (field.get_value() != value) {
215 console.log(" |-> Onchange Action : change '%s' value from '%s' to '%s'", field.name, field.get_value(), value);
216 field.set_value(value);
217 if (_.indexOf(processed, field.name) < 0) {
218 this.do_onchange(field, processed);
222 this.log("warning : on_processed_onchange can't find field " + field, result);
225 this.on_form_changed();
227 if (result.warning) {
228 $(QWeb.render("DialogWarning", result.warning)).dialog({
232 $(this).dialog("close");
242 on_button_new: function() {
244 var context = new openerp.base.CompoundContext(this.dataset.context);
245 if (this.view_manager.action && this.view_manager.action.context) {
246 context.add(this.view_manager.action.context);
248 $.when(this.has_been_loaded).then(function() {
249 self.dataset.default_get(_.keys(self.fields_view.fields), context, function(result) {
250 self.on_record_loaded(result.result);
255 * Triggers saving the form's record. Chooses between creating a new
256 * record or saving an existing one depending on whether the record
257 * already has an id property.
259 * @param {Function} success callback on save success
260 * @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)
262 do_save: function(success, prepend_on_create) {
269 first_invalid_field = null;
270 for (var f in this.fields) {
275 if (!first_invalid_field) {
276 first_invalid_field = f;
278 } else if (f.touched) {
279 values[f.name] = f.get_value();
283 first_invalid_field.focus();
287 this.log("About to save", values);
288 if (!this.datarecord.id) {
289 this.dataset.create(values, function(r) {
290 self.on_created(r, success, prepend_on_create);
293 this.dataset.write(this.datarecord.id, values, function(r) {
294 self.on_saved(r, success);
300 do_save_edit: function() {
302 //this.switch_readonly(); Use promises
304 switch_readonly: function() {
306 switch_editable: function() {
308 on_invalid: function() {
310 _.each(this.fields, function(f) {
312 msg += "<li>" + f.string + "</li>";
316 this.notification.warn("The following fields are invalid :", msg);
318 on_saved: function(r, success) {
320 this.notification.warn("Record not saved", "Problem while saving record.");
322 this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
330 * Updates the form' dataset to contain the new record:
332 * * Adds the newly created record to the current dataset (at the end by
334 * * Selects that record (sets the dataset's index to point to the new
336 * * Updates the pager and sidebar displays
339 * @param {Function} success callback to execute after having updated the dataset
340 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
342 on_created: function(r, success, prepend_on_create) {
344 this.notification.warn("Record not created", "Problem while creating record.");
346 this.datarecord.id = r.result;
347 if (!prepend_on_create) {
348 this.dataset.ids.push(this.datarecord.id);
349 this.dataset.index = this.dataset.ids.length - 1;
351 this.dataset.ids.unshift(this.datarecord.id);
352 this.dataset.index = 0;
354 this.dataset.count++;
355 this.do_update_pager();
356 this.do_update_sidebar();
357 this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
359 success(_.extend(r, {created: true}));
364 do_search: function (domains, contexts, groupbys) {
365 this.notification.notify("Searching form");
367 on_action: function (action) {
368 this.notification.notify('Executing action ' + action);
370 do_cancel: function () {
371 this.notification.notify("Cancelling form");
373 do_update_sidebar: function() {
374 if (this.flags.sidebar === false) {
377 if (!this.datarecord.id) {
378 this.on_attachments_loaded([]);
380 // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
381 /*this.rpc('/base/dataset/search_read', {
382 model: 'ir.attachment',
383 fields: ['name', 'url', 'type'],
384 domain: [['res_model', '=', this.dataset.model], ['res_id', '=', this.datarecord.id], ['type', 'in', ['binary', 'url']]],
385 context: this.dataset.context
386 }, this.on_attachments_loaded);*/
389 on_attachments_loaded: function(attachments) {
390 this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
391 this.attachments = attachments;
392 this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
393 this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
394 this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
396 on_attachment_changed: function(e) {
397 window[this.element_id + '_iframe'] = this.do_update_sidebar;
398 var $e = $(e.target);
399 if ($e.val() != '') {
400 this.$sidebar.find('form.oe-binary-form').submit();
401 $e.parent().find('input[type=file]').attr('disabled', 'true');
402 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
405 on_attachment_delete: function(e) {
406 var self = this, $e = $(e.currentTarget);
407 var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
408 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
409 this.rpc('/base/dataset/unlink', {
410 model: 'ir.attachment',
411 ids: [parseInt($e.attr('data-id'))]
413 $e.parent().remove();
414 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
419 if (this.datarecord.id) {
420 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
422 this.on_button_new();
428 openerp.base.form = {};
430 openerp.base.form.compute_domain = function(expr, fields) {
432 for (var i = expr.length - 1; i >= 0; i--) {
434 if (ex.length == 1) {
435 var top = stack.pop();
438 stack.push(stack.pop() || top);
441 stack.push(stack.pop() && top);
447 throw new Error('Unknown domain operator ' + ex);
451 var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
455 switch (op.toLowerCase()) {
458 stack.push(field == val);
462 stack.push(field != val);
465 stack.push(field < val);
468 stack.push(field > val);
471 stack.push(field <= val);
474 stack.push(field >= val);
477 stack.push(_(val).contains(field));
480 stack.push(!_(val).contains(field));
483 this.log("Unsupported operator in attrs :", op);
489 openerp.base.form.Widget = openerp.base.Controller.extend({
491 init: function(view, node) {
494 this.attrs = JSON.parse(this.node.attrs.attrs || '{}');
495 this.type = this.type || node.tag;
496 this.element_name = this.element_name || this.type;
497 this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
499 this._super(this.view.session, this.element_id);
501 this.view.widgets[this.element_id] = this;
502 this.children = node.children;
503 this.colspan = parseInt(node.attrs.colspan || 1);
505 this.string = this.string || node.attrs.string;
506 this.help = this.help || node.attrs.help;
507 this.invisible = (node.attrs.invisible == '1');
510 this.$element = $('#' + this.element_id);
512 process_attrs: function() {
513 var compute_domain = openerp.base.form.compute_domain;
514 for (var a in this.attrs) {
515 this[a] = compute_domain(this.attrs[a], this.view.fields);
518 update_dom: function() {
519 this.$element.toggle(!this.invisible);
522 var template = this.template;
523 return QWeb.render(template, { "widget": this });
527 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
528 template: 'WidgetFrame',
529 init: function(view, node) {
530 this._super(view, node);
531 this.columns = node.attrs.col || 4;
536 for (var i = 0; i < node.children.length; i++) {
537 var n = node.children[i];
538 if (n.tag == "newline") {
544 this.set_row_cells_with(this.table[this.table.length - 1]);
547 if (this.table.length) {
548 this.set_row_cells_with(this.table[this.table.length - 1]);
551 this.table.push(row);
556 set_row_cells_with: function(row) {
557 for (var i = 0; i < row.length; i++) {
559 if (w.is_field_label) {
562 row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
564 } else if (w.width === undefined) {
565 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
569 handle_node: function(node) {
570 var type = this.view.fields_view.fields[node.attrs.name] || {};
571 var widget = new (this.view.registry.get_any(
572 [node.attrs.widget, type.type, node.tag])) (this.view, node);
573 if (node.tag == 'field') {
574 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
575 this.view.default_focus_field = widget;
577 if (node.attrs.nolabel != '1') {
578 var label = new (this.view.registry.get_object('label')) (this.view, node);
579 label["for"] = widget;
580 this.add_widget(label);
583 this.add_widget(widget);
585 add_widget: function(widget) {
586 var current_row = this.table[this.table.length - 1];
587 if (current_row.length && (this.x + widget.colspan) > this.columns) {
588 current_row = this.add_row();
590 current_row.push(widget);
591 this.x += widget.colspan;
596 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
597 init: function(view, node) {
598 this._super(view, node);
599 this.template = "WidgetNotebook";
601 for (var i = 0; i < node.children.length; i++) {
602 var n = node.children[i];
603 if (n.tag == "page") {
604 var page = new openerp.base.form.WidgetFrame(this.view, n);
605 this.pages.push(page);
610 this._super.apply(this, arguments);
611 this.$element.tabs();
615 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
616 init: function(view, node) {
617 this._super(view, node);
618 this.template = "WidgetSeparator";
622 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
623 init: function(view, node) {
624 this._super(view, node);
625 this.template = "WidgetButton";
626 if (node.attrs.default_focus == '1') {
627 // TODO fme: provide enter key binding to widgets
628 this.view.default_focus_button = this;
632 this._super.apply(this, arguments);
633 this.$element.click(this.on_click);
635 on_click: function(saved) {
637 if (!this.node.attrs.special && this.view.touched && saved !== true) {
638 this.view.do_save(function() {
642 if (this.node.attrs.confirm) {
643 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
649 $(this).dialog("close");
652 $(this).dialog("close");
661 on_confirmed: function() {
664 this.view.execute_action(
665 this.node.attrs, this.view.dataset, this.session.action_manager,
666 this.view.datarecord.id, function (result) {
667 self.log("Button returned", result);
673 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
674 init: function(view, node) {
675 this.is_field_label = true;
676 this.element_name = 'label_' + node.attrs.name;
678 this._super(view, node);
680 this.template = "WidgetLabel";
683 render: function () {
684 if (this['for'] && this.type !== 'label') {
685 return QWeb.render(this.template, {widget: this['for']});
687 // Actual label widgets should not have a false and have type label
688 return QWeb.render(this.template, {widget: this});
692 openerp.base.form.Field = openerp.base.form.Widget.extend({
693 init: function(view, node) {
694 this.name = node.attrs.name;
695 this.value = undefined;
696 view.fields[this.name] = this;
697 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
698 this.element_name = "field_" + this.name + "_" + this.type;
700 this._super(view, node);
702 if (node.attrs.nolabel != '1' && this.colspan > 1) {
705 this.field = view.fields_view.fields[node.attrs.name] || {};
706 this.string = node.attrs.string || this.field.string;
707 this.help = node.attrs.help || this.field.help;
708 this.invisible = (this.invisible || this.field.invisible == '1');
709 this.nolabel = (this.field.nolabel || node.attrs.nolabel) == '1';
710 this.readonly = (this.field.readonly || node.attrs.readonly) == '1';
711 this.required = (this.field.required || node.attrs.required) == '1';
712 this.invalid = false;
713 this.touched = false;
715 set_value: function(value) {
717 this.invalid = false;
720 set_value_from_ui: function() {
721 this.value = undefined;
723 get_value: function() {
726 update_dom: function() {
727 this._super.apply(this, arguments);
728 this.$element.toggleClass('disabled', this.readonly);
729 this.$element.toggleClass('required', this.required);
730 if (this.view.show_invalid) {
731 this.$element.toggleClass('invalid', this.invalid);
734 on_ui_change: function() {
735 this.touched = this.view.touched = true;
738 this.set_value_from_ui();
739 this.view.do_onchange(this);
740 this.view.on_form_changed();
745 validate: function() {
746 this.invalid = false;
752 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
753 init: function(view, node) {
754 this._super(view, node);
755 this.template = "FieldChar";
758 this._super.apply(this, arguments);
759 this.$element.find('input').change(this.on_ui_change);
761 set_value: function(value) {
762 this._super.apply(this, arguments);
763 var show_value = (value != null && value !== false) ? value : '';
764 this.$element.find('input').val(show_value);
766 update_dom: function() {
767 this._super.apply(this, arguments);
768 this.$element.find('input').attr('disabled', this.readonly);
770 set_value_from_ui: function() {
771 this.value = this.$element.find('input').val();
773 validate: function() {
774 this.invalid = false;
775 var value = this.$element.find('input').val();
777 this.invalid = this.required;
778 } else if (this.validation_regex) {
779 this.invalid = !this.validation_regex.test(value);
783 this.$element.find('input').focus();
787 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
788 init: function(view, node) {
789 this._super(view, node);
790 this.template = "FieldEmail";
791 this.validation_regex = /@/;
794 this._super.apply(this, arguments);
795 this.$element.find('button').click(this.on_button_clicked);
797 on_button_clicked: function() {
798 if (!this.value || this.invalid) {
799 this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
801 location.href = 'mailto:' + this.value;
804 set_value: function(value) {
805 this._super.apply(this, arguments);
806 var show_value = (value != null && value !== false) ? value : '';
807 this.$element.find('a').attr('href', 'mailto:' + show_value);
811 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
812 init: function(view, node) {
813 this._super(view, node);
814 this.template = "FieldUrl";
817 this._super.apply(this, arguments);
818 this.$element.find('button').click(this.on_button_clicked);
820 on_button_clicked: function() {
822 this.notification.warn("Resource error", "This resource is empty");
824 window.open(this.value);
829 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
830 init: function(view, node) {
831 this._super(view, node);
832 this.validation_regex = /^-?\d+(\.\d+)?$/;
834 set_value: function(value) {
835 this._super.apply(this, [value]);
836 if (value === false || value === undefined) {
837 // As in GTK client, floats default to 0
840 var show_value = value.toFixed(2);
841 this.$element.find('input').val(show_value);
843 set_value_from_ui: function() {
844 this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
848 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
849 init: function(view, node) {
850 this._super(view, node);
851 this.template = "FieldDate";
852 this.jqueryui_object = 'datetimepicker';
855 this._super.apply(this, arguments);
856 this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
857 dateFormat: 'yy-mm-dd',
858 timeFormat: 'hh:mm:ss'
861 set_value: function(value) {
862 this._super.apply(this, arguments);
863 if (value == null || value == false) {
864 this.$element.find('input').val('');
866 this.$element.find('input').unbind('change');
867 // jQuery UI date picker wrongly call on_change event herebelow
868 this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
869 this.$element.find('input').change(this.on_ui_change);
872 set_value_from_ui: function() {
873 this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
875 this.value = this.format(this.value);
878 validate: function() {
879 this.invalid = this.required && !this.$element.find('input')[this.jqueryui_object]('getDate');
882 this.$element.find('input').focus();
884 parse: openerp.base.parse_datetime,
885 format: openerp.base.format_datetime
888 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
889 init: function(view, node) {
890 this._super(view, node);
891 this.jqueryui_object = 'datepicker';
893 parse: openerp.base.parse_date,
894 format: openerp.base.format_date
897 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
898 init: function(view, node) {
899 this._super(view, node);
900 this.validation_regex = /^\d+:\d+$/;
902 set_value: function(value) {
903 this._super.apply(this, [value]);
904 if (value === false || value === undefined) {
905 // As in GTK client, floats default to 0
908 var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
909 this.$element.find('input').val(show_value);
911 set_value_from_ui: function() {
912 var time = this.$element.find('input').val().split(':');
913 this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
917 openerp.base.form.FieldText = openerp.base.form.Field.extend({
918 init: function(view, node) {
919 this._super(view, node);
920 this.template = "FieldText";
921 this.validation_regex = null;
924 this._super.apply(this, arguments);
925 this.$element.find('textarea').change(this.on_ui_change);
927 set_value: function(value) {
928 this._super.apply(this, arguments);
929 var show_value = (value != null && value !== false) ? value : '';
930 this.$element.find('textarea').val(show_value);
932 update_dom: function() {
933 this._super.apply(this, arguments);
934 this.$element.find('textarea').attr('disabled', this.readonly);
936 set_value_from_ui: function() {
937 this.value = this.$element.find('textarea').val();
939 validate: function() {
940 this.invalid = false;
941 var value = this.$element.find('textarea').val();
943 this.invalid = this.required;
944 } else if (this.validation_regex) {
945 this.invalid = !this.validation_regex.test(value);
949 this.$element.find('textarea').focus();
953 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
954 init: function(view, node) {
955 this._super(view, node);
956 this.template = "FieldBoolean";
960 this._super.apply(this, arguments);
961 this.$element.find('input').click(function() {
962 if ($(this).is(':checked') != self.value) {
967 set_value: function(value) {
968 this._super.apply(this, arguments);
969 this.$element.find('input')[0].checked = value;
971 set_value_from_ui: function() {
972 this.value = this.$element.find('input').is(':checked');
974 update_dom: function() {
975 this._super.apply(this, arguments);
976 this.$element.find('input').attr('disabled', this.readonly);
978 validate: function() {
979 this.invalid = this.required && !this.$element.find('input').is(':checked');
982 this.$element.find('input').focus();
986 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
987 init: function(view, node) {
988 this._super(view, node);
989 this.template = "FieldProgressBar";
992 this._super.apply(this, arguments);
993 this.$element.find('div').progressbar({
995 disabled: this.readonly
998 set_value: function(value) {
999 this._super.apply(this, arguments);
1000 var show_value = Number(value);
1001 if (show_value === NaN) {
1004 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1008 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1009 // to replace view editor
1012 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1013 init: function(view, node) {
1014 this._super(view, node);
1015 this.template = "FieldSelection";
1018 this._super.apply(this, arguments);
1019 this.$element.find('select').change(this.on_ui_change);
1021 set_value: function(value) {
1022 this._super.apply(this, arguments);
1023 if (value != null && value !== false) {
1024 this.$element.find('select').val(value);
1026 this.$element.find('select').val('false');
1029 set_value_from_ui: function() {
1030 this.value = this.$element.find('select').val();
1032 update_dom: function() {
1033 this._super.apply(this, arguments);
1034 this.$element.find('select').attr('disabled', this.readonly);
1036 validate: function() {
1037 this.invalid = this.required && this.$element.find('select').val() === "";
1040 this.$element.find('select').focus();
1044 // jquery autocomplete tweak to allow html
1046 var proto = $.ui.autocomplete.prototype,
1047 initSource = proto._initSource;
1049 function filter( array, term ) {
1050 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1051 return $.grep( array, function(value) {
1052 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1057 _initSource: function() {
1058 if ( this.options.html && $.isArray(this.options.source) ) {
1059 this.source = function( request, response ) {
1060 response( filter( this.options.source, request.term ) );
1063 initSource.call( this );
1067 _renderItem: function( ul, item) {
1068 return $( "<li></li>" )
1069 .data( "item.autocomplete", item )
1070 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1077 * Builds a new context usable for operations related to fields by merging
1078 * the fields'context with the action's context.
1080 var build_relation_context = function(relation_field) {
1081 var action = relation_field.view.view_manager.action || {};
1082 var a_context = action.context || {};
1083 var f_context = relation_field.field.context || {};
1084 var ctx = new openerp.base.CompoundContext(a_context).add(f_context);
1088 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1089 init: function(view, node) {
1090 this._super(view, node);
1091 this.template = "FieldMany2One";
1094 this.cm_id = _.uniqueId('m2o_cm_');
1095 this.last_search = [];
1096 this.tmp_value = undefined;
1101 this.$input = this.$element.find("input");
1102 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1103 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1107 bindings[this.cm_id + "_search"] = function() {
1108 self._search_create_popup("search");
1110 bindings[this.cm_id + "_create"] = function() {
1111 self._search_create_popup("form");
1113 bindings[this.cm_id + "_open"] = function() {
1117 self.session.action_manager.do_action({
1118 "res_model": self.field.relation,
1119 "views":[[false,"form"]],
1120 "res_id": self.value[0],
1121 "type":"ir.actions.act_window",
1125 "context": build_relation_context(self)
1128 var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1129 bindings: bindings, itemStyle: {"color": ""},
1130 onContextMenu: function() {
1132 $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1134 $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1140 // some behavior for input
1141 this.$input.keyup(function() {
1142 if (self.$input.val() === "") {
1143 self._change_int_value(null);
1144 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1145 self._change_int_value(undefined);
1148 this.$drop_down.click(function() {
1149 if (self.$input.autocomplete("widget").is(":visible")) {
1150 self.$input.autocomplete("close");
1153 self.$input.autocomplete("search", "");
1155 self.$input.autocomplete("search");
1157 self.$input.focus();
1160 var anyoneLoosesFocus = function() {
1161 if (!self.$input.is(":focus") &&
1162 !self.$input.autocomplete("widget").is(":visible") &&
1164 if(self.value === undefined && self.last_search.length > 0) {
1165 self._change_int_ext_value(self.last_search[0]);
1167 self._change_int_ext_value(null);
1171 this.$input.focusout(anyoneLoosesFocus);
1174 this.$input.autocomplete({
1175 source: function(req, resp) { self.get_search_result(req, resp); },
1176 select: function(event, ui) {
1179 self._change_int_value([item.id, item.name]);
1180 } else if (item.action) {
1181 self._change_int_value(undefined);
1186 focus: function(e, ui) {
1190 close: anyoneLoosesFocus,
1195 // autocomplete component content handling
1196 get_search_result: function(request, response) {
1197 var search_val = request.term;
1200 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, []);
1202 dataset.name_search([search_val, self.field.domain || [], 'ilike',
1203 build_relation_context(self), this.limit + 1], function(data) {
1204 self.last_search = data.result;
1205 // possible selections for the m2o
1206 var values = _.map(data.result, function(x) {
1207 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1210 // search more... if more results that max
1211 if (values.length > self.limit) {
1212 values = values.slice(0, self.limit);
1213 values.push({label: "<em>Â Â Â Search More...</em>", action: function() {
1214 dataset.name_search([search_val, self.field.domain || [], 'ilike',
1215 build_relation_context(self), false], function(data) {
1216 self._change_int_value(null);
1217 self._search_create_popup("search", data.result);
1222 var raw_result = _(data.result).map(function(x) {return x[1];})
1223 if (search_val.length > 0 &&
1224 !_.include(raw_result, search_val) &&
1225 (!self.value || search_val !== self.value[1])) {
1226 values.push({label: '<em>Â Â Â Create "<strong>' +
1227 $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1228 self._quick_create(search_val);
1232 values.push({label: "<em>Â Â Â Create and Edit...</em>", action: function() {
1233 self._change_int_value(null);
1234 self._search_create_popup("form");
1240 _quick_create: function(name) {
1242 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, []);
1243 dataset.call("name_create", [name, build_relation_context(self)], function(data) {
1244 self._change_int_ext_value(data.result);
1246 self._change_int_value(null);
1247 self._search_create_popup("form", undefined, {"default_name": name});
1250 // all search/create popup handling
1251 _search_create_popup: function(view, ids, context) {
1252 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, []);
1254 var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1255 pop.select_element(self.field.relation,{
1256 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1258 disable_multiple_selection: true
1259 }, self.view.domain || [],
1260 new openerp.base.CompoundContext(build_relation_context(self)).add(context || {}));
1261 pop.on_select_elements.add(function(element_ids) {
1262 dataset.call("name_get", [[element_ids[0]]], function(data) {
1263 self._change_int_ext_value(data.result[0]);
1268 _change_int_ext_value: function(value) {
1269 this._change_int_value(value);
1270 this.$input.val(this.value ? this.value[1] : "");
1272 _change_int_value: function(value) {
1274 if (this.original_value === undefined || (this.value !== undefined &&
1275 ((this.original_value ? this.original_value[0] : null) !== (this.value ? this.value[0] : null)))) {
1276 this.original_value = undefined;
1277 this.on_ui_change();
1280 set_value_from_ui: function() {},
1281 set_value: function(value) {
1282 value = value || null;
1284 var _super = this._super;
1285 this.tmp_value = value;
1286 var real_set_value = function(rval) {
1287 self.tmp_value = undefined;
1288 _super.apply(self, rval);
1289 self.original_value = rval;
1290 self._change_int_ext_value(rval);
1292 if(typeof(value) === "number") {
1293 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, []);
1294 dataset.call("name_get", [[value]], function(data) {
1295 real_set_value(data.result[0]);
1296 }).fail(function() {self.tmp_value = undefined;});
1298 setTimeout(function() {real_set_value(value);}, 0);
1301 get_value: function() {
1302 if (this.tmp_value !== undefined) {
1303 if (this.tmp_value instanceof Array) {
1304 return this.tmp_value[0];
1306 return this.tmp_value === null ? false : this.tmp_value;
1308 if (this.value === undefined)
1309 throw "theorically unreachable state";
1310 return this.value ? this.value[0] : false;
1312 validate: function() {
1313 this.invalid = false;
1314 if (this.value === null) {
1315 this.invalid = this.required;
1321 # Values: (0, 0, { fields }) create
1322 # (1, ID, { fields }) update
1323 # (2, ID) remove (delete)
1324 # (3, ID) unlink one (target id or target of relation)
1326 # (5) unlink all (only valid for one2many)
1331 'create': function (values) {
1332 return [commands.CREATE, false, values];
1334 // (1, id, {values})
1336 'update': function (id, values) {
1337 return [commands.UPDATE, id, values];
1341 'delete': function (id) {
1342 return [commands.DELETE, id, false];
1344 // (3, id[, _]) removes relation, but not linked record itself
1346 'forget': function (id) {
1347 return [commands.FORGET, id, false];
1351 'link_to': function (id) {
1352 return [commands.LINK_TO, id, false];
1356 'forget_all': function () {
1357 return [5, false, false];
1359 // (6, _, ids) replaces all linked records with provided ids
1361 'replace_with': function (ids) {
1362 return [6, false, ids];
1365 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1366 init: function(view, node) {
1367 this._super(view, node);
1368 this.template = "FieldOne2Many";
1369 this.is_started = $.Deferred();
1372 this._super.apply(this, arguments);
1376 this.dataset = new openerp.base.BufferedDataSet(this.session, this.field.relation);
1377 this.dataset.on_change.add_last(function() {
1378 self.on_ui_change();
1381 var modes = this.node.attrs.mode;
1382 modes = !!modes ? modes.split(",") : ["tree", "form"];
1384 _.each(modes, function(mode) {
1385 var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1386 if (self.field.views && self.field.views[mode]) {
1387 view.embedded_view = self.field.views[mode];
1389 if(view.view_type === "list") {
1397 this.viewmanager = new openerp.base.ViewManager(this.view.session,
1398 this.element_id, this.dataset, views);
1399 this.viewmanager.registry = openerp.base.views.clone({
1400 list: 'openerp.base.form.One2ManyListView'
1403 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1404 if (view_type == "list") {
1405 controller.o2m = self;
1406 } else if (view_type == "form") {
1409 self.is_started.resolve();
1411 this.viewmanager.start();
1413 reload_current_view: function() {
1415 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1416 if(self.viewmanager.active_view === "list") {
1417 view.reload_content();
1418 } else if (self.viewmanager.active_view === "form") {
1419 // TODO niv: implement
1422 set_value_from_ui: function() {},
1423 set_value: function(value) {
1424 value = value || [];
1426 if(value.length >= 1 && value[0] instanceof Array) {
1428 _.each(value, function(command) {
1429 var obj = {values: command[2]};
1430 switch (command[0]) {
1431 case commands.CREATE:
1432 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1433 self.dataset.to_create.push(obj);
1434 self.dataset.cache.push(_.clone(obj));
1437 case commands.UPDATE:
1438 obj['id'] = command[1];
1439 self.dataset.to_write.push(obj);
1440 self.dataset.cache.push(_.clone(obj));
1443 case commands.DELETE:
1444 self.dataset.to_delete.push({id: command[1]});
1446 case commands.LINK_TO:
1447 ids.push(command[1]);
1452 this.dataset.set_ids(ids);
1455 this.dataset.reset_ids(value);
1457 $.when(this.is_started).then(function() {
1458 self.reload_current_view();
1461 get_value: function() {
1463 var val = _.map(this.dataset.ids, function(id) {
1464 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1466 return commands.create(alter_order.values);
1468 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1470 return commands.update(alter_order.id, alter_order.values);
1472 return commands.link_to(id);
1474 return val.concat(_.map(
1475 this.dataset.to_delete, function(x) {
1476 return commands['delete'](x.id);}));
1478 validate: function() {
1479 this.invalid = false;
1484 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1485 do_add_record: function () {
1487 var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1488 pop.select_element(self.o2m.field.relation,{
1489 initial_view: "form",
1490 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1493 pop.on_create.add(function(data) {
1494 self.o2m.dataset.create(data, function(r) {
1495 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1497 self.o2m.reload_current_view();
1503 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1504 init: function(view, node) {
1505 this._super(view, node);
1506 this.template = "FieldMany2Many";
1507 this.list_id = _.uniqueId("many2many");
1508 this.is_started = $.Deferred();
1511 this._super.apply(this, arguments);
1515 this.dataset = new openerp.base.DataSetStatic(
1516 this.session, this.field.relation);
1517 this.dataset.on_unlink.add_last(function(ids) {
1518 //TODO niv: should check this for other cases
1519 self.on_ui_change();
1522 this.list_view = new openerp.base.form.Many2ManyListView(
1523 null, this.view.session, this.list_id, this.dataset, false, {
1526 this.list_view.m2m_field = this;
1527 this.list_view.on_loaded.add_last(function() {
1528 self.is_started.resolve();
1530 this.list_view.start();
1532 set_value: function(value) {
1533 value = value || [];
1534 if (value.length >= 1 && value[0] instanceof Array) {
1535 value = value[0][2];
1538 this.dataset.set_ids(value);
1540 $.when(this.is_started).then(function() {
1541 self.list_view.reload_content();
1544 get_value: function() {
1545 return [commands.replace_with(this.dataset.ids)];
1549 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1550 do_add_record: function () {
1551 var pop = new openerp.base.form.SelectCreatePopup(
1552 null, this.m2m_field.view.session);
1553 pop.select_element(this.model);
1555 pop.on_select_elements.add(function(element_ids) {
1556 _.each(element_ids, function(element_id) {
1557 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1558 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1559 self.reload_content();
1565 do_activate_record: function(index, id) {
1566 this.m2m_field.view.session.action_manager.do_action({
1567 "res_model": this.dataset.model,
1568 "views":[[false,"form"]],
1570 "type":"ir.actions.act_window",
1578 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1579 identifier_prefix: "selectcreatepopup",
1580 template: "SelectCreatePopup",
1584 * - initial_view: form or search (default search)
1585 * - disable_multiple_selection
1586 * - alternative_form_view
1587 * - auto_create (default true)
1589 select_element: function(model, options, domain, context) {
1591 this.domain = domain || [];
1592 this.context = context || {};
1593 this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1594 this.initial_ids = this.options.initial_ids;
1595 jQuery(this.render()).dialog({title: '',
1602 this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1603 this.context, this.domain);
1604 if (this.options.initial_view == "search") {
1605 this.setup_search_view();
1610 setup_search_view: function() {
1612 if (this.searchview) {
1613 this.searchview.stop();
1615 this.searchview = new openerp.base.SearchView(null, this.session,
1616 this.element_id + "_search", this.dataset, false, {
1617 "selectable": !this.options.disable_multiple_selection,
1620 this.searchview.on_search.add(function(domains, contexts, groupbys) {
1621 if (self.initial_ids) {
1622 self.view_list.do_search.call(self,[[["id", "in", self.initial_ids]]],
1623 contexts, groupbys);
1624 self.initial_ids = undefined;
1626 self.view_list.do_search.call(self, domains, contexts, groupbys);
1629 this.searchview.on_loaded.add_last(function () {
1630 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1631 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1632 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1633 $cbutton.click(function() {
1636 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1637 if(self.options.disable_multiple_selection) {
1640 $sbutton.click(function() {
1641 self.on_select_elements(self.selected_ids);
1643 self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1644 self.element_id + "_view_list", self.dataset, false,
1645 {'deletable': false});
1646 self.view_list.popup = self;
1647 self.view_list.do_show();
1648 self.view_list.start().then(function() {
1649 self.searchview.do_search();
1652 this.searchview.start();
1654 on_create: function(data) {
1655 if (!this.options.auto_create)
1658 var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1659 wdataset.create(data, function(r) {
1660 self.on_select_elements([r.result]);
1663 on_select_elements: function(element_ids) {
1665 on_click_element: function(ids) {
1666 this.selected_ids = ids || [];
1667 if(this.selected_ids.length > 0) {
1668 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1670 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1673 new_object: function() {
1675 if (this.searchview) {
1676 this.searchview.hide();
1678 if (this.view_list) {
1679 this.view_list.$element.hide();
1681 this.dataset.index = null;
1682 this.view_form = new openerp.base.FormView(null, this.session,
1683 this.element_id + "_view_form", this.dataset, false);
1684 if (this.options.alternative_form_view) {
1685 this.view_form.set_embedded_view(this.options.alternative_form_view);
1687 this.view_form.start();
1688 this.view_form.on_loaded.add_last(function() {
1689 var $buttons = self.view_form.$element.find(".oe_form_buttons");
1690 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1691 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1692 $nbutton.click(function() {
1693 self.view_form.do_save();
1695 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1696 $cbutton.click(function() {
1700 this.dataset.on_create.add(this.on_create);
1701 this.view_form.do_show();
1705 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1706 do_add_record: function () {
1707 this.popup.new_object();
1709 select_record: function(index) {
1710 this.popup.on_select_elements([this.dataset.ids[index]]);
1712 do_select: function(ids, records) {
1713 this._super(ids, records);
1714 this.popup.on_click_element(ids);
1718 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1719 init: function(view, node) {
1720 this._super(view, node);
1721 this.template = "FieldReference";
1725 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1726 init: function(view, node) {
1727 this._super(view, node);
1728 this.iframe = this.element_id + '_iframe';
1729 this.binary_value = false;
1732 this._super.apply(this, arguments);
1733 this.$element.find('input.oe-binary-file').change(this.on_file_change);
1734 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1735 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1737 set_value_from_ui: function() {
1739 human_filesize : function(size) {
1740 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1742 while (size >= 1024) {
1746 return size.toFixed(2) + ' ' + units[i];
1748 on_file_change: function(e) {
1749 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1750 // http://www.html5rocks.com/tutorials/file/dndfiles/
1751 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1752 window[this.iframe] = this.on_file_uploaded;
1753 if ($(e.target).val() != '') {
1754 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1755 this.$element.find('form.oe-binary-form').submit();
1756 this.toggle_progress();
1759 toggle_progress: function() {
1760 this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1762 on_file_uploaded: function(size, name, content_type, file_base64) {
1763 delete(window[this.iframe]);
1764 if (size === false) {
1765 this.notification.warn("File Upload", "There was a problem while uploading your file");
1766 // TODO: use openerp web exception handler
1767 console.log("Error while uploading file : ", name);
1769 this.on_file_uploaded_and_valid.apply(this, arguments);
1770 this.on_ui_change();
1772 this.toggle_progress();
1774 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1776 on_save_as: function() {
1777 if (!this.view.datarecord.id) {
1778 this.notification.warn("Can't save file", "The record has not yet been saved");
1780 var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1781 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1782 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1786 on_clear: function() {
1787 if (this.value !== false) {
1789 this.binary_value = false;
1790 this.on_ui_change();
1796 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1797 init: function(view, node) {
1798 this._super(view, node);
1799 this.template = "FieldBinaryFile";
1801 set_value: function(value) {
1802 this._super.apply(this, arguments);
1803 var show_value = (value != null && value !== false) ? value : '';
1804 this.$element.find('input').eq(0).val(show_value);
1806 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1807 this.value = file_base64;
1808 this.binary_value = true;
1809 var show_value = this.human_filesize(size);
1810 this.$element.find('input').eq(0).val(show_value);
1811 this.set_filename(name);
1813 set_filename: function(value) {
1814 var filename = this.node.attrs.filename;
1815 if (this.view.fields[filename]) {
1816 this.view.fields[filename].set_value(value);
1817 this.view.fields[filename].on_ui_change();
1820 on_clear: function() {
1821 this._super.apply(this, arguments);
1822 this.$element.find('input').eq(0).val('');
1823 this.set_filename('');
1827 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1828 init: function(view, node) {
1829 this._super(view, node);
1830 this.template = "FieldBinaryImage";
1833 this._super.apply(this, arguments);
1834 this.$image = this.$element.find('img.oe-binary-image');
1836 set_image_maxwidth: function() {
1837 this.$image.css('max-width', this.$element.width());
1839 on_file_change: function() {
1840 this.set_image_maxwidth();
1841 this._super.apply(this, arguments);
1843 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1844 this.value = file_base64;
1845 this.binary_value = true;
1846 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
1848 on_clear: function() {
1849 this._super.apply(this, arguments);
1850 this.$image.attr('src', '/base/static/src/img/placeholder.png');
1852 set_value: function(value) {
1853 this._super.apply(this, arguments);
1854 this.set_image_maxwidth();
1855 var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
1856 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
1857 this.$image.attr('src', url);
1862 * Registry of form widgets, called by :js:`openerp.base.FormView`
1864 openerp.base.form.widgets = new openerp.base.Registry({
1865 'frame' : 'openerp.base.form.WidgetFrame',
1866 'group' : 'openerp.base.form.WidgetFrame',
1867 'notebook' : 'openerp.base.form.WidgetNotebook',
1868 'separator' : 'openerp.base.form.WidgetSeparator',
1869 'label' : 'openerp.base.form.WidgetLabel',
1870 'button' : 'openerp.base.form.WidgetButton',
1871 'char' : 'openerp.base.form.FieldChar',
1872 'email' : 'openerp.base.form.FieldEmail',
1873 'url' : 'openerp.base.form.FieldUrl',
1874 'text' : 'openerp.base.form.FieldText',
1875 'text_wiki' : 'openerp.base.form.FieldText',
1876 'date' : 'openerp.base.form.FieldDate',
1877 'datetime' : 'openerp.base.form.FieldDatetime',
1878 'selection' : 'openerp.base.form.FieldSelection',
1879 'many2one' : 'openerp.base.form.FieldMany2One',
1880 'many2many' : 'openerp.base.form.FieldMany2Many',
1881 'one2many' : 'openerp.base.form.FieldOne2Many',
1882 'one2many_list' : 'openerp.base.form.FieldOne2Many',
1883 'reference' : 'openerp.base.form.FieldReference',
1884 'boolean' : 'openerp.base.form.FieldBoolean',
1885 'float' : 'openerp.base.form.FieldFloat',
1886 'integer': 'openerp.base.form.FieldFloat',
1887 'progressbar': 'openerp.base.form.FieldProgressBar',
1888 'float_time': 'openerp.base.form.FieldFloatTime',
1889 'image': 'openerp.base.form.FieldBinaryImage',
1890 'binary': 'openerp.base.form.FieldBinaryFile'
1895 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: