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.get_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 = {
176 'context': widget.build_context ? widget.build_context() : {}
178 var parent_fields = null;
179 _.each(call[2].split(','), function(a) {
180 var field = _.trim(a);
181 if (field in argument_replacement) {
182 args.push(argument_replacement[field]);
184 } else if (self.fields[field]) {
185 var value = self.fields[field].get_on_change_value();
186 args.push(value == null ? false : value);
189 var splitted = field.split('.');
190 if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
191 if (parent_fields === null) {
192 parent_fields = self.dataset.parent_view.get_fields_values();
194 var p_val = parent_fields[_.trim(splitted[1])];
195 if (p_val !== undefined) {
196 args.push(value ? value : false);
201 throw "Could not get field with name '" + field +
202 "' for onchange '" + onchange + "'";
205 url: '/base/dataset/call',
208 return this.rpc(ajax, {
209 model: this.dataset.model,
211 args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args)
212 }, function(response) {
213 self.on_processed_onchange(response, processed);
216 this.log("Wrong on_change format", on_change);
220 on_processed_onchange: function(response, processed) {
221 var result = response.result;
223 console.log(" |-> Onchange Response :", result.value);
224 for (var f in result.value) {
225 var field = this.fields[f];
227 var value = result.value[f];
228 processed.push(field.name);
229 if (field.get_value() != value) {
230 console.log(" |-> Onchange Action : change '%s' value from '%s' to '%s'", field.name, field.get_value(), value);
231 field.set_value(value);
232 field.touched = true;
233 if (_.indexOf(processed, field.name) < 0) {
234 this.do_onchange(field, processed);
238 // this is a common case, the normal behavior should be to ignore it
239 this.log("on_processed_onchange can't find field " + f, result);
242 this.on_form_changed();
244 if (result.warning) {
245 $(QWeb.render("DialogWarning", result.warning)).dialog({
249 $(this).dialog("close");
259 on_button_new: function() {
261 $.when(this.has_been_loaded).then(function() {
262 self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
263 self.on_record_loaded(result.result);
268 * Triggers saving the form's record. Chooses between creating a new
269 * record or saving an existing one depending on whether the record
270 * already has an id property.
272 * @param {Function} success callback on save success
273 * @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)
275 do_save: function(success, prepend_on_create) {
282 first_invalid_field = null;
283 for (var f in this.fields) {
288 if (!first_invalid_field) {
289 first_invalid_field = f;
291 } else if (f.touched) {
292 values[f.name] = f.get_value();
296 first_invalid_field.focus();
300 this.log("About to save", values);
301 if (!this.datarecord.id) {
302 this.dataset.create(values, function(r) {
303 self.on_created(r, success, prepend_on_create);
306 this.dataset.write(this.datarecord.id, values, function(r) {
307 self.on_saved(r, success);
313 do_save_edit: function() {
315 //this.switch_readonly(); Use promises
317 switch_readonly: function() {
319 switch_editable: function() {
321 on_invalid: function() {
323 _.each(this.fields, function(f) {
325 msg += "<li>" + f.string + "</li>";
329 this.notification.warn("The following fields are invalid :", msg);
331 on_saved: function(r, success) {
333 this.notification.warn("Record not saved", "Problem while saving record.");
335 this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
343 * Updates the form' dataset to contain the new record:
345 * * Adds the newly created record to the current dataset (at the end by
347 * * Selects that record (sets the dataset's index to point to the new
349 * * Updates the pager and sidebar displays
352 * @param {Function} success callback to execute after having updated the dataset
353 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
355 on_created: function(r, success, prepend_on_create) {
357 this.notification.warn("Record not created", "Problem while creating record.");
359 this.datarecord.id = r.result;
360 if (!prepend_on_create) {
361 this.dataset.ids.push(this.datarecord.id);
362 this.dataset.index = this.dataset.ids.length - 1;
364 this.dataset.ids.unshift(this.datarecord.id);
365 this.dataset.index = 0;
367 this.do_update_pager();
368 this.do_update_sidebar();
369 this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
371 success(_.extend(r, {created: true}));
376 do_search: function (domains, contexts, groupbys) {
377 this.notification.notify("Searching form");
379 on_action: function (action) {
380 this.notification.notify('Executing action ' + action);
382 do_cancel: function () {
383 this.notification.notify("Cancelling form");
385 do_update_sidebar: function() {
386 if (this.flags.sidebar === false) {
389 if (!this.datarecord.id) {
390 this.on_attachments_loaded([]);
392 // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
393 /*this.rpc('/base/dataset/search_read', {
394 model: 'ir.attachment',
395 fields: ['name', 'url', 'type'],
396 domain: [['res_model', '=', this.dataset.model], ['res_id', '=', this.datarecord.id], ['type', 'in', ['binary', 'url']]],
397 context: this.dataset.get_context()
398 }, this.on_attachments_loaded);*/
401 on_attachments_loaded: function(attachments) {
402 this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
403 this.attachments = attachments;
404 this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
405 this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
406 this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
408 on_attachment_changed: function(e) {
409 window[this.element_id + '_iframe'] = this.do_update_sidebar;
410 var $e = $(e.target);
411 if ($e.val() != '') {
412 this.$sidebar.find('form.oe-binary-form').submit();
413 $e.parent().find('input[type=file]').attr('disabled', 'true');
414 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
417 on_attachment_delete: function(e) {
418 var self = this, $e = $(e.currentTarget);
419 var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
420 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
421 this.rpc('/base/dataset/unlink', {
422 model: 'ir.attachment',
423 ids: [parseInt($e.attr('data-id'))]
425 $e.parent().remove();
426 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
431 if (this.datarecord.id) {
432 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
434 this.on_button_new();
437 get_fields_values: function() {
439 _.each(this.fields, function(value, key) {
440 values[key] = value.get_value();
447 openerp.base.form = {};
449 openerp.base.form.compute_domain = function(expr, fields) {
451 for (var i = expr.length - 1; i >= 0; i--) {
453 if (ex.length == 1) {
454 var top = stack.pop();
457 stack.push(stack.pop() || top);
460 stack.push(stack.pop() && top);
466 throw new Error('Unknown domain operator ' + ex);
470 var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
474 switch (op.toLowerCase()) {
477 stack.push(field == val);
481 stack.push(field != val);
484 stack.push(field < val);
487 stack.push(field > val);
490 stack.push(field <= val);
493 stack.push(field >= val);
496 stack.push(_(val).contains(field));
499 stack.push(!_(val).contains(field));
502 this.log("Unsupported operator in attrs :", op);
508 openerp.base.form.Widget = openerp.base.Controller.extend({
510 init: function(view, node) {
513 this.attrs = JSON.parse(this.node.attrs.attrs || '{}');
514 this.type = this.type || node.tag;
515 this.element_name = this.element_name || this.type;
516 this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
518 this._super(this.view.session, this.element_id);
520 this.view.widgets[this.element_id] = this;
521 this.children = node.children;
522 this.colspan = parseInt(node.attrs.colspan || 1);
524 this.string = this.string || node.attrs.string;
525 this.help = this.help || node.attrs.help;
526 this.invisible = (node.attrs.invisible == '1');
529 this.$element = $('#' + this.element_id);
531 process_attrs: function() {
532 var compute_domain = openerp.base.form.compute_domain;
533 for (var a in this.attrs) {
534 this[a] = compute_domain(this.attrs[a], this.view.fields);
537 update_dom: function() {
538 this.$element.toggle(!this.invisible);
541 var template = this.template;
542 return QWeb.render(template, { "widget": this });
546 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
547 template: 'WidgetFrame',
548 init: function(view, node) {
549 this._super(view, node);
550 this.columns = node.attrs.col || 4;
555 for (var i = 0; i < node.children.length; i++) {
556 var n = node.children[i];
557 if (n.tag == "newline") {
563 this.set_row_cells_with(this.table[this.table.length - 1]);
566 if (this.table.length) {
567 this.set_row_cells_with(this.table[this.table.length - 1]);
570 this.table.push(row);
575 set_row_cells_with: function(row) {
576 for (var i = 0; i < row.length; i++) {
578 if (w.is_field_label) {
581 row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
583 } else if (w.width === undefined) {
584 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
588 handle_node: function(node) {
589 var type = this.view.fields_view.fields[node.attrs.name] || {};
590 var widget = new (this.view.registry.get_any(
591 [node.attrs.widget, type.type, node.tag])) (this.view, node);
592 if (node.tag == 'field') {
593 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
594 this.view.default_focus_field = widget;
596 if (node.attrs.nolabel != '1') {
597 var label = new (this.view.registry.get_object('label')) (this.view, node);
598 label["for"] = widget;
599 this.add_widget(label);
602 this.add_widget(widget);
604 add_widget: function(widget) {
605 var current_row = this.table[this.table.length - 1];
606 if (current_row.length && (this.x + widget.colspan) > this.columns) {
607 current_row = this.add_row();
609 current_row.push(widget);
610 this.x += widget.colspan;
615 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
616 init: function(view, node) {
617 this._super(view, node);
618 this.template = "WidgetNotebook";
620 for (var i = 0; i < node.children.length; i++) {
621 var n = node.children[i];
622 if (n.tag == "page") {
623 var page = new openerp.base.form.WidgetFrame(this.view, n);
624 this.pages.push(page);
629 this._super.apply(this, arguments);
630 this.$element.tabs();
634 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
635 init: function(view, node) {
636 this._super(view, node);
637 this.template = "WidgetSeparator";
641 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
642 init: function(view, node) {
643 this._super(view, node);
644 this.template = "WidgetButton";
645 if (node.attrs.default_focus == '1') {
646 // TODO fme: provide enter key binding to widgets
647 this.view.default_focus_button = this;
651 this._super.apply(this, arguments);
652 this.$element.click(this.on_click);
654 on_click: function(saved) {
656 if (!this.node.attrs.special && this.view.touched && saved !== true) {
657 this.view.do_save(function() {
661 if (this.node.attrs.confirm) {
662 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
668 $(this).dialog("close");
671 $(this).dialog("close");
680 on_confirmed: function() {
683 this.view.execute_action(
684 this.node.attrs, this.view.dataset, this.session.action_manager,
685 this.view.datarecord.id, function (result) {
686 self.log("Button returned", result);
694 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
695 init: function(view, node) {
696 this.element_name = 'label_' + node.attrs.name;
698 this._super(view, node);
700 // TODO fme: support for attrs.align
701 if (this.node.tag == 'label' && this.node.attrs.colspan) {
702 this.is_field_label = false;
703 this.template = "WidgetParagraph";
705 this.is_field_label = true;
706 this.template = "WidgetLabel";
710 render: function () {
711 if (this['for'] && this.type !== 'label') {
712 return QWeb.render(this.template, {widget: this['for']});
714 // Actual label widgets should not have a false and have type label
715 return QWeb.render(this.template, {widget: this});
719 openerp.base.form.Field = openerp.base.form.Widget.extend({
720 init: function(view, node) {
721 this.name = node.attrs.name;
722 this.value = undefined;
723 view.fields[this.name] = this;
724 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
725 this.element_name = "field_" + this.name + "_" + this.type;
727 this._super(view, node);
729 if (node.attrs.nolabel != '1' && this.colspan > 1) {
732 this.field = view.fields_view.fields[node.attrs.name] || {};
733 this.string = node.attrs.string || this.field.string;
734 this.help = node.attrs.help || this.field.help;
735 this.invisible = (this.invisible || this.field.invisible == '1');
736 this.nolabel = (this.field.nolabel || node.attrs.nolabel) == '1';
737 this.readonly = (this.field.readonly || node.attrs.readonly) == '1';
738 this.required = (this.field.required || node.attrs.required) == '1';
739 this.invalid = false;
740 this.touched = false;
742 set_value: function(value) {
744 this.invalid = false;
747 set_value_from_ui: function() {
748 this.value = undefined;
750 get_value: function() {
753 get_on_change_value: function() {
754 return this.get_value();
756 update_dom: function() {
757 this._super.apply(this, arguments);
758 this.$element.toggleClass('disabled', this.readonly);
759 this.$element.toggleClass('required', this.required);
760 if (this.view.show_invalid) {
761 this.$element.toggleClass('invalid', this.invalid);
764 on_ui_change: function() {
765 this.touched = this.view.touched = true;
768 this.set_value_from_ui();
769 this.view.do_onchange(this);
770 this.view.on_form_changed();
775 validate: function() {
776 this.invalid = false;
780 _build_view_fields_values: function() {
781 var a_dataset = this.view.dataset || {};
782 var fields_values = this.view.get_fields_values();
783 var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
784 fields_values.parent = parent_values;
785 return fields_values;
788 * Builds a new context usable for operations related to fields by merging
789 * the fields'context with the action's context.
791 build_context: function() {
792 var a_context = this.view.dataset.get_context() || {};
793 var f_context = this.field.context || {};
794 var v_context1 = this.node.attrs.default_get || {};
795 var v_context2 = this.node.attrs.context || {};
796 var v_context = new openerp.base.CompoundContext(v_context1, v_context2);
797 if (v_context1.__ref || v_context2.__ref) {
798 var fields_values = this._build_view_fields_values();
799 v_context.set_eval_context(fields_values);
801 var ctx = new openerp.base.CompoundContext(a_context, f_context, v_context);
804 build_domain: function() {
805 var f_domain = this.field.domain || [];
806 var v_domain = this.node.attrs.domain || [];
807 if (!(v_domain instanceof Array)) {
808 var fields_values = this._build_view_fields_values();
809 v_domain = new openerp.base.CompoundDomain(v_domain).set_eval_context(fields_values);
811 return new openerp.base.CompoundDomain(f_domain, v_domain);
815 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
816 init: function(view, node) {
817 this._super(view, node);
818 this.template = "FieldChar";
821 this._super.apply(this, arguments);
822 this.$element.find('input').change(this.on_ui_change);
824 set_value: function(value) {
825 this._super.apply(this, arguments);
826 var show_value = (value != null && value !== false) ? value : '';
827 this.$element.find('input').val(show_value);
829 update_dom: function() {
830 this._super.apply(this, arguments);
831 this.$element.find('input').attr('disabled', this.readonly);
833 set_value_from_ui: function() {
834 this.value = this.$element.find('input').val();
836 validate: function() {
837 this.invalid = false;
838 var value = this.$element.find('input').val();
840 this.invalid = this.required;
841 } else if (this.validation_regex) {
842 this.invalid = !this.validation_regex.test(value);
846 this.$element.find('input').focus();
850 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
851 init: function(view, node) {
852 this._super(view, node);
853 this.template = "FieldEmail";
854 this.validation_regex = /@/;
857 this._super.apply(this, arguments);
858 this.$element.find('button').click(this.on_button_clicked);
860 on_button_clicked: function() {
861 if (!this.value || this.invalid) {
862 this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
864 location.href = 'mailto:' + this.value;
867 set_value: function(value) {
868 this._super.apply(this, arguments);
869 var show_value = (value != null && value !== false) ? value : '';
870 this.$element.find('a').attr('href', 'mailto:' + show_value);
874 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
875 init: function(view, node) {
876 this._super(view, node);
877 this.template = "FieldUrl";
880 this._super.apply(this, arguments);
881 this.$element.find('button').click(this.on_button_clicked);
883 on_button_clicked: function() {
885 this.notification.warn("Resource error", "This resource is empty");
887 window.open(this.value);
892 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
893 init: function(view, node) {
894 this._super(view, node);
895 this.validation_regex = /^-?\d+(\.\d+)?$/;
897 set_value: function(value) {
898 this._super.apply(this, [value]);
899 if (value === false || value === undefined) {
900 // As in GTK client, floats default to 0
903 var show_value = value.toFixed(2);
904 this.$element.find('input').val(show_value);
906 set_value_from_ui: function() {
907 this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
911 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
912 init: function(view, node) {
913 this._super(view, node);
914 this.template = "FieldDate";
915 this.jqueryui_object = 'datetimepicker';
916 this.validation_regex = /^\d+-\d+-\d+( \d+:\d+(:\d+)?)?$/;
919 this._super.apply(this, arguments);
920 this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
921 dateFormat: 'yy-mm-dd',
922 timeFormat: 'hh:mm:ss',
924 buttonImage: '/base/static/src/img/ui/field_calendar.png',
925 buttonImageOnly: true,
926 constrainInput: false
929 set_value: function(value) {
930 this._super.apply(this, arguments);
931 if (value == null || value == false) {
932 this.$element.find('input').val('');
934 this.$element.find('input').unbind('change');
935 // jQuery UI date picker wrongly call on_change event herebelow
936 this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
937 this.$element.find('input').change(this.on_ui_change);
940 set_value_from_ui: function() {
941 this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
943 this.value = this.format(this.value);
946 update_dom: function() {
947 this._super.apply(this, arguments);
948 this.$element.find('input').attr('disabled', this.readonly);
950 validate: function() {
951 this.invalid = false;
952 var value = this.$element.find('input').val();
954 this.invalid = this.required;
955 } else if (this.validation_regex) {
956 this.invalid = !this.validation_regex.test(value);
958 this.invalid = !this.$element.find('input')[this.jqueryui_object]('getDate');
962 this.$element.find('input').focus();
964 parse: openerp.base.parse_datetime,
965 format: openerp.base.format_datetime
968 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
969 init: function(view, node) {
970 this._super(view, node);
971 this.jqueryui_object = 'datepicker';
972 this.validation_regex = /^\d+-\d+-\d+$/;
974 parse: openerp.base.parse_date,
975 format: openerp.base.format_date
978 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
979 init: function(view, node) {
980 this._super(view, node);
981 this.validation_regex = /^\d+:\d+$/;
983 set_value: function(value) {
984 this._super.apply(this, [value]);
985 if (value === false || value === undefined) {
986 // As in GTK client, floats default to 0
989 var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
990 this.$element.find('input').val(show_value);
992 set_value_from_ui: function() {
993 var time = this.$element.find('input').val().split(':');
994 this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
998 openerp.base.form.FieldText = openerp.base.form.Field.extend({
999 init: function(view, node) {
1000 this._super(view, node);
1001 this.template = "FieldText";
1002 this.validation_regex = null;
1005 this._super.apply(this, arguments);
1006 this.$element.find('textarea').change(this.on_ui_change);
1008 set_value: function(value) {
1009 this._super.apply(this, arguments);
1010 var show_value = (value != null && value !== false) ? value : '';
1011 this.$element.find('textarea').val(show_value);
1013 update_dom: function() {
1014 this._super.apply(this, arguments);
1015 this.$element.find('textarea').attr('disabled', this.readonly);
1017 set_value_from_ui: function() {
1018 this.value = this.$element.find('textarea').val();
1020 validate: function() {
1021 this.invalid = false;
1022 var value = this.$element.find('textarea').val();
1024 this.invalid = this.required;
1025 } else if (this.validation_regex) {
1026 this.invalid = !this.validation_regex.test(value);
1030 this.$element.find('textarea').focus();
1034 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
1035 init: function(view, node) {
1036 this._super(view, node);
1037 this.template = "FieldBoolean";
1041 this._super.apply(this, arguments);
1042 this.$element.find('input').click(function() {
1043 if ($(this).is(':checked') != self.value) {
1044 self.on_ui_change();
1048 set_value: function(value) {
1049 this._super.apply(this, arguments);
1050 this.$element.find('input')[0].checked = value;
1052 set_value_from_ui: function() {
1053 this.value = this.$element.find('input').is(':checked');
1055 update_dom: function() {
1056 this._super.apply(this, arguments);
1057 this.$element.find('input').attr('disabled', this.readonly);
1059 validate: function() {
1060 this.invalid = this.required && !this.$element.find('input').is(':checked');
1063 this.$element.find('input').focus();
1067 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1068 init: function(view, node) {
1069 this._super(view, node);
1070 this.template = "FieldProgressBar";
1073 this._super.apply(this, arguments);
1074 this.$element.find('div').progressbar({
1076 disabled: this.readonly
1079 set_value: function(value) {
1080 this._super.apply(this, arguments);
1081 var show_value = Number(value);
1082 if (show_value === NaN) {
1085 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1089 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1090 // to replace view editor
1093 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1094 init: function(view, node) {
1095 this._super(view, node);
1096 this.template = "FieldSelection";
1099 this._super.apply(this, arguments);
1100 this.$element.find('select').change(this.on_ui_change);
1102 set_value: function(value) {
1103 this._super.apply(this, arguments);
1104 if (value != null && value !== false) {
1105 this.$element.find('select').val(value);
1107 this.$element.find('select').val('false');
1110 set_value_from_ui: function() {
1111 this.value = this.$element.find('select').val();
1113 update_dom: function() {
1114 this._super.apply(this, arguments);
1115 this.$element.find('select').attr('disabled', this.readonly);
1117 validate: function() {
1118 this.invalid = this.required && this.$element.find('select').val() === "";
1121 this.$element.find('select').focus();
1125 // jquery autocomplete tweak to allow html
1127 var proto = $.ui.autocomplete.prototype,
1128 initSource = proto._initSource;
1130 function filter( array, term ) {
1131 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1132 return $.grep( array, function(value) {
1133 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1138 _initSource: function() {
1139 if ( this.options.html && $.isArray(this.options.source) ) {
1140 this.source = function( request, response ) {
1141 response( filter( this.options.source, request.term ) );
1144 initSource.call( this );
1148 _renderItem: function( ul, item) {
1149 return $( "<li></li>" )
1150 .data( "item.autocomplete", item )
1151 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1157 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1158 init: function(view, node) {
1159 this._super(view, node);
1160 this.template = "FieldMany2One";
1163 this.cm_id = _.uniqueId('m2o_cm_');
1164 this.last_search = [];
1165 this.tmp_value = undefined;
1170 this.$input = this.$element.find("input");
1171 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1172 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1176 bindings[this.cm_id + "_search"] = function() {
1177 self._search_create_popup("search");
1179 bindings[this.cm_id + "_create"] = function() {
1180 self._search_create_popup("form");
1182 bindings[this.cm_id + "_open"] = function() {
1186 self.session.action_manager.do_action({
1187 "res_model": self.field.relation,
1188 "views":[[false,"form"]],
1189 "res_id": self.value[0],
1190 "type":"ir.actions.act_window",
1192 "context": self.build_context()
1195 var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1196 bindings: bindings, itemStyle: {"color": ""},
1197 onContextMenu: function() {
1199 $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1201 $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1207 // some behavior for input
1208 this.$input.keyup(function() {
1209 if (self.$input.val() === "") {
1210 self._change_int_value(null);
1211 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1212 self._change_int_value(undefined);
1215 this.$drop_down.click(function() {
1216 if (self.$input.autocomplete("widget").is(":visible")) {
1217 self.$input.autocomplete("close");
1220 self.$input.autocomplete("search", "");
1222 self.$input.autocomplete("search");
1224 self.$input.focus();
1227 var anyoneLoosesFocus = function() {
1228 if (!self.$input.is(":focus") &&
1229 !self.$input.autocomplete("widget").is(":visible") &&
1231 if(self.value === undefined && self.last_search.length > 0) {
1232 self._change_int_ext_value(self.last_search[0]);
1234 self._change_int_ext_value(null);
1238 this.$input.focusout(anyoneLoosesFocus);
1241 this.$input.autocomplete({
1242 source: function(req, resp) { self.get_search_result(req, resp); },
1243 select: function(event, ui) {
1246 self._change_int_value([item.id, item.name]);
1247 } else if (item.action) {
1248 self._change_int_value(undefined);
1253 focus: function(e, ui) {
1257 close: anyoneLoosesFocus,
1262 // autocomplete component content handling
1263 get_search_result: function(request, response) {
1264 var search_val = request.term;
1267 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1269 dataset.name_search(search_val, self.build_domain(), 'ilike',
1270 this.limit + 1, function(data) {
1271 self.last_search = data.result;
1272 // possible selections for the m2o
1273 var values = _.map(data.result, function(x) {
1274 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1277 // search more... if more results that max
1278 if (values.length > self.limit) {
1279 values = values.slice(0, self.limit);
1280 values.push({label: "<em>Â Â Â Search More...</em>", action: function() {
1281 dataset.name_search(search_val, self.build_domain(), 'ilike'
1282 , false, function(data) {
1283 self._change_int_value(null);
1284 self._search_create_popup("search", data.result);
1289 var raw_result = _(data.result).map(function(x) {return x[1];})
1290 if (search_val.length > 0 &&
1291 !_.include(raw_result, search_val) &&
1292 (!self.value || search_val !== self.value[1])) {
1293 values.push({label: '<em>Â Â Â Create "<strong>' +
1294 $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1295 self._quick_create(search_val);
1299 values.push({label: "<em>Â Â Â Create and Edit...</em>", action: function() {
1300 self._change_int_value(null);
1301 self._search_create_popup("form");
1307 _quick_create: function(name) {
1309 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1310 dataset.name_create(name, function(data) {
1311 self._change_int_ext_value(data.result);
1312 }).fail(function(error, event) {
1313 event.preventDefault();
1314 self._change_int_value(null);
1315 self._search_create_popup("form", undefined, {"default_name": name});
1318 // all search/create popup handling
1319 _search_create_popup: function(view, ids, context) {
1321 var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1322 pop.select_element(self.field.relation,{
1323 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1325 disable_multiple_selection: true
1326 }, self.build_domain(),
1327 new openerp.base.CompoundContext(self.build_context(), context || {}));
1328 pop.on_select_elements.add(function(element_ids) {
1329 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1330 dataset.name_get([element_ids[0]], function(data) {
1331 self._change_int_ext_value(data.result[0]);
1336 _change_int_ext_value: function(value) {
1337 this._change_int_value(value);
1338 this.$input.val(this.value ? this.value[1] : "");
1340 _change_int_value: function(value) {
1342 var back_orig_value = this.original_value;
1343 if (this.value === null || this.value) {
1344 this.original_value = this.value;
1346 if (back_orig_value === undefined) { // first use after a set_value()
1349 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1350 !== (this.value ? this.value[0] : null))) {
1351 this.on_ui_change();
1354 set_value_from_ui: function() {},
1355 set_value: function(value) {
1356 value = value || null;
1358 var _super = this._super;
1359 this.tmp_value = value;
1360 var real_set_value = function(rval) {
1361 self.tmp_value = undefined;
1362 _super.apply(self, rval);
1363 self.original_value = undefined;
1364 self._change_int_ext_value(rval);
1366 if(typeof(value) === "number") {
1367 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1368 dataset.name_get([value], function(data) {
1369 real_set_value(data.result[0]);
1370 }).fail(function() {self.tmp_value = undefined;});
1372 setTimeout(function() {real_set_value(value);}, 0);
1375 get_value: function() {
1376 if (this.tmp_value !== undefined) {
1377 if (this.tmp_value instanceof Array) {
1378 return this.tmp_value[0];
1380 return this.tmp_value ? this.tmp_value : false;
1382 if (this.value === undefined)
1383 return this.original_value ? this.original_value[0] : false;
1384 return this.value ? this.value[0] : false;
1386 validate: function() {
1387 this.invalid = false;
1388 if (this.value === null) {
1389 this.invalid = this.required;
1395 # Values: (0, 0, { fields }) create
1396 # (1, ID, { fields }) update
1397 # (2, ID) remove (delete)
1398 # (3, ID) unlink one (target id or target of relation)
1400 # (5) unlink all (only valid for one2many)
1405 'create': function (values) {
1406 return [commands.CREATE, false, values];
1408 // (1, id, {values})
1410 'update': function (id, values) {
1411 return [commands.UPDATE, id, values];
1415 'delete': function (id) {
1416 return [commands.DELETE, id, false];
1418 // (3, id[, _]) removes relation, but not linked record itself
1420 'forget': function (id) {
1421 return [commands.FORGET, id, false];
1425 'link_to': function (id) {
1426 return [commands.LINK_TO, id, false];
1430 'delete_all': function () {
1431 return [5, false, false];
1433 // (6, _, ids) replaces all linked records with provided ids
1435 'replace_with': function (ids) {
1436 return [6, false, ids];
1439 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1440 init: function(view, node) {
1441 this._super(view, node);
1442 this.template = "FieldOne2Many";
1443 this.is_started = $.Deferred();
1446 this._super.apply(this, arguments);
1450 this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1451 this.dataset.o2m = this;
1452 this.dataset.parent_view = this.view;
1453 this.dataset.on_change.add_last(function() {
1454 self.on_ui_change();
1457 var modes = this.node.attrs.mode;
1458 modes = !!modes ? modes.split(",") : ["tree", "form"];
1460 _.each(modes, function(mode) {
1461 var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1462 if (self.field.views && self.field.views[mode]) {
1463 view.embedded_view = self.field.views[mode];
1465 if(view.view_type === "list") {
1473 this.viewmanager = new openerp.base.ViewManager(this.view.session,
1474 this.element_id, this.dataset, views);
1475 this.viewmanager.registry = openerp.base.views.clone({
1476 list: 'openerp.base.form.One2ManyListView'
1479 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1480 if (view_type == "list") {
1481 controller.o2m = self;
1482 } else if (view_type == "form") {
1485 self.is_started.resolve();
1487 this.viewmanager.start();
1489 reload_current_view: function() {
1491 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1492 if(self.viewmanager.active_view === "list") {
1493 view.reload_content();
1494 } else if (self.viewmanager.active_view === "form") {
1495 // TODO niv: implement
1498 set_value_from_ui: function() {},
1499 set_value: function(value) {
1500 value = value || [];
1502 this.dataset.reset_ids([]);
1503 if(value.length >= 1 && value[0] instanceof Array) {
1505 _.each(value, function(command) {
1506 var obj = {values: command[2]};
1507 switch (command[0]) {
1508 case commands.CREATE:
1509 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1510 self.dataset.to_create.push(obj);
1511 self.dataset.cache.push(_.clone(obj));
1514 case commands.UPDATE:
1515 obj['id'] = command[1];
1516 self.dataset.to_write.push(obj);
1517 self.dataset.cache.push(_.clone(obj));
1520 case commands.DELETE:
1521 self.dataset.to_delete.push({id: command[1]});
1523 case commands.LINK_TO:
1524 ids.push(command[1]);
1526 case commands.DELETE_ALL:
1527 self.dataset.delete_all = true;
1532 this.dataset.set_ids(ids);
1533 } else if (value.length >= 1 && typeof(value[0]) === "object") {
1535 this.dataset.delete_all = true;
1536 _.each(value, function(command) {
1537 var obj = {values: command};
1538 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1539 self.dataset.to_create.push(obj);
1540 self.dataset.cache.push(_.clone(obj));
1544 this.dataset.set_ids(ids);
1547 this.dataset.reset_ids(value);
1549 $.when(this.is_started).then(function() {
1550 self.reload_current_view();
1553 get_value: function() {
1557 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1558 val = val.concat(_.map(this.dataset.ids, function(id) {
1559 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1561 return commands.create(alter_order.values);
1563 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1565 return commands.update(alter_order.id, alter_order.values);
1567 return commands.link_to(id);
1569 return val.concat(_.map(
1570 this.dataset.to_delete, function(x) {
1571 return commands['delete'](x.id);}));
1573 validate: function() {
1574 this.invalid = false;
1579 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1580 get_context: function() {
1581 this.context = this.o2m.build_context();
1582 return this.context;
1586 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1587 do_add_record: function () {
1589 var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1590 pop.select_element(self.o2m.field.relation,{
1591 initial_view: "form",
1592 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1594 parent_view: self.o2m.view
1595 }, self.o2m.build_domain(), self.o2m.build_context());
1596 pop.on_create.add(function(data) {
1597 self.o2m.dataset.create(data, function(r) {
1598 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1599 self.o2m.dataset.on_change();
1601 self.o2m.reload_current_view();
1607 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1608 init: function(view, node) {
1609 this._super(view, node);
1610 this.template = "FieldMany2Many";
1611 this.list_id = _.uniqueId("many2many");
1612 this.is_started = $.Deferred();
1615 this._super.apply(this, arguments);
1619 this.dataset = new openerp.base.form.Many2ManyDataSet(
1620 this.session, this.field.relation);
1621 this.dataset.m2m = this;
1622 this.dataset.on_unlink.add_last(function(ids) {
1623 self.on_ui_change();
1626 this.list_view = new openerp.base.form.Many2ManyListView(
1627 null, this.view.session, this.list_id, this.dataset, false, {
1630 this.list_view.m2m_field = this;
1631 this.list_view.on_loaded.add_last(function() {
1632 self.is_started.resolve();
1634 this.list_view.start();
1636 set_value: function(value) {
1637 value = value || [];
1638 if (value.length >= 1 && value[0] instanceof Array) {
1639 value = value[0][2];
1642 this.dataset.set_ids(value);
1644 $.when(this.is_started).then(function() {
1645 self.list_view.reload_content();
1648 get_value: function() {
1649 return [commands.replace_with(this.dataset.ids)];
1651 set_value_from_ui: function() {},
1652 validate: function() {
1653 this.invalid = false;
1658 openerp.base.form.Many2ManyDataSet = openerp.base.DataSetStatic.extend({
1659 get_context: function() {
1660 this.context = this.m2m.build_context();
1661 return this.context;
1665 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1666 do_add_record: function () {
1667 var pop = new openerp.base.form.SelectCreatePopup(
1668 null, this.m2m_field.view.session);
1669 pop.select_element(this.model, {}, this.m2m_field.build_domain(), this.m2m_field.build_context());
1671 pop.on_select_elements.add(function(element_ids) {
1672 _.each(element_ids, function(element_id) {
1673 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1674 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1675 self.m2m_field.on_ui_change();
1676 self.reload_content();
1682 do_activate_record: function(index, id) {
1683 this.m2m_field.view.session.action_manager.do_action({
1684 "res_model": this.dataset.model,
1685 "views": [[false,"form"]],
1687 "type": "ir.actions.act_window",
1688 "view_type": "form",
1689 "view_mode": "form",
1691 "context": this.m2m_field.build_context()
1696 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1697 identifier_prefix: "selectcreatepopup",
1698 template: "SelectCreatePopup",
1702 * - initial_view: form or search (default search)
1703 * - disable_multiple_selection
1704 * - alternative_form_view
1705 * - auto_create (default true)
1708 select_element: function(model, options, domain, context) {
1710 this.domain = domain || [];
1711 this.context = context || {};
1712 this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1713 this.initial_ids = this.options.initial_ids;
1714 jQuery(this.render()).dialog({title: '',
1721 this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1722 this.context, this.domain);
1723 this.dataset.parent_view = this.options.parent_view;
1724 if (this.options.initial_view == "search") {
1725 this.setup_search_view();
1730 setup_search_view: function() {
1732 if (this.searchview) {
1733 this.searchview.stop();
1735 this.searchview = new openerp.base.SearchView(null, this.session,
1736 this.element_id + "_search", this.dataset, false, {
1737 "selectable": !this.options.disable_multiple_selection,
1740 this.searchview.on_search.add(function(domains, contexts, groupbys) {
1741 if (self.initial_ids) {
1742 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]]]),
1743 contexts, groupbys);
1744 self.initial_ids = undefined;
1746 self.view_list.do_search.call(self, domains, contexts, groupbys);
1749 this.searchview.on_loaded.add_last(function () {
1750 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1751 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1752 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1753 $cbutton.click(function() {
1756 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1757 if(self.options.disable_multiple_selection) {
1760 $sbutton.click(function() {
1761 self.on_select_elements(self.selected_ids);
1763 self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1764 self.element_id + "_view_list", self.dataset, false,
1765 {'deletable': false});
1766 self.view_list.popup = self;
1767 self.view_list.do_show();
1768 self.view_list.start().then(function() {
1769 self.searchview.do_search();
1772 this.searchview.start();
1774 on_create: function(data) {
1775 if (!this.options.auto_create)
1778 var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1779 wdataset = this.options.parent_view;
1780 wdataset.create(data, function(r) {
1781 self.on_select_elements([r.result]);
1784 on_select_elements: function(element_ids) {
1786 on_click_element: function(ids) {
1787 this.selected_ids = ids || [];
1788 if(this.selected_ids.length > 0) {
1789 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1791 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1794 new_object: function() {
1796 if (this.searchview) {
1797 this.searchview.hide();
1799 if (this.view_list) {
1800 this.view_list.$element.hide();
1802 this.dataset.index = null;
1803 this.view_form = new openerp.base.FormView(null, this.session,
1804 this.element_id + "_view_form", this.dataset, false);
1805 if (this.options.alternative_form_view) {
1806 this.view_form.set_embedded_view(this.options.alternative_form_view);
1808 this.view_form.start();
1809 this.view_form.on_loaded.add_last(function() {
1810 var $buttons = self.view_form.$element.find(".oe_form_buttons");
1811 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1812 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1813 $nbutton.click(function() {
1814 self.view_form.do_save();
1816 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1817 $cbutton.click(function() {
1821 this.dataset.on_create.add(this.on_create);
1822 this.view_form.do_show();
1826 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1827 do_add_record: function () {
1828 this.popup.new_object();
1830 select_record: function(index) {
1831 this.popup.on_select_elements([this.dataset.ids[index]]);
1833 do_select: function(ids, records) {
1834 this._super(ids, records);
1835 this.popup.on_click_element(ids);
1839 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1840 init: function(view, node) {
1841 this._super(view, node);
1842 this.template = "FieldReference";
1846 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1847 init: function(view, node) {
1848 this._super(view, node);
1849 this.iframe = this.element_id + '_iframe';
1850 this.binary_value = false;
1853 this._super.apply(this, arguments);
1854 this.$element.find('input.oe-binary-file').change(this.on_file_change);
1855 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1856 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1858 set_value_from_ui: function() {
1860 human_filesize : function(size) {
1861 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1863 while (size >= 1024) {
1867 return size.toFixed(2) + ' ' + units[i];
1869 on_file_change: function(e) {
1870 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1871 // http://www.html5rocks.com/tutorials/file/dndfiles/
1872 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1873 window[this.iframe] = this.on_file_uploaded;
1874 if ($(e.target).val() != '') {
1875 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1876 this.$element.find('form.oe-binary-form').submit();
1877 this.toggle_progress();
1880 toggle_progress: function() {
1881 this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1883 on_file_uploaded: function(size, name, content_type, file_base64) {
1884 delete(window[this.iframe]);
1885 if (size === false) {
1886 this.notification.warn("File Upload", "There was a problem while uploading your file");
1887 // TODO: use openerp web exception handler
1888 console.log("Error while uploading file : ", name);
1890 this.on_file_uploaded_and_valid.apply(this, arguments);
1891 this.on_ui_change();
1893 this.toggle_progress();
1895 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1897 on_save_as: function() {
1898 if (!this.view.datarecord.id) {
1899 this.notification.warn("Can't save file", "The record has not yet been saved");
1901 var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1902 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1903 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1907 on_clear: function() {
1908 if (this.value !== false) {
1910 this.binary_value = false;
1911 this.on_ui_change();
1917 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1918 init: function(view, node) {
1919 this._super(view, node);
1920 this.template = "FieldBinaryFile";
1922 set_value: function(value) {
1923 this._super.apply(this, arguments);
1924 var show_value = (value != null && value !== false) ? value : '';
1925 this.$element.find('input').eq(0).val(show_value);
1927 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1928 this.value = file_base64;
1929 this.binary_value = true;
1930 var show_value = this.human_filesize(size);
1931 this.$element.find('input').eq(0).val(show_value);
1932 this.set_filename(name);
1934 set_filename: function(value) {
1935 var filename = this.node.attrs.filename;
1936 if (this.view.fields[filename]) {
1937 this.view.fields[filename].set_value(value);
1938 this.view.fields[filename].on_ui_change();
1941 on_clear: function() {
1942 this._super.apply(this, arguments);
1943 this.$element.find('input').eq(0).val('');
1944 this.set_filename('');
1948 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1949 init: function(view, node) {
1950 this._super(view, node);
1951 this.template = "FieldBinaryImage";
1954 this._super.apply(this, arguments);
1955 this.$image = this.$element.find('img.oe-binary-image');
1957 set_image_maxwidth: function() {
1958 this.$image.css('max-width', this.$element.width());
1960 on_file_change: function() {
1961 this.set_image_maxwidth();
1962 this._super.apply(this, arguments);
1964 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1965 this.value = file_base64;
1966 this.binary_value = true;
1967 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
1969 on_clear: function() {
1970 this._super.apply(this, arguments);
1971 this.$image.attr('src', '/base/static/src/img/placeholder.png');
1973 set_value: function(value) {
1974 this._super.apply(this, arguments);
1975 this.set_image_maxwidth();
1976 var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
1977 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
1978 this.$image.attr('src', url);
1983 * Registry of form widgets, called by :js:`openerp.base.FormView`
1985 openerp.base.form.widgets = new openerp.base.Registry({
1986 'frame' : 'openerp.base.form.WidgetFrame',
1987 'group' : 'openerp.base.form.WidgetFrame',
1988 'notebook' : 'openerp.base.form.WidgetNotebook',
1989 'separator' : 'openerp.base.form.WidgetSeparator',
1990 'label' : 'openerp.base.form.WidgetLabel',
1991 'button' : 'openerp.base.form.WidgetButton',
1992 'char' : 'openerp.base.form.FieldChar',
1993 'email' : 'openerp.base.form.FieldEmail',
1994 'url' : 'openerp.base.form.FieldUrl',
1995 'text' : 'openerp.base.form.FieldText',
1996 'text_wiki' : 'openerp.base.form.FieldText',
1997 'date' : 'openerp.base.form.FieldDate',
1998 'datetime' : 'openerp.base.form.FieldDatetime',
1999 'selection' : 'openerp.base.form.FieldSelection',
2000 'many2one' : 'openerp.base.form.FieldMany2One',
2001 'many2many' : 'openerp.base.form.FieldMany2Many',
2002 'one2many' : 'openerp.base.form.FieldOne2Many',
2003 'one2many_list' : 'openerp.base.form.FieldOne2Many',
2004 'reference' : 'openerp.base.form.FieldReference',
2005 'boolean' : 'openerp.base.form.FieldBoolean',
2006 'float' : 'openerp.base.form.FieldFloat',
2007 'integer': 'openerp.base.form.FieldFloat',
2008 'progressbar': 'openerp.base.form.FieldProgressBar',
2009 'float_time': 'openerp.base.form.FieldFloatTime',
2010 'image': 'openerp.base.form.FieldBinaryImage',
2011 'binary': 'openerp.base.form.FieldBinaryFile'
2016 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: