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.ids.length);
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 var parent_fields = null;
178 _.each(call[2].split(','), function(a) {
179 var field = _.trim(a);
180 if (field in argument_replacement) {
181 args.push(argument_replacement[field]);
183 } else if (self.fields[field]) {
184 var value = self.fields[field].get_on_change_value();
185 args.push(value == null ? false : value);
188 var splitted = field.split('.');
189 if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
190 if (parent_fields === null) {
191 parent_fields = self.dataset.parent_view.get_fields_values();
193 var p_val = parent_fields[_.trim(splitted[1])];
194 if (p_val !== undefined) {
195 args.push(value ? value : false);
200 throw "Could not get field with name '" + field +
201 "' for onchange '" + onchange + "'";
204 url: '/base/dataset/call',
207 return this.rpc(ajax, {
208 model: this.dataset.model,
210 args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args)
211 }, function(response) {
212 self.on_processed_onchange(response, processed);
215 this.log("Wrong on_change format", on_change);
219 on_processed_onchange: function(response, processed) {
220 var result = response.result;
222 console.log(" |-> Onchange Response :", result.value);
223 for (var f in result.value) {
224 var field = this.fields[f];
226 var value = result.value[f];
227 processed.push(field.name);
228 if (field.get_value() != value) {
229 console.log(" |-> Onchange Action : change '%s' value from '%s' to '%s'", field.name, field.get_value(), value);
230 field.set_value(value);
231 if (_.indexOf(processed, field.name) < 0) {
232 this.do_onchange(field, processed);
236 // this is a common case, the normal behavior should be to ignore it
237 this.log("on_processed_onchange can't find field " + f, result);
240 this.on_form_changed();
242 if (result.warning) {
243 $(QWeb.render("DialogWarning", result.warning)).dialog({
247 $(this).dialog("close");
257 on_button_new: function() {
259 $.when(this.has_been_loaded).then(function() {
260 self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
261 self.on_record_loaded(result.result);
266 * Triggers saving the form's record. Chooses between creating a new
267 * record or saving an existing one depending on whether the record
268 * already has an id property.
270 * @param {Function} success callback on save success
271 * @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)
273 do_save: function(success, prepend_on_create) {
280 first_invalid_field = null;
281 for (var f in this.fields) {
286 if (!first_invalid_field) {
287 first_invalid_field = f;
289 } else if (f.touched) {
290 values[f.name] = f.get_value();
294 first_invalid_field.focus();
298 this.log("About to save", values);
299 if (!this.datarecord.id) {
300 this.dataset.create(values, function(r) {
301 self.on_created(r, success, prepend_on_create);
304 this.dataset.write(this.datarecord.id, values, function(r) {
305 self.on_saved(r, success);
311 do_save_edit: function() {
313 //this.switch_readonly(); Use promises
315 switch_readonly: function() {
317 switch_editable: function() {
319 on_invalid: function() {
321 _.each(this.fields, function(f) {
323 msg += "<li>" + f.string + "</li>";
327 this.notification.warn("The following fields are invalid :", msg);
329 on_saved: function(r, success) {
331 this.notification.warn("Record not saved", "Problem while saving record.");
333 this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
341 * Updates the form' dataset to contain the new record:
343 * * Adds the newly created record to the current dataset (at the end by
345 * * Selects that record (sets the dataset's index to point to the new
347 * * Updates the pager and sidebar displays
350 * @param {Function} success callback to execute after having updated the dataset
351 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
353 on_created: function(r, success, prepend_on_create) {
355 this.notification.warn("Record not created", "Problem while creating record.");
357 this.datarecord.id = r.result;
358 if (!prepend_on_create) {
359 this.dataset.ids.push(this.datarecord.id);
360 this.dataset.index = this.dataset.ids.length - 1;
362 this.dataset.ids.unshift(this.datarecord.id);
363 this.dataset.index = 0;
365 this.do_update_pager();
366 this.do_update_sidebar();
367 this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
369 success(_.extend(r, {created: true}));
374 do_search: function (domains, contexts, groupbys) {
375 this.notification.notify("Searching form");
377 on_action: function (action) {
378 this.notification.notify('Executing action ' + action);
380 do_cancel: function () {
381 this.notification.notify("Cancelling form");
383 do_update_sidebar: function() {
384 if (this.flags.sidebar === false) {
387 if (!this.datarecord.id) {
388 this.on_attachments_loaded([]);
390 // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
391 /*this.rpc('/base/dataset/search_read', {
392 model: 'ir.attachment',
393 fields: ['name', 'url', 'type'],
394 domain: [['res_model', '=', this.dataset.model], ['res_id', '=', this.datarecord.id], ['type', 'in', ['binary', 'url']]],
395 context: this.dataset.context
396 }, this.on_attachments_loaded);*/
399 on_attachments_loaded: function(attachments) {
400 this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
401 this.attachments = attachments;
402 this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
403 this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
404 this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
406 on_attachment_changed: function(e) {
407 window[this.element_id + '_iframe'] = this.do_update_sidebar;
408 var $e = $(e.target);
409 if ($e.val() != '') {
410 this.$sidebar.find('form.oe-binary-form').submit();
411 $e.parent().find('input[type=file]').attr('disabled', 'true');
412 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
415 on_attachment_delete: function(e) {
416 var self = this, $e = $(e.currentTarget);
417 var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
418 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
419 this.rpc('/base/dataset/unlink', {
420 model: 'ir.attachment',
421 ids: [parseInt($e.attr('data-id'))]
423 $e.parent().remove();
424 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
429 if (this.datarecord.id) {
430 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
432 this.on_button_new();
435 get_fields_values: function() {
437 _.each(this.fields, function(value, key) {
438 values[key] = value.get_value();
445 openerp.base.form = {};
447 openerp.base.form.compute_domain = function(expr, fields) {
449 for (var i = expr.length - 1; i >= 0; i--) {
451 if (ex.length == 1) {
452 var top = stack.pop();
455 stack.push(stack.pop() || top);
458 stack.push(stack.pop() && top);
464 throw new Error('Unknown domain operator ' + ex);
468 var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
472 switch (op.toLowerCase()) {
475 stack.push(field == val);
479 stack.push(field != val);
482 stack.push(field < val);
485 stack.push(field > val);
488 stack.push(field <= val);
491 stack.push(field >= val);
494 stack.push(_(val).contains(field));
497 stack.push(!_(val).contains(field));
500 this.log("Unsupported operator in attrs :", op);
506 openerp.base.form.Widget = openerp.base.Controller.extend({
508 init: function(view, node) {
511 this.attrs = JSON.parse(this.node.attrs.attrs || '{}');
512 this.type = this.type || node.tag;
513 this.element_name = this.element_name || this.type;
514 this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
516 this._super(this.view.session, this.element_id);
518 this.view.widgets[this.element_id] = this;
519 this.children = node.children;
520 this.colspan = parseInt(node.attrs.colspan || 1);
522 this.string = this.string || node.attrs.string;
523 this.help = this.help || node.attrs.help;
524 this.invisible = (node.attrs.invisible == '1');
527 this.$element = $('#' + this.element_id);
529 process_attrs: function() {
530 var compute_domain = openerp.base.form.compute_domain;
531 for (var a in this.attrs) {
532 this[a] = compute_domain(this.attrs[a], this.view.fields);
535 update_dom: function() {
536 this.$element.toggle(!this.invisible);
539 var template = this.template;
540 return QWeb.render(template, { "widget": this });
544 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
545 template: 'WidgetFrame',
546 init: function(view, node) {
547 this._super(view, node);
548 this.columns = node.attrs.col || 4;
553 for (var i = 0; i < node.children.length; i++) {
554 var n = node.children[i];
555 if (n.tag == "newline") {
561 this.set_row_cells_with(this.table[this.table.length - 1]);
564 if (this.table.length) {
565 this.set_row_cells_with(this.table[this.table.length - 1]);
568 this.table.push(row);
573 set_row_cells_with: function(row) {
574 for (var i = 0; i < row.length; i++) {
576 if (w.is_field_label) {
579 row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
581 } else if (w.width === undefined) {
582 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
586 handle_node: function(node) {
587 var type = this.view.fields_view.fields[node.attrs.name] || {};
588 var widget = new (this.view.registry.get_any(
589 [node.attrs.widget, type.type, node.tag])) (this.view, node);
590 if (node.tag == 'field') {
591 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
592 this.view.default_focus_field = widget;
594 if (node.attrs.nolabel != '1') {
595 var label = new (this.view.registry.get_object('label')) (this.view, node);
596 label["for"] = widget;
597 this.add_widget(label);
600 this.add_widget(widget);
602 add_widget: function(widget) {
603 var current_row = this.table[this.table.length - 1];
604 if (current_row.length && (this.x + widget.colspan) > this.columns) {
605 current_row = this.add_row();
607 current_row.push(widget);
608 this.x += widget.colspan;
613 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
614 init: function(view, node) {
615 this._super(view, node);
616 this.template = "WidgetNotebook";
618 for (var i = 0; i < node.children.length; i++) {
619 var n = node.children[i];
620 if (n.tag == "page") {
621 var page = new openerp.base.form.WidgetFrame(this.view, n);
622 this.pages.push(page);
627 this._super.apply(this, arguments);
628 this.$element.tabs();
632 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
633 init: function(view, node) {
634 this._super(view, node);
635 this.template = "WidgetSeparator";
639 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
640 init: function(view, node) {
641 this._super(view, node);
642 this.template = "WidgetButton";
643 if (node.attrs.default_focus == '1') {
644 // TODO fme: provide enter key binding to widgets
645 this.view.default_focus_button = this;
649 this._super.apply(this, arguments);
650 this.$element.click(this.on_click);
652 on_click: function(saved) {
654 if (!this.node.attrs.special && this.view.touched && saved !== true) {
655 this.view.do_save(function() {
659 if (this.node.attrs.confirm) {
660 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
666 $(this).dialog("close");
669 $(this).dialog("close");
678 on_confirmed: function() {
681 this.view.execute_action(
682 this.node.attrs, this.view.dataset, this.session.action_manager,
683 this.view.datarecord.id, function (result) {
684 self.log("Button returned", result);
692 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
693 init: function(view, node) {
694 this.element_name = 'label_' + node.attrs.name;
696 this._super(view, node);
698 // TODO fme: support for attrs.align
699 if (this.node.tag == 'label' && this.node.attrs.colspan) {
700 this.is_field_label = false;
701 this.template = "WidgetParagraph";
703 this.is_field_label = true;
704 this.template = "WidgetLabel";
708 render: function () {
709 if (this['for'] && this.type !== 'label') {
710 return QWeb.render(this.template, {widget: this['for']});
712 // Actual label widgets should not have a false and have type label
713 return QWeb.render(this.template, {widget: this});
717 openerp.base.form.Field = openerp.base.form.Widget.extend({
718 init: function(view, node) {
719 this.name = node.attrs.name;
720 this.value = undefined;
721 view.fields[this.name] = this;
722 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
723 this.element_name = "field_" + this.name + "_" + this.type;
725 this._super(view, node);
727 if (node.attrs.nolabel != '1' && this.colspan > 1) {
730 this.field = view.fields_view.fields[node.attrs.name] || {};
731 this.string = node.attrs.string || this.field.string;
732 this.help = node.attrs.help || this.field.help;
733 this.invisible = (this.invisible || this.field.invisible == '1');
734 this.nolabel = (this.field.nolabel || node.attrs.nolabel) == '1';
735 this.readonly = (this.field.readonly || node.attrs.readonly) == '1';
736 this.required = (this.field.required || node.attrs.required) == '1';
737 this.invalid = false;
738 this.touched = false;
740 set_value: function(value) {
742 this.invalid = false;
745 set_value_from_ui: function() {
746 this.value = undefined;
748 get_value: function() {
751 get_on_change_value: function() {
752 return this.get_value();
754 update_dom: function() {
755 this._super.apply(this, arguments);
756 this.$element.toggleClass('disabled', this.readonly);
757 this.$element.toggleClass('required', this.required);
758 if (this.view.show_invalid) {
759 this.$element.toggleClass('invalid', this.invalid);
762 on_ui_change: function() {
763 this.touched = this.view.touched = true;
766 this.set_value_from_ui();
767 this.view.do_onchange(this);
768 this.view.on_form_changed();
773 validate: function() {
774 this.invalid = false;
780 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
781 init: function(view, node) {
782 this._super(view, node);
783 this.template = "FieldChar";
786 this._super.apply(this, arguments);
787 this.$element.find('input').change(this.on_ui_change);
789 set_value: function(value) {
790 this._super.apply(this, arguments);
791 var show_value = (value != null && value !== false) ? value : '';
792 this.$element.find('input').val(show_value);
794 update_dom: function() {
795 this._super.apply(this, arguments);
796 this.$element.find('input').attr('disabled', this.readonly);
798 set_value_from_ui: function() {
799 this.value = this.$element.find('input').val();
801 validate: function() {
802 this.invalid = false;
803 var value = this.$element.find('input').val();
805 this.invalid = this.required;
806 } else if (this.validation_regex) {
807 this.invalid = !this.validation_regex.test(value);
811 this.$element.find('input').focus();
815 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
816 init: function(view, node) {
817 this._super(view, node);
818 this.template = "FieldEmail";
819 this.validation_regex = /@/;
822 this._super.apply(this, arguments);
823 this.$element.find('button').click(this.on_button_clicked);
825 on_button_clicked: function() {
826 if (!this.value || this.invalid) {
827 this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
829 location.href = 'mailto:' + this.value;
832 set_value: function(value) {
833 this._super.apply(this, arguments);
834 var show_value = (value != null && value !== false) ? value : '';
835 this.$element.find('a').attr('href', 'mailto:' + show_value);
839 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
840 init: function(view, node) {
841 this._super(view, node);
842 this.template = "FieldUrl";
845 this._super.apply(this, arguments);
846 this.$element.find('button').click(this.on_button_clicked);
848 on_button_clicked: function() {
850 this.notification.warn("Resource error", "This resource is empty");
852 window.open(this.value);
857 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
858 init: function(view, node) {
859 this._super(view, node);
860 this.validation_regex = /^-?\d+(\.\d+)?$/;
862 set_value: function(value) {
863 this._super.apply(this, [value]);
864 if (value === false || value === undefined) {
865 // As in GTK client, floats default to 0
868 var show_value = value.toFixed(2);
869 this.$element.find('input').val(show_value);
871 set_value_from_ui: function() {
872 this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
876 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
877 init: function(view, node) {
878 this._super(view, node);
879 this.template = "FieldDate";
880 this.jqueryui_object = 'datetimepicker';
883 this._super.apply(this, arguments);
884 this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
885 dateFormat: 'yy-mm-dd',
886 timeFormat: 'hh:mm:ss'
889 set_value: function(value) {
890 this._super.apply(this, arguments);
891 if (value == null || value == false) {
892 this.$element.find('input').val('');
894 this.$element.find('input').unbind('change');
895 // jQuery UI date picker wrongly call on_change event herebelow
896 this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
897 this.$element.find('input').change(this.on_ui_change);
900 set_value_from_ui: function() {
901 this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
903 this.value = this.format(this.value);
906 validate: function() {
907 this.invalid = this.required && !this.$element.find('input')[this.jqueryui_object]('getDate');
910 this.$element.find('input').focus();
912 parse: openerp.base.parse_datetime,
913 format: openerp.base.format_datetime
916 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
917 init: function(view, node) {
918 this._super(view, node);
919 this.jqueryui_object = 'datepicker';
921 parse: openerp.base.parse_date,
922 format: openerp.base.format_date
925 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
926 init: function(view, node) {
927 this._super(view, node);
928 this.validation_regex = /^\d+:\d+$/;
930 set_value: function(value) {
931 this._super.apply(this, [value]);
932 if (value === false || value === undefined) {
933 // As in GTK client, floats default to 0
936 var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
937 this.$element.find('input').val(show_value);
939 set_value_from_ui: function() {
940 var time = this.$element.find('input').val().split(':');
941 this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
945 openerp.base.form.FieldText = openerp.base.form.Field.extend({
946 init: function(view, node) {
947 this._super(view, node);
948 this.template = "FieldText";
949 this.validation_regex = null;
952 this._super.apply(this, arguments);
953 this.$element.find('textarea').change(this.on_ui_change);
955 set_value: function(value) {
956 this._super.apply(this, arguments);
957 var show_value = (value != null && value !== false) ? value : '';
958 this.$element.find('textarea').val(show_value);
960 update_dom: function() {
961 this._super.apply(this, arguments);
962 this.$element.find('textarea').attr('disabled', this.readonly);
964 set_value_from_ui: function() {
965 this.value = this.$element.find('textarea').val();
967 validate: function() {
968 this.invalid = false;
969 var value = this.$element.find('textarea').val();
971 this.invalid = this.required;
972 } else if (this.validation_regex) {
973 this.invalid = !this.validation_regex.test(value);
977 this.$element.find('textarea').focus();
981 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
982 init: function(view, node) {
983 this._super(view, node);
984 this.template = "FieldBoolean";
988 this._super.apply(this, arguments);
989 this.$element.find('input').click(function() {
990 if ($(this).is(':checked') != self.value) {
995 set_value: function(value) {
996 this._super.apply(this, arguments);
997 this.$element.find('input')[0].checked = value;
999 set_value_from_ui: function() {
1000 this.value = this.$element.find('input').is(':checked');
1002 update_dom: function() {
1003 this._super.apply(this, arguments);
1004 this.$element.find('input').attr('disabled', this.readonly);
1006 validate: function() {
1007 this.invalid = this.required && !this.$element.find('input').is(':checked');
1010 this.$element.find('input').focus();
1014 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1015 init: function(view, node) {
1016 this._super(view, node);
1017 this.template = "FieldProgressBar";
1020 this._super.apply(this, arguments);
1021 this.$element.find('div').progressbar({
1023 disabled: this.readonly
1026 set_value: function(value) {
1027 this._super.apply(this, arguments);
1028 var show_value = Number(value);
1029 if (show_value === NaN) {
1032 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1036 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1037 // to replace view editor
1040 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1041 init: function(view, node) {
1042 this._super(view, node);
1043 this.template = "FieldSelection";
1046 this._super.apply(this, arguments);
1047 this.$element.find('select').change(this.on_ui_change);
1049 set_value: function(value) {
1050 this._super.apply(this, arguments);
1051 if (value != null && value !== false) {
1052 this.$element.find('select').val(value);
1054 this.$element.find('select').val('false');
1057 set_value_from_ui: function() {
1058 this.value = this.$element.find('select').val();
1060 update_dom: function() {
1061 this._super.apply(this, arguments);
1062 this.$element.find('select').attr('disabled', this.readonly);
1064 validate: function() {
1065 this.invalid = this.required && this.$element.find('select').val() === "";
1068 this.$element.find('select').focus();
1072 // jquery autocomplete tweak to allow html
1074 var proto = $.ui.autocomplete.prototype,
1075 initSource = proto._initSource;
1077 function filter( array, term ) {
1078 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1079 return $.grep( array, function(value) {
1080 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1085 _initSource: function() {
1086 if ( this.options.html && $.isArray(this.options.source) ) {
1087 this.source = function( request, response ) {
1088 response( filter( this.options.source, request.term ) );
1091 initSource.call( this );
1095 _renderItem: function( ul, item) {
1096 return $( "<li></li>" )
1097 .data( "item.autocomplete", item )
1098 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1104 var build_view_fields_values = function(view) {
1105 var a_dataset = view.dataset || {};
1106 var fields_values = view.get_fields_values();
1107 var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
1108 fields_values.parent = parent_values;
1109 return fields_values;
1112 * Builds a new context usable for operations related to fields by merging
1113 * the fields'context with the action's context.
1115 var build_relation_context = function(relation_field) {
1116 var a_context = relation_field.view.dataset.get_context() || {};
1117 var fields_values = build_view_fields_values(relation_field.view);
1118 var f_context = new openerp.base.CompoundContext(relation_field.field.context || {}).set_eval_context(fields_values);
1119 var ctx = new openerp.base.CompoundContext(a_context, f_context);
1122 var build_relation_domain = function(relation_field) {
1123 var fields_values = build_view_fields_values(relation_field.view);
1124 var f_domain = new openerp.base.CompoundDomain(relation_field.field.domain || []).set_eval_context(fields_values);
1128 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1129 init: function(view, node) {
1130 this._super(view, node);
1131 this.template = "FieldMany2One";
1134 this.cm_id = _.uniqueId('m2o_cm_');
1135 this.last_search = [];
1136 this.tmp_value = undefined;
1141 this.$input = this.$element.find("input");
1142 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1143 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1147 bindings[this.cm_id + "_search"] = function() {
1148 self._search_create_popup("search");
1150 bindings[this.cm_id + "_create"] = function() {
1151 self._search_create_popup("form");
1153 bindings[this.cm_id + "_open"] = function() {
1157 self.session.action_manager.do_action({
1158 "res_model": self.field.relation,
1159 "views":[[false,"form"]],
1160 "res_id": self.value[0],
1161 "type":"ir.actions.act_window",
1163 "context": build_relation_context(self)
1166 var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1167 bindings: bindings, itemStyle: {"color": ""},
1168 onContextMenu: function() {
1170 $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1172 $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1178 // some behavior for input
1179 this.$input.keyup(function() {
1180 if (self.$input.val() === "") {
1181 self._change_int_value(null);
1182 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1183 self._change_int_value(undefined);
1186 this.$drop_down.click(function() {
1187 if (self.$input.autocomplete("widget").is(":visible")) {
1188 self.$input.autocomplete("close");
1191 self.$input.autocomplete("search", "");
1193 self.$input.autocomplete("search");
1195 self.$input.focus();
1198 var anyoneLoosesFocus = function() {
1199 if (!self.$input.is(":focus") &&
1200 !self.$input.autocomplete("widget").is(":visible") &&
1202 if(self.value === undefined && self.last_search.length > 0) {
1203 self._change_int_ext_value(self.last_search[0]);
1205 self._change_int_ext_value(null);
1209 this.$input.focusout(anyoneLoosesFocus);
1212 this.$input.autocomplete({
1213 source: function(req, resp) { self.get_search_result(req, resp); },
1214 select: function(event, ui) {
1217 self._change_int_value([item.id, item.name]);
1218 } else if (item.action) {
1219 self._change_int_value(undefined);
1224 focus: function(e, ui) {
1228 close: anyoneLoosesFocus,
1233 // autocomplete component content handling
1234 get_search_result: function(request, response) {
1235 var search_val = request.term;
1238 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1240 dataset.name_search(search_val, build_relation_domain(self), 'ilike',
1241 this.limit + 1, function(data) {
1242 self.last_search = data.result;
1243 // possible selections for the m2o
1244 var values = _.map(data.result, function(x) {
1245 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1248 // search more... if more results that max
1249 if (values.length > self.limit) {
1250 values = values.slice(0, self.limit);
1251 values.push({label: "<em>Â Â Â Search More...</em>", action: function() {
1252 dataset.name_search(search_val, build_relation_domain(self), 'ilike'
1253 , false, function(data) {
1254 self._change_int_value(null);
1255 self._search_create_popup("search", data.result);
1260 var raw_result = _(data.result).map(function(x) {return x[1];})
1261 if (search_val.length > 0 &&
1262 !_.include(raw_result, search_val) &&
1263 (!self.value || search_val !== self.value[1])) {
1264 values.push({label: '<em>Â Â Â Create "<strong>' +
1265 $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1266 self._quick_create(search_val);
1270 values.push({label: "<em>Â Â Â Create and Edit...</em>", action: function() {
1271 self._change_int_value(null);
1272 self._search_create_popup("form");
1278 _quick_create: function(name) {
1280 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1281 dataset.name_create(name, function(data) {
1282 self._change_int_ext_value(data.result);
1283 }).fail(function(error, event) {
1284 event.preventDefault();
1285 self._change_int_value(null);
1286 self._search_create_popup("form", undefined, {"default_name": name});
1289 // all search/create popup handling
1290 _search_create_popup: function(view, ids, context) {
1292 var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1293 pop.select_element(self.field.relation,{
1294 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1296 disable_multiple_selection: true
1297 }, build_relation_domain(self),
1298 new openerp.base.CompoundContext(build_relation_context(self), context || {}));
1299 pop.on_select_elements.add(function(element_ids) {
1300 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1301 dataset.name_get([element_ids[0]], function(data) {
1302 self._change_int_ext_value(data.result[0]);
1307 _change_int_ext_value: function(value) {
1308 this._change_int_value(value);
1309 this.$input.val(this.value ? this.value[1] : "");
1311 _change_int_value: function(value) {
1313 var back_orig_value = this.original_value;
1314 if (this.value === null || this.value) {
1315 this.original_value = this.value;
1317 if (back_orig_value === undefined) { // first use after a set_value()
1320 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1321 !== (this.value ? this.value[0] : null))) {
1322 this.on_ui_change();
1325 set_value_from_ui: function() {},
1326 set_value: function(value) {
1327 value = value || null;
1329 var _super = this._super;
1330 this.tmp_value = value;
1331 var real_set_value = function(rval) {
1332 self.tmp_value = undefined;
1333 _super.apply(self, rval);
1334 self.original_value = undefined;
1335 self._change_int_ext_value(rval);
1337 if(typeof(value) === "number") {
1338 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1339 dataset.name_get([value], function(data) {
1340 real_set_value(data.result[0]);
1341 }).fail(function() {self.tmp_value = undefined;});
1343 setTimeout(function() {real_set_value(value);}, 0);
1346 get_value: function() {
1347 if (this.tmp_value !== undefined) {
1348 if (this.tmp_value instanceof Array) {
1349 return this.tmp_value[0];
1351 return this.tmp_value ? this.tmp_value : false;
1353 if (this.value === undefined)
1354 return this.original_value ? this.original_value[0] : false;
1355 return this.value ? this.value[0] : false;
1357 validate: function() {
1358 this.invalid = false;
1359 if (this.value === null) {
1360 this.invalid = this.required;
1366 # Values: (0, 0, { fields }) create
1367 # (1, ID, { fields }) update
1368 # (2, ID) remove (delete)
1369 # (3, ID) unlink one (target id or target of relation)
1371 # (5) unlink all (only valid for one2many)
1376 'create': function (values) {
1377 return [commands.CREATE, false, values];
1379 // (1, id, {values})
1381 'update': function (id, values) {
1382 return [commands.UPDATE, id, values];
1386 'delete': function (id) {
1387 return [commands.DELETE, id, false];
1389 // (3, id[, _]) removes relation, but not linked record itself
1391 'forget': function (id) {
1392 return [commands.FORGET, id, false];
1396 'link_to': function (id) {
1397 return [commands.LINK_TO, id, false];
1401 'delete_all': function () {
1402 return [5, false, false];
1404 // (6, _, ids) replaces all linked records with provided ids
1406 'replace_with': function (ids) {
1407 return [6, false, ids];
1410 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1411 init: function(view, node) {
1412 this._super(view, node);
1413 this.template = "FieldOne2Many";
1414 this.is_started = $.Deferred();
1417 this._super.apply(this, arguments);
1421 this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1422 this.dataset.o2m = this;
1423 this.dataset.parent_view = this.view;
1424 this.dataset.on_change.add_last(function() {
1425 self.on_ui_change();
1428 var modes = this.node.attrs.mode;
1429 modes = !!modes ? modes.split(",") : ["tree", "form"];
1431 _.each(modes, function(mode) {
1432 var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1433 if (self.field.views && self.field.views[mode]) {
1434 view.embedded_view = self.field.views[mode];
1436 if(view.view_type === "list") {
1444 this.viewmanager = new openerp.base.ViewManager(this.view.session,
1445 this.element_id, this.dataset, views);
1446 this.viewmanager.registry = openerp.base.views.clone({
1447 list: 'openerp.base.form.One2ManyListView'
1450 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1451 if (view_type == "list") {
1452 controller.o2m = self;
1453 } else if (view_type == "form") {
1456 self.is_started.resolve();
1458 this.viewmanager.start();
1460 reload_current_view: function() {
1462 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1463 if(self.viewmanager.active_view === "list") {
1464 view.reload_content();
1465 } else if (self.viewmanager.active_view === "form") {
1466 // TODO niv: implement
1469 set_value_from_ui: function() {},
1470 set_value: function(value) {
1471 value = value || [];
1473 this.dataset.reset_ids([]);
1474 if(value.length >= 1 && value[0] instanceof Array) {
1476 _.each(value, function(command) {
1477 var obj = {values: command[2]};
1478 switch (command[0]) {
1479 case commands.CREATE:
1480 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1481 self.dataset.to_create.push(obj);
1482 self.dataset.cache.push(_.clone(obj));
1485 case commands.UPDATE:
1486 obj['id'] = command[1];
1487 self.dataset.to_write.push(obj);
1488 self.dataset.cache.push(_.clone(obj));
1491 case commands.DELETE:
1492 self.dataset.to_delete.push({id: command[1]});
1494 case commands.LINK_TO:
1495 ids.push(command[1]);
1497 case commands.DELETE_ALL:
1498 self.dataset.delete_all = true;
1503 this.dataset.set_ids(ids);
1504 } else if (value.length >= 1 && typeof(value[0]) === "object") {
1506 this.dataset.delete_all = true;
1507 _.each(value, function(command) {
1508 var obj = {values: command};
1509 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1510 self.dataset.to_create.push(obj);
1511 self.dataset.cache.push(_.clone(obj));
1515 this.dataset.set_ids(ids);
1518 this.dataset.reset_ids(value);
1520 $.when(this.is_started).then(function() {
1521 self.reload_current_view();
1524 get_value: function() {
1528 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1529 val = val.concat(_.map(this.dataset.ids, function(id) {
1530 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1532 return commands.create(alter_order.values);
1534 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1536 return commands.update(alter_order.id, alter_order.values);
1538 return commands.link_to(id);
1540 return val.concat(_.map(
1541 this.dataset.to_delete, function(x) {
1542 return commands['delete'](x.id);}));
1544 validate: function() {
1545 this.invalid = false;
1550 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1551 get_context: function() {
1552 this.context = build_relation_context(this.o2m);
1553 return this.context;
1557 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1558 do_add_record: function () {
1560 var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1561 pop.select_element(self.o2m.field.relation,{
1562 initial_view: "form",
1563 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1565 parent_view: self.o2m.view
1566 }, build_relation_domain(self.o2m), build_relation_context(self.o2m));
1567 pop.on_create.add(function(data) {
1568 self.o2m.dataset.create(data, function(r) {
1569 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1570 self.o2m.dataset.on_change();
1572 self.o2m.reload_current_view();
1578 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1579 init: function(view, node) {
1580 this._super(view, node);
1581 this.template = "FieldMany2Many";
1582 this.list_id = _.uniqueId("many2many");
1583 this.is_started = $.Deferred();
1586 this._super.apply(this, arguments);
1590 this.dataset = new openerp.base.DataSetStatic(
1591 this.session, this.field.relation);
1592 this.dataset.on_unlink.add_last(function(ids) {
1593 //TODO niv: should check this for other cases
1594 self.on_ui_change();
1597 this.list_view = new openerp.base.form.Many2ManyListView(
1598 null, this.view.session, this.list_id, this.dataset, false, {
1601 this.list_view.m2m_field = this;
1602 this.list_view.on_loaded.add_last(function() {
1603 self.is_started.resolve();
1605 this.list_view.start();
1607 set_value: function(value) {
1608 value = value || [];
1609 if (value.length >= 1 && value[0] instanceof Array) {
1610 value = value[0][2];
1613 this.dataset.set_ids(value);
1615 $.when(this.is_started).then(function() {
1616 self.list_view.reload_content();
1619 get_value: function() {
1620 return [commands.replace_with(this.dataset.ids)];
1624 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1625 do_add_record: function () {
1626 var pop = new openerp.base.form.SelectCreatePopup(
1627 null, this.m2m_field.view.session);
1628 pop.select_element(this.model);
1630 pop.on_select_elements.add(function(element_ids) {
1631 _.each(element_ids, function(element_id) {
1632 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1633 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1634 self.reload_content();
1640 do_activate_record: function(index, id) {
1641 this.m2m_field.view.session.action_manager.do_action({
1642 "res_model": this.dataset.model,
1643 "views":[[false,"form"]],
1645 "type":"ir.actions.act_window",
1653 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1654 identifier_prefix: "selectcreatepopup",
1655 template: "SelectCreatePopup",
1659 * - initial_view: form or search (default search)
1660 * - disable_multiple_selection
1661 * - alternative_form_view
1662 * - auto_create (default true)
1665 select_element: function(model, options, domain, context) {
1667 this.domain = domain || [];
1668 this.context = context || {};
1669 this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1670 this.initial_ids = this.options.initial_ids;
1671 jQuery(this.render()).dialog({title: '',
1678 this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1679 this.context, this.domain);
1680 this.dataset.parent_view = this.options.parent_view;
1681 if (this.options.initial_view == "search") {
1682 this.setup_search_view();
1687 setup_search_view: function() {
1689 if (this.searchview) {
1690 this.searchview.stop();
1692 this.searchview = new openerp.base.SearchView(null, this.session,
1693 this.element_id + "_search", this.dataset, false, {
1694 "selectable": !this.options.disable_multiple_selection,
1697 this.searchview.on_search.add(function(domains, contexts, groupbys) {
1698 if (self.initial_ids) {
1699 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]]]),
1700 contexts, groupbys);
1701 self.initial_ids = undefined;
1703 self.view_list.do_search.call(self, domains, contexts, groupbys);
1706 this.searchview.on_loaded.add_last(function () {
1707 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1708 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1709 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1710 $cbutton.click(function() {
1713 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1714 if(self.options.disable_multiple_selection) {
1717 $sbutton.click(function() {
1718 self.on_select_elements(self.selected_ids);
1720 self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1721 self.element_id + "_view_list", self.dataset, false,
1722 {'deletable': false});
1723 self.view_list.popup = self;
1724 self.view_list.do_show();
1725 self.view_list.start().then(function() {
1726 self.searchview.do_search();
1729 this.searchview.start();
1731 on_create: function(data) {
1732 if (!this.options.auto_create)
1735 var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1736 wdataset = this.options.parent_view;
1737 wdataset.create(data, function(r) {
1738 self.on_select_elements([r.result]);
1741 on_select_elements: function(element_ids) {
1743 on_click_element: function(ids) {
1744 this.selected_ids = ids || [];
1745 if(this.selected_ids.length > 0) {
1746 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1748 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1751 new_object: function() {
1753 if (this.searchview) {
1754 this.searchview.hide();
1756 if (this.view_list) {
1757 this.view_list.$element.hide();
1759 this.dataset.index = null;
1760 this.view_form = new openerp.base.FormView(null, this.session,
1761 this.element_id + "_view_form", this.dataset, false);
1762 if (this.options.alternative_form_view) {
1763 this.view_form.set_embedded_view(this.options.alternative_form_view);
1765 this.view_form.start();
1766 this.view_form.on_loaded.add_last(function() {
1767 var $buttons = self.view_form.$element.find(".oe_form_buttons");
1768 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1769 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1770 $nbutton.click(function() {
1771 self.view_form.do_save();
1773 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1774 $cbutton.click(function() {
1778 this.dataset.on_create.add(this.on_create);
1779 this.view_form.do_show();
1783 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1784 do_add_record: function () {
1785 this.popup.new_object();
1787 select_record: function(index) {
1788 this.popup.on_select_elements([this.dataset.ids[index]]);
1790 do_select: function(ids, records) {
1791 this._super(ids, records);
1792 this.popup.on_click_element(ids);
1796 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1797 init: function(view, node) {
1798 this._super(view, node);
1799 this.template = "FieldReference";
1803 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1804 init: function(view, node) {
1805 this._super(view, node);
1806 this.iframe = this.element_id + '_iframe';
1807 this.binary_value = false;
1810 this._super.apply(this, arguments);
1811 this.$element.find('input.oe-binary-file').change(this.on_file_change);
1812 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1813 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1815 set_value_from_ui: function() {
1817 human_filesize : function(size) {
1818 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1820 while (size >= 1024) {
1824 return size.toFixed(2) + ' ' + units[i];
1826 on_file_change: function(e) {
1827 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1828 // http://www.html5rocks.com/tutorials/file/dndfiles/
1829 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1830 window[this.iframe] = this.on_file_uploaded;
1831 if ($(e.target).val() != '') {
1832 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1833 this.$element.find('form.oe-binary-form').submit();
1834 this.toggle_progress();
1837 toggle_progress: function() {
1838 this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1840 on_file_uploaded: function(size, name, content_type, file_base64) {
1841 delete(window[this.iframe]);
1842 if (size === false) {
1843 this.notification.warn("File Upload", "There was a problem while uploading your file");
1844 // TODO: use openerp web exception handler
1845 console.log("Error while uploading file : ", name);
1847 this.on_file_uploaded_and_valid.apply(this, arguments);
1848 this.on_ui_change();
1850 this.toggle_progress();
1852 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1854 on_save_as: function() {
1855 if (!this.view.datarecord.id) {
1856 this.notification.warn("Can't save file", "The record has not yet been saved");
1858 var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1859 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1860 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1864 on_clear: function() {
1865 if (this.value !== false) {
1867 this.binary_value = false;
1868 this.on_ui_change();
1874 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1875 init: function(view, node) {
1876 this._super(view, node);
1877 this.template = "FieldBinaryFile";
1879 set_value: function(value) {
1880 this._super.apply(this, arguments);
1881 var show_value = (value != null && value !== false) ? value : '';
1882 this.$element.find('input').eq(0).val(show_value);
1884 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1885 this.value = file_base64;
1886 this.binary_value = true;
1887 var show_value = this.human_filesize(size);
1888 this.$element.find('input').eq(0).val(show_value);
1889 this.set_filename(name);
1891 set_filename: function(value) {
1892 var filename = this.node.attrs.filename;
1893 if (this.view.fields[filename]) {
1894 this.view.fields[filename].set_value(value);
1895 this.view.fields[filename].on_ui_change();
1898 on_clear: function() {
1899 this._super.apply(this, arguments);
1900 this.$element.find('input').eq(0).val('');
1901 this.set_filename('');
1905 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1906 init: function(view, node) {
1907 this._super(view, node);
1908 this.template = "FieldBinaryImage";
1911 this._super.apply(this, arguments);
1912 this.$image = this.$element.find('img.oe-binary-image');
1914 set_image_maxwidth: function() {
1915 this.$image.css('max-width', this.$element.width());
1917 on_file_change: function() {
1918 this.set_image_maxwidth();
1919 this._super.apply(this, arguments);
1921 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1922 this.value = file_base64;
1923 this.binary_value = true;
1924 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
1926 on_clear: function() {
1927 this._super.apply(this, arguments);
1928 this.$image.attr('src', '/base/static/src/img/placeholder.png');
1930 set_value: function(value) {
1931 this._super.apply(this, arguments);
1932 this.set_image_maxwidth();
1933 var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
1934 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
1935 this.$image.attr('src', url);
1940 * Registry of form widgets, called by :js:`openerp.base.FormView`
1942 openerp.base.form.widgets = new openerp.base.Registry({
1943 'frame' : 'openerp.base.form.WidgetFrame',
1944 'group' : 'openerp.base.form.WidgetFrame',
1945 'notebook' : 'openerp.base.form.WidgetNotebook',
1946 'separator' : 'openerp.base.form.WidgetSeparator',
1947 'label' : 'openerp.base.form.WidgetLabel',
1948 'button' : 'openerp.base.form.WidgetButton',
1949 'char' : 'openerp.base.form.FieldChar',
1950 'email' : 'openerp.base.form.FieldEmail',
1951 'url' : 'openerp.base.form.FieldUrl',
1952 'text' : 'openerp.base.form.FieldText',
1953 'text_wiki' : 'openerp.base.form.FieldText',
1954 'date' : 'openerp.base.form.FieldDate',
1955 'datetime' : 'openerp.base.form.FieldDatetime',
1956 'selection' : 'openerp.base.form.FieldSelection',
1957 'many2one' : 'openerp.base.form.FieldMany2One',
1958 'many2many' : 'openerp.base.form.FieldMany2Many',
1959 'one2many' : 'openerp.base.form.FieldOne2Many',
1960 'one2many_list' : 'openerp.base.form.FieldOne2Many',
1961 'reference' : 'openerp.base.form.FieldReference',
1962 'boolean' : 'openerp.base.form.FieldBoolean',
1963 'float' : 'openerp.base.form.FieldFloat',
1964 'integer': 'openerp.base.form.FieldFloat',
1965 'progressbar': 'openerp.base.form.FieldProgressBar',
1966 'float_time': 'openerp.base.form.FieldFloatTime',
1967 'image': 'openerp.base.form.FieldBinaryImage',
1968 'binary': 'openerp.base.form.FieldBinaryFile'
1973 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: