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) {
135 w.process_modifiers();
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?$/);
170 var method = call[1], args = [];
171 var context_index = null;
172 var argument_replacement = {
173 'False' : function() {return false;},
174 'True' : function() {return true;},
175 'None' : function() {return null;},
176 'context': function(i) {
178 var ctx = widget.build_context ? widget.build_context() : {};
182 var parent_fields = null;
183 _.each(call[2].split(','), function(a, i) {
184 var field = _.trim(a);
185 if (field in argument_replacement) {
186 args.push(argument_replacement[field](i));
188 } else if (self.fields[field]) {
189 var value = self.fields[field].get_on_change_value();
190 args.push(value == null ? false : value);
193 var splitted = field.split('.');
194 if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
195 if (parent_fields === null) {
196 parent_fields = self.dataset.parent_view.get_fields_values();
198 var p_val = parent_fields[_.trim(splitted[1])];
199 if (p_val !== undefined) {
200 args.push(p_val == null ? false : p_val);
205 throw "Could not get field with name '" + field +
206 "' for onchange '" + onchange + "'";
209 url: '/base/dataset/call',
212 return this.rpc(ajax, {
213 model: this.dataset.model,
215 args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args),
216 context_id: context_index === null ? null : context_index + 1
217 }, function(response) {
218 self.on_processed_onchange(response, processed);
221 this.log("Wrong on_change format", on_change);
225 on_processed_onchange: function(response, processed) {
226 var result = response.result;
228 for (var f in result.value) {
229 var field = this.fields[f];
231 var value = result.value[f];
232 processed.push(field.name);
233 if (field.get_value() != value) {
234 field.set_value(value);
235 field.touched = true;
236 if (_.indexOf(processed, field.name) < 0) {
237 this.do_onchange(field, processed);
241 // this is a common case, the normal behavior should be to ignore it
244 this.on_form_changed();
246 if (!_.isEmpty(result.warning)) {
247 $(QWeb.render("DialogWarning", result.warning)).dialog({
251 $(this).dialog("close");
261 on_button_new: function() {
263 $.when(this.has_been_loaded).then(function() {
264 self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
265 self.on_record_loaded(result.result);
270 * Triggers saving the form's record. Chooses between creating a new
271 * record or saving an existing one depending on whether the record
272 * already has an id property.
274 * @param {Function} success callback on save success
275 * @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)
277 do_save: function(success, prepend_on_create) {
284 first_invalid_field = null;
285 for (var f in this.fields) {
290 if (!first_invalid_field) {
291 first_invalid_field = f;
293 } else if (f.touched) {
294 values[f.name] = f.get_value();
298 first_invalid_field.focus();
302 this.log("About to save", values);
303 if (!this.datarecord.id) {
304 this.dataset.create(values, function(r) {
305 self.on_created(r, success, prepend_on_create);
308 this.dataset.write(this.datarecord.id, values, function(r) {
309 self.on_saved(r, success);
315 do_save_edit: function() {
317 //this.switch_readonly(); Use promises
319 switch_readonly: function() {
321 switch_editable: function() {
323 on_invalid: function() {
325 _.each(this.fields, function(f) {
327 msg += "<li>" + f.string + "</li>";
331 this.notification.warn("The following fields are invalid :", msg);
333 on_saved: function(r, success) {
335 this.notification.warn("Record not saved", "Problem while saving record.");
337 this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
345 * Updates the form' dataset to contain the new record:
347 * * Adds the newly created record to the current dataset (at the end by
349 * * Selects that record (sets the dataset's index to point to the new
351 * * Updates the pager and sidebar displays
354 * @param {Function} success callback to execute after having updated the dataset
355 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
357 on_created: function(r, success, prepend_on_create) {
359 this.notification.warn("Record not created", "Problem while creating record.");
361 this.datarecord.id = r.result;
362 if (!prepend_on_create) {
363 this.dataset.ids.push(this.datarecord.id);
364 this.dataset.index = this.dataset.ids.length - 1;
366 this.dataset.ids.unshift(this.datarecord.id);
367 this.dataset.index = 0;
369 this.do_update_pager();
370 this.do_update_sidebar();
371 this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
373 success(_.extend(r, {created: true}));
378 do_search: function (domains, contexts, groupbys) {
379 this.notification.notify("Searching form");
381 on_action: function (action) {
382 this.notification.notify('Executing action ' + action);
384 do_cancel: function () {
385 this.notification.notify("Cancelling form");
387 do_update_sidebar: function() {
388 if (this.flags.sidebar === false) {
391 if (!this.datarecord.id) {
392 this.on_attachments_loaded([]);
394 // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
395 /*(new openerp.base.DataSetSearch(
396 this.session, 'ir.attachment', this.dataset.get_context(),
397 [['res_model', '=', this.dataset.model],
398 ['res_id', '=', this.datarecord.id],
399 ['type', 'in', ['binary', 'url']]])).read_slice(
400 ['name', 'url', 'type'], false, false,
401 this.on_attachments_loaded);*/
404 on_attachments_loaded: function(attachments) {
405 this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
406 this.attachments = attachments;
407 this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
408 this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
409 this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
411 on_attachment_changed: function(e) {
412 window[this.element_id + '_iframe'] = this.do_update_sidebar;
413 var $e = $(e.target);
414 if ($e.val() != '') {
415 this.$sidebar.find('form.oe-binary-form').submit();
416 $e.parent().find('input[type=file]').attr('disabled', 'true');
417 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
420 on_attachment_delete: function(e) {
421 var self = this, $e = $(e.currentTarget);
422 var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
423 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
424 this.rpc('/base/dataset/unlink', {
425 model: 'ir.attachment',
426 ids: [parseInt($e.attr('data-id'))]
428 $e.parent().remove();
429 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
434 if (this.datarecord.id) {
435 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
437 this.on_button_new();
440 get_fields_values: function() {
442 _.each(this.fields, function(value, key) {
443 var val = value.get_value();
451 openerp.base.form = {};
453 openerp.base.form.compute_domain = function(expr, fields) {
455 for (var i = expr.length - 1; i >= 0; i--) {
457 if (ex.length == 1) {
458 var top = stack.pop();
461 stack.push(stack.pop() || top);
464 stack.push(stack.pop() && top);
470 throw new Error('Unknown domain operator ' + ex);
474 var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
478 switch (op.toLowerCase()) {
481 stack.push(field == val);
485 stack.push(field != val);
488 stack.push(field < val);
491 stack.push(field > val);
494 stack.push(field <= val);
497 stack.push(field >= val);
500 stack.push(_(val).contains(field));
503 stack.push(!_(val).contains(field));
506 this.log("Unsupported operator in modifiers :", op);
512 openerp.base.form.Widget = openerp.base.Controller.extend({
514 init: function(view, node) {
517 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
518 this.type = this.type || node.tag;
519 this.element_name = this.element_name || this.type;
520 this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
522 this._super(this.view.session, this.element_id);
524 this.view.widgets[this.element_id] = this;
525 this.children = node.children;
526 this.colspan = parseInt(node.attrs.colspan || 1);
528 this.string = this.string || node.attrs.string;
529 this.help = this.help || node.attrs.help;
530 this.invisible = this.modifiers['invisible'] === true;
533 this.$element = $('#' + this.element_id);
535 process_modifiers: function() {
536 var compute_domain = openerp.base.form.compute_domain;
537 for (var a in this.modifiers) {
538 this[a] = compute_domain(this.modifiers[a], this.view.fields);
541 update_dom: function() {
542 this.$element.toggle(!this.invisible);
545 var template = this.template;
546 return QWeb.render(template, { "widget": this });
550 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
551 template: 'WidgetFrame',
552 init: function(view, node) {
553 this._super(view, node);
554 this.columns = node.attrs.col || 4;
559 for (var i = 0; i < node.children.length; i++) {
560 var n = node.children[i];
561 if (n.tag == "newline") {
567 this.set_row_cells_with(this.table[this.table.length - 1]);
570 if (this.table.length) {
571 this.set_row_cells_with(this.table[this.table.length - 1]);
574 this.table.push(row);
579 set_row_cells_with: function(row) {
580 for (var i = 0; i < row.length; i++) {
582 if (w.is_field_label) {
585 row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
587 } else if (w.width === undefined) {
588 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
592 handle_node: function(node) {
593 var type = this.view.fields_view.fields[node.attrs.name] || {};
594 var widget = new (this.view.registry.get_any(
595 [node.attrs.widget, type.type, node.tag])) (this.view, node);
596 if (node.tag == 'field') {
597 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
598 this.view.default_focus_field = widget;
600 if (node.attrs.nolabel != '1') {
601 var label = new (this.view.registry.get_object('label')) (this.view, node);
602 label["for"] = widget;
603 this.add_widget(label);
606 this.add_widget(widget);
608 add_widget: function(widget) {
609 var current_row = this.table[this.table.length - 1];
610 if (current_row.length && (this.x + widget.colspan) > this.columns) {
611 current_row = this.add_row();
613 current_row.push(widget);
614 this.x += widget.colspan;
619 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
620 init: function(view, node) {
621 this._super(view, node);
622 this.template = "WidgetNotebook";
624 for (var i = 0; i < node.children.length; i++) {
625 var n = node.children[i];
626 if (n.tag == "page") {
627 var page = new openerp.base.form.WidgetFrame(this.view, n);
628 this.pages.push(page);
633 this._super.apply(this, arguments);
634 this.$element.tabs();
638 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
639 init: function(view, node) {
640 this._super(view, node);
641 this.template = "WidgetSeparator";
645 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
646 init: function(view, node) {
647 this._super(view, node);
648 this.template = "WidgetButton";
649 if (node.attrs.default_focus == '1') {
650 // TODO fme: provide enter key binding to widgets
651 this.view.default_focus_button = this;
655 this._super.apply(this, arguments);
656 this.$element.click(this.on_click);
658 on_click: function(saved) {
660 if (!this.node.attrs.special && this.view.touched && saved !== true) {
661 this.view.do_save(function() {
665 if (this.node.attrs.confirm) {
666 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
672 $(this).dialog("close");
675 $(this).dialog("close");
684 on_confirmed: function() {
687 this.view.execute_action(
688 this.node.attrs, this.view.dataset, this.session.action_manager,
689 this.view.datarecord.id, function (result) {
690 self.log("Button returned", result);
698 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
699 init: function(view, node) {
700 this.element_name = 'label_' + node.attrs.name;
702 this._super(view, node);
704 // TODO fme: support for attrs.align
705 if (this.node.tag == 'label' && this.node.attrs.colspan) {
706 this.is_field_label = false;
707 this.template = "WidgetParagraph";
709 this.is_field_label = true;
710 this.template = "WidgetLabel";
714 render: function () {
715 if (this['for'] && this.type !== 'label') {
716 return QWeb.render(this.template, {widget: this['for']});
718 // Actual label widgets should not have a false and have type label
719 return QWeb.render(this.template, {widget: this});
723 openerp.base.form.Field = openerp.base.form.Widget.extend({
724 init: function(view, node) {
725 this.name = node.attrs.name;
726 this.value = undefined;
727 view.fields[this.name] = this;
728 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
729 this.element_name = "field_" + this.name + "_" + this.type;
731 this._super(view, node);
733 if (node.attrs.nolabel != '1' && this.colspan > 1) {
736 this.field = view.fields_view.fields[node.attrs.name] || {};
737 this.string = node.attrs.string || this.field.string;
738 this.help = node.attrs.help || this.field.help;
739 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
740 this.readonly = this.modifiers['readonly'] === true;
741 this.required = this.modifiers['required'] === true;
742 this.invalid = false;
743 this.touched = false;
745 set_value: function(value) {
747 this.invalid = false;
750 set_value_from_ui: function() {
751 this.value = undefined;
753 get_value: function() {
756 get_on_change_value: function() {
757 return this.get_value();
759 update_dom: function() {
760 this._super.apply(this, arguments);
761 this.$element.toggleClass('disabled', this.readonly);
762 this.$element.toggleClass('required', this.required);
763 if (this.view.show_invalid) {
764 this.$element.toggleClass('invalid', this.invalid);
767 on_ui_change: function() {
768 this.touched = this.view.touched = true;
771 this.set_value_from_ui();
772 this.view.do_onchange(this);
773 this.view.on_form_changed();
778 validate: function() {
779 this.invalid = false;
783 _build_view_fields_values: function() {
784 var a_dataset = this.view.dataset || {};
785 var fields_values = this.view.get_fields_values();
786 var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
787 fields_values.parent = parent_values;
788 return fields_values;
791 * Builds a new context usable for operations related to fields by merging
792 * the fields'context with the action's context.
794 build_context: function() {
795 var a_context = this.view.dataset.get_context() || {};
796 var f_context = this.field.context || {};
797 var v_context1 = this.node.attrs.default_get || {};
798 var v_context2 = this.node.attrs.context || {};
799 var v_context = new openerp.base.CompoundContext(v_context1, v_context2);
800 if (v_context1.__ref || v_context2.__ref || true) { //TODO niv: remove || true
801 var fields_values = this._build_view_fields_values();
802 v_context.set_eval_context(fields_values);
804 var ctx = new openerp.base.CompoundContext(a_context, f_context, v_context);
807 build_domain: function() {
808 var f_domain = this.field.domain || [];
809 var v_domain = this.node.attrs.domain || [];
810 if (!(v_domain instanceof Array) || true) { //TODO niv: remove || true
811 var fields_values = this._build_view_fields_values();
812 v_domain = new openerp.base.CompoundDomain(v_domain).set_eval_context(fields_values);
814 return new openerp.base.CompoundDomain(f_domain, v_domain);
818 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
819 init: function(view, node) {
820 this._super(view, node);
821 this.template = "FieldChar";
824 this._super.apply(this, arguments);
825 this.$element.find('input').change(this.on_ui_change);
827 set_value: function(value) {
828 this._super.apply(this, arguments);
829 var show_value = (value != null && value !== false) ? value : '';
830 this.$element.find('input').val(show_value);
832 update_dom: function() {
833 this._super.apply(this, arguments);
834 this.$element.find('input').attr('disabled', this.readonly);
836 set_value_from_ui: function() {
837 this.value = this.$element.find('input').val();
839 validate: function() {
840 this.invalid = false;
841 var value = this.$element.find('input').val();
843 this.invalid = this.required;
844 } else if (this.validation_regex) {
845 this.invalid = !this.validation_regex.test(value);
849 this.$element.find('input').focus();
853 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
854 init: function(view, node) {
855 this._super(view, node);
856 this.template = "FieldEmail";
857 this.validation_regex = /@/;
860 this._super.apply(this, arguments);
861 this.$element.find('button').click(this.on_button_clicked);
863 on_button_clicked: function() {
864 if (!this.value || this.invalid) {
865 this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
867 location.href = 'mailto:' + this.value;
870 set_value: function(value) {
871 this._super.apply(this, arguments);
872 var show_value = (value != null && value !== false) ? value : '';
873 this.$element.find('a').attr('href', 'mailto:' + show_value);
877 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
878 init: function(view, node) {
879 this._super(view, node);
880 this.template = "FieldUrl";
883 this._super.apply(this, arguments);
884 this.$element.find('button').click(this.on_button_clicked);
886 on_button_clicked: function() {
888 this.notification.warn("Resource error", "This resource is empty");
890 window.open(this.value);
895 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
896 init: function(view, node) {
897 this._super(view, node);
898 this.validation_regex = /^-?\d+(\.\d+)?$/;
900 set_value: function(value) {
901 this._super.apply(this, [value]);
902 if (value === false || value === undefined) {
903 // As in GTK client, floats default to 0
906 var show_value = value.toFixed(2);
907 this.$element.find('input').val(show_value);
909 set_value_from_ui: function() {
910 this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
914 openerp.base.form.FieldInteger = openerp.base.form.FieldFloat.extend({
915 init: function(view, node) {
916 this._super(view, node);
917 this.validation_regex = /^-?\d+$/;
919 set_value: function(value) {
920 this._super.apply(this, [value]);
921 if (value === false || value === undefined) {
922 // TODO fme: check if GTK client default integers to 0 (like it does with floats)
925 var show_value = parseInt(value, 10);
926 this.$element.find('input').val(show_value);
928 set_value_from_ui: function() {
929 this.value = Number(this.$element.find('input').val());
933 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
934 init: function(view, node) {
935 this._super(view, node);
936 this.template = "FieldDate";
937 this.jqueryui_object = 'datetimepicker';
938 this.validation_regex = /^\d+-\d+-\d+( \d+:\d+(:\d+)?)?$/;
941 this._super.apply(this, arguments);
942 this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
943 dateFormat: 'yy-mm-dd',
944 timeFormat: 'hh:mm:ss',
946 buttonImage: '/base/static/src/img/ui/field_calendar.png',
947 buttonImageOnly: true,
948 constrainInput: false
951 set_value: function(value) {
952 this._super.apply(this, arguments);
954 this.$element.find('input').val('');
956 this.$element.find('input').unbind('change');
957 // jQuery UI date picker wrongly call on_change event herebelow
958 this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
959 this.$element.find('input').change(this.on_ui_change);
962 set_value_from_ui: function() {
963 this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
965 this.value = this.format(this.value);
968 update_dom: function() {
969 this._super.apply(this, arguments);
970 this.$element.find('input').attr('disabled', this.readonly);
972 validate: function() {
973 this.invalid = false;
974 var value = this.$element.find('input').val();
976 this.invalid = this.required;
977 } else if (this.validation_regex) {
978 this.invalid = !this.validation_regex.test(value);
980 this.invalid = !this.$element.find('input')[this.jqueryui_object]('getDate');
984 this.$element.find('input').focus();
986 parse: openerp.base.parse_datetime,
987 format: openerp.base.format_datetime
990 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
991 init: function(view, node) {
992 this._super(view, node);
993 this.jqueryui_object = 'datepicker';
994 this.validation_regex = /^\d+-\d+-\d+$/;
996 parse: openerp.base.parse_date,
997 format: openerp.base.format_date
1000 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
1001 init: function(view, node) {
1002 this._super(view, node);
1003 this.validation_regex = /^\d+:\d+$/;
1005 set_value: function(value) {
1006 this._super.apply(this, [value]);
1007 if (value === false || value === undefined) {
1008 // As in GTK client, floats default to 0
1011 var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
1012 this.$element.find('input').val(show_value);
1014 set_value_from_ui: function() {
1015 var time = this.$element.find('input').val().split(':');
1016 this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
1020 openerp.base.form.FieldText = openerp.base.form.Field.extend({
1021 init: function(view, node) {
1022 this._super(view, node);
1023 this.template = "FieldText";
1024 this.validation_regex = null;
1027 this._super.apply(this, arguments);
1028 this.$element.find('textarea').change(this.on_ui_change);
1030 set_value: function(value) {
1031 this._super.apply(this, arguments);
1032 var show_value = (value != null && value !== false) ? value : '';
1033 this.$element.find('textarea').val(show_value);
1035 update_dom: function() {
1036 this._super.apply(this, arguments);
1037 this.$element.find('textarea').attr('disabled', this.readonly);
1039 set_value_from_ui: function() {
1040 this.value = this.$element.find('textarea').val();
1042 validate: function() {
1043 this.invalid = false;
1044 var value = this.$element.find('textarea').val();
1046 this.invalid = this.required;
1047 } else if (this.validation_regex) {
1048 this.invalid = !this.validation_regex.test(value);
1052 this.$element.find('textarea').focus();
1056 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
1057 init: function(view, node) {
1058 this._super(view, node);
1059 this.template = "FieldBoolean";
1063 this._super.apply(this, arguments);
1064 this.$element.find('input').click(function() {
1065 if ($(this).is(':checked') != self.value) {
1066 self.on_ui_change();
1070 set_value: function(value) {
1071 this._super.apply(this, arguments);
1072 this.$element.find('input')[0].checked = value;
1074 set_value_from_ui: function() {
1075 this.value = this.$element.find('input').is(':checked');
1077 update_dom: function() {
1078 this._super.apply(this, arguments);
1079 this.$element.find('input').attr('disabled', this.readonly);
1081 validate: function() {
1082 this.invalid = this.required && !this.$element.find('input').is(':checked');
1085 this.$element.find('input').focus();
1089 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1090 init: function(view, node) {
1091 this._super(view, node);
1092 this.template = "FieldProgressBar";
1095 this._super.apply(this, arguments);
1096 this.$element.find('div').progressbar({
1098 disabled: this.readonly
1101 set_value: function(value) {
1102 this._super.apply(this, arguments);
1103 var show_value = Number(value);
1104 if (isNaN(show_value)) {
1107 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1111 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1112 // to replace view editor
1115 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1116 init: function(view, node) {
1117 this._super(view, node);
1118 this.template = "FieldSelection";
1119 this.field_index = [];
1122 _.each(this.field.selection, function(x) {
1123 self.field_index.push({"ikey": "" + i, "ekey": x[0], "label": x[1]});
1128 this._super.apply(this, arguments);
1129 this.$element.find('select').change(this.on_ui_change);
1131 set_value: function(value) {
1132 value = value === null ? false : value;
1133 value = value instanceof Array ? value[0] : value;
1135 var option = _.detect(this.field_index, function(x) {return x.ekey === value;});
1136 this.$element.find('select').val(option.ikey);
1138 set_value_from_ui: function() {
1139 var ikey = this.$element.find('select').val();
1140 var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1141 this.value = option.ekey;
1143 update_dom: function() {
1144 this._super.apply(this, arguments);
1145 this.$element.find('select').attr('disabled', this.readonly);
1147 validate: function() {
1148 var ikey = this.$element.find('select').val();
1149 var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1150 this.invalid = this.required && option.ekey === false;
1153 this.$element.find('select').focus();
1157 // jquery autocomplete tweak to allow html
1159 var proto = $.ui.autocomplete.prototype,
1160 initSource = proto._initSource;
1162 function filter( array, term ) {
1163 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1164 return $.grep( array, function(value) {
1165 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1170 _initSource: function() {
1171 if ( this.options.html && $.isArray(this.options.source) ) {
1172 this.source = function( request, response ) {
1173 response( filter( this.options.source, request.term ) );
1176 initSource.call( this );
1180 _renderItem: function( ul, item) {
1181 return $( "<li></li>" )
1182 .data( "item.autocomplete", item )
1183 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1189 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1190 init: function(view, node) {
1191 this._super(view, node);
1192 this.template = "FieldMany2One";
1195 this.cm_id = _.uniqueId('m2o_cm_');
1196 this.last_search = [];
1197 this.tmp_value = undefined;
1202 this.$input = this.$element.find("input");
1203 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1204 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1208 bindings[this.cm_id + "_search"] = function() {
1209 self._search_create_popup("search");
1211 bindings[this.cm_id + "_create"] = function() {
1212 self._search_create_popup("form");
1214 bindings[this.cm_id + "_open"] = function() {
1218 self.session.action_manager.do_action({
1219 "res_model": self.field.relation,
1220 "views":[[false,"form"]],
1221 "res_id": self.value[0],
1222 "type":"ir.actions.act_window",
1224 "context": self.build_context()
1227 var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1228 bindings: bindings, itemStyle: {"color": ""},
1229 onContextMenu: function() {
1231 $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1233 $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1239 // some behavior for input
1240 this.$input.keyup(function() {
1241 if (self.$input.val() === "") {
1242 self._change_int_value(null);
1243 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1244 self._change_int_value(undefined);
1247 this.$drop_down.click(function() {
1248 if (self.$input.autocomplete("widget").is(":visible")) {
1249 self.$input.autocomplete("close");
1252 self.$input.autocomplete("search", "");
1254 self.$input.autocomplete("search");
1256 self.$input.focus();
1259 var anyoneLoosesFocus = function() {
1260 if (!self.$input.is(":focus") &&
1261 !self.$input.autocomplete("widget").is(":visible") &&
1263 if(self.value === undefined && self.last_search.length > 0) {
1264 self._change_int_ext_value(self.last_search[0]);
1266 self._change_int_ext_value(null);
1270 this.$input.focusout(anyoneLoosesFocus);
1273 this.$input.autocomplete({
1274 source: function(req, resp) { self.get_search_result(req, resp); },
1275 select: function(event, ui) {
1278 self._change_int_value([item.id, item.name]);
1279 } else if (item.action) {
1280 self._change_int_value(undefined);
1285 focus: function(e, ui) {
1289 close: anyoneLoosesFocus,
1294 // autocomplete component content handling
1295 get_search_result: function(request, response) {
1296 var search_val = request.term;
1299 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1301 dataset.name_search(search_val, self.build_domain(), 'ilike',
1302 this.limit + 1, function(data) {
1303 self.last_search = data.result;
1304 // possible selections for the m2o
1305 var values = _.map(data.result, function(x) {
1306 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1309 // search more... if more results that max
1310 if (values.length > self.limit) {
1311 values = values.slice(0, self.limit);
1312 values.push({label: "<em>Â Â Â Search More...</em>", action: function() {
1313 dataset.name_search(search_val, self.build_domain(), 'ilike'
1314 , false, function(data) {
1315 self._change_int_value(null);
1316 self._search_create_popup("search", data.result);
1321 var raw_result = _(data.result).map(function(x) {return x[1];})
1322 if (search_val.length > 0 &&
1323 !_.include(raw_result, search_val) &&
1324 (!self.value || search_val !== self.value[1])) {
1325 values.push({label: '<em>Â Â Â Create "<strong>' +
1326 $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1327 self._quick_create(search_val);
1331 values.push({label: "<em>Â Â Â Create and Edit...</em>", action: function() {
1332 self._change_int_value(null);
1333 self._search_create_popup("form", undefined, {"default_name": search_val});
1339 _quick_create: function(name) {
1341 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1342 dataset.name_create(name, function(data) {
1343 self._change_int_ext_value(data.result);
1344 }).fail(function(error, event) {
1345 event.preventDefault();
1346 self._change_int_value(null);
1347 self._search_create_popup("form", undefined, {"default_name": name});
1350 // all search/create popup handling
1351 _search_create_popup: function(view, ids, context) {
1353 var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1354 pop.select_element(self.field.relation,{
1355 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1357 disable_multiple_selection: true
1358 }, self.build_domain(),
1359 new openerp.base.CompoundContext(self.build_context(), context || {}));
1360 pop.on_select_elements.add(function(element_ids) {
1361 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1362 dataset.name_get([element_ids[0]], function(data) {
1363 self._change_int_ext_value(data.result[0]);
1368 _change_int_ext_value: function(value) {
1369 this._change_int_value(value);
1370 this.$input.val(this.value ? this.value[1] : "");
1372 _change_int_value: function(value) {
1374 var back_orig_value = this.original_value;
1375 if (this.value === null || this.value) {
1376 this.original_value = this.value;
1378 if (back_orig_value === undefined) { // first use after a set_value()
1381 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1382 !== (this.value ? this.value[0] : null))) {
1383 this.on_ui_change();
1386 set_value_from_ui: function() {},
1387 set_value: function(value) {
1388 value = value || null;
1390 var _super = this._super;
1391 this.tmp_value = value;
1392 var real_set_value = function(rval) {
1393 self.tmp_value = undefined;
1394 _super.apply(self, rval);
1395 self.original_value = undefined;
1396 self._change_int_ext_value(rval);
1398 if(typeof(value) === "number") {
1399 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1400 dataset.name_get([value], function(data) {
1401 real_set_value(data.result[0]);
1402 }).fail(function() {self.tmp_value = undefined;});
1404 setTimeout(function() {real_set_value(value);}, 0);
1407 get_value: function() {
1408 if (this.tmp_value !== undefined) {
1409 if (this.tmp_value instanceof Array) {
1410 return this.tmp_value[0];
1412 return this.tmp_value ? this.tmp_value : false;
1414 if (this.value === undefined)
1415 return this.original_value ? this.original_value[0] : false;
1416 return this.value ? this.value[0] : false;
1418 validate: function() {
1419 this.invalid = false;
1420 if (this.value === null) {
1421 this.invalid = this.required;
1427 # Values: (0, 0, { fields }) create
1428 # (1, ID, { fields }) update
1429 # (2, ID) remove (delete)
1430 # (3, ID) unlink one (target id or target of relation)
1432 # (5) unlink all (only valid for one2many)
1437 'create': function (values) {
1438 return [commands.CREATE, false, values];
1440 // (1, id, {values})
1442 'update': function (id, values) {
1443 return [commands.UPDATE, id, values];
1447 'delete': function (id) {
1448 return [commands.DELETE, id, false];
1450 // (3, id[, _]) removes relation, but not linked record itself
1452 'forget': function (id) {
1453 return [commands.FORGET, id, false];
1457 'link_to': function (id) {
1458 return [commands.LINK_TO, id, false];
1462 'delete_all': function () {
1463 return [5, false, false];
1465 // (6, _, ids) replaces all linked records with provided ids
1467 'replace_with': function (ids) {
1468 return [6, false, ids];
1471 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1472 multi_selection: false,
1473 init: function(view, node) {
1474 this._super(view, node);
1475 this.template = "FieldOne2Many";
1476 this.is_started = $.Deferred();
1479 this._super.apply(this, arguments);
1483 this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1484 this.dataset.o2m = this;
1485 this.dataset.parent_view = this.view;
1486 this.dataset.on_change.add_last(function() {
1487 self.on_ui_change();
1490 var modes = this.node.attrs.mode;
1491 modes = !!modes ? modes.split(",") : ["tree", "form"];
1493 _.each(modes, function(mode) {
1494 var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1495 if (self.field.views && self.field.views[mode]) {
1496 view.embedded_view = self.field.views[mode];
1498 if(view.view_type === "list") {
1500 'selectable': self.multi_selection
1507 this.viewmanager = new openerp.base.ViewManager(this.view.session,
1508 this.element_id, this.dataset, views);
1509 this.viewmanager.registry = openerp.base.views.clone({
1510 list: 'openerp.base.form.One2ManyListView'
1513 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1514 if (view_type == "list") {
1515 controller.o2m = self;
1516 } else if (view_type == "form") {
1519 self.is_started.resolve();
1521 setTimeout(function () {
1522 self.viewmanager.start();
1525 reload_current_view: function() {
1527 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1528 if(self.viewmanager.active_view === "list") {
1529 view.reload_content();
1530 } else if (self.viewmanager.active_view === "form") {
1531 // TODO niv: implement
1534 set_value_from_ui: function() {},
1535 set_value: function(value) {
1536 value = value || [];
1538 this.dataset.reset_ids([]);
1539 if(value.length >= 1 && value[0] instanceof Array) {
1541 _.each(value, function(command) {
1542 var obj = {values: command[2]};
1543 switch (command[0]) {
1544 case commands.CREATE:
1545 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1546 self.dataset.to_create.push(obj);
1547 self.dataset.cache.push(_.clone(obj));
1550 case commands.UPDATE:
1551 obj['id'] = command[1];
1552 self.dataset.to_write.push(obj);
1553 self.dataset.cache.push(_.clone(obj));
1556 case commands.DELETE:
1557 self.dataset.to_delete.push({id: command[1]});
1559 case commands.LINK_TO:
1560 ids.push(command[1]);
1562 case commands.DELETE_ALL:
1563 self.dataset.delete_all = true;
1568 this.dataset.set_ids(ids);
1569 } else if (value.length >= 1 && typeof(value[0]) === "object") {
1571 this.dataset.delete_all = true;
1572 _.each(value, function(command) {
1573 var obj = {values: command};
1574 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1575 self.dataset.to_create.push(obj);
1576 self.dataset.cache.push(_.clone(obj));
1580 this.dataset.set_ids(ids);
1583 this.dataset.reset_ids(value);
1585 $.when(this.is_started).then(function() {
1586 self.reload_current_view();
1589 get_value: function() {
1593 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1594 val = val.concat(_.map(this.dataset.ids, function(id) {
1595 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1597 return commands.create(alter_order.values);
1599 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1601 return commands.update(alter_order.id, alter_order.values);
1603 return commands.link_to(id);
1605 return val.concat(_.map(
1606 this.dataset.to_delete, function(x) {
1607 return commands['delete'](x.id);}));
1609 validate: function() {
1610 this.invalid = false;
1615 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1616 get_context: function() {
1617 this.context = this.o2m.build_context();
1618 return this.context;
1622 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1623 do_add_record: function () {
1624 if (this.options.editable) {
1625 this._super.apply(this, arguments);
1628 var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1629 pop.select_element(self.o2m.field.relation,{
1630 initial_view: "form",
1631 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1633 parent_view: self.o2m.view
1634 }, self.o2m.build_domain(), self.o2m.build_context());
1635 pop.on_create.add(function(data) {
1636 self.o2m.dataset.create(data, function(r) {
1637 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1638 self.o2m.dataset.on_change();
1640 self.o2m.reload_current_view();
1647 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1648 multi_selection: false,
1649 init: function(view, node) {
1650 this._super(view, node);
1651 this.template = "FieldMany2Many";
1652 this.list_id = _.uniqueId("many2many");
1653 this.is_started = $.Deferred();
1656 this._super.apply(this, arguments);
1660 this.dataset = new openerp.base.form.Many2ManyDataSet(
1661 this.session, this.field.relation);
1662 this.dataset.m2m = this;
1663 this.dataset.on_unlink.add_last(function(ids) {
1664 self.on_ui_change();
1667 this.list_view = new openerp.base.form.Many2ManyListView(
1668 null, this.view.session, this.list_id, this.dataset, false, {
1670 'selectable': self.multi_selection
1672 this.list_view.m2m_field = this;
1673 this.list_view.on_loaded.add_last(function() {
1674 self.is_started.resolve();
1676 setTimeout(function () {
1677 self.list_view.start();
1680 set_value: function(value) {
1681 value = value || [];
1682 if (value.length >= 1 && value[0] instanceof Array) {
1683 value = value[0][2];
1686 this.dataset.set_ids(value);
1688 $.when(this.is_started).then(function() {
1689 self.list_view.reload_content();
1692 get_value: function() {
1693 return [commands.replace_with(this.dataset.ids)];
1695 set_value_from_ui: function() {},
1696 validate: function() {
1697 this.invalid = false;
1702 openerp.base.form.Many2ManyDataSet = openerp.base.DataSetStatic.extend({
1703 get_context: function() {
1704 this.context = this.m2m.build_context();
1705 return this.context;
1709 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1710 do_add_record: function () {
1711 var pop = new openerp.base.form.SelectCreatePopup(
1712 null, this.m2m_field.view.session);
1713 pop.select_element(this.model, {},
1714 new openerp.base.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
1715 this.m2m_field.build_context());
1717 pop.on_select_elements.add(function(element_ids) {
1718 _.each(element_ids, function(element_id) {
1719 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1720 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1721 self.m2m_field.on_ui_change();
1722 self.reload_content();
1728 do_activate_record: function(index, id) {
1729 this.m2m_field.view.session.action_manager.do_action({
1730 "res_model": this.dataset.model,
1731 "views": [[false,"form"]],
1733 "type": "ir.actions.act_window",
1734 "view_type": "form",
1735 "view_mode": "form",
1737 "context": this.m2m_field.build_context()
1742 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1743 identifier_prefix: "selectcreatepopup",
1744 template: "SelectCreatePopup",
1748 * - initial_view: form or search (default search)
1749 * - disable_multiple_selection
1750 * - alternative_form_view
1751 * - auto_create (default true)
1754 select_element: function(model, options, domain, context) {
1756 this.domain = domain || [];
1757 this.context = context || {};
1758 this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1759 this.initial_ids = this.options.initial_ids;
1760 jQuery(this.render()).dialog({title: '',
1767 this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1769 this.dataset.parent_view = this.options.parent_view;
1770 if (this.options.initial_view == "search") {
1771 this.setup_search_view();
1776 setup_search_view: function() {
1778 if (this.searchview) {
1779 this.searchview.stop();
1781 this.searchview = new openerp.base.SearchView(null, this.session,
1782 this.element_id + "_search", this.dataset, false, {
1783 "selectable": !this.options.disable_multiple_selection,
1786 this.searchview.on_search.add(function(domains, contexts, groupbys) {
1787 if (self.initial_ids) {
1788 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]], self.domain]),
1789 contexts, groupbys);
1790 self.initial_ids = undefined;
1792 self.view_list.do_search.call(self, domains.concat([self.domain]), contexts, groupbys);
1795 this.searchview.on_loaded.add_last(function () {
1796 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1797 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1798 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1799 $cbutton.click(function() {
1802 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1803 if(self.options.disable_multiple_selection) {
1806 $sbutton.click(function() {
1807 self.on_select_elements(self.selected_ids);
1809 self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1810 self.element_id + "_view_list", self.dataset, false,
1811 {'deletable': false});
1812 self.view_list.popup = self;
1813 self.view_list.do_show();
1814 self.view_list.start().then(function() {
1815 self.searchview.do_search();
1818 this.searchview.start();
1820 on_create: function(data) {
1821 if (!this.options.auto_create)
1824 var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1825 wdataset = this.options.parent_view;
1826 wdataset.create(data, function(r) {
1827 self.on_select_elements([r.result]);
1830 on_select_elements: function(element_ids) {
1832 on_click_element: function(ids) {
1833 this.selected_ids = ids || [];
1834 if(this.selected_ids.length > 0) {
1835 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1837 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1840 new_object: function() {
1842 if (this.searchview) {
1843 this.searchview.hide();
1845 if (this.view_list) {
1846 this.view_list.$element.hide();
1848 this.dataset.index = null;
1849 this.view_form = new openerp.base.FormView(null, this.session,
1850 this.element_id + "_view_form", this.dataset, false);
1851 if (this.options.alternative_form_view) {
1852 this.view_form.set_embedded_view(this.options.alternative_form_view);
1854 this.view_form.start();
1855 this.view_form.on_loaded.add_last(function() {
1856 var $buttons = self.view_form.$element.find(".oe_form_buttons");
1857 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1858 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1859 $nbutton.click(function() {
1860 self.view_form.do_save();
1862 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1863 $cbutton.click(function() {
1867 this.dataset.on_create.add(this.on_create);
1868 this.view_form.do_show();
1872 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1873 do_add_record: function () {
1874 this.popup.new_object();
1876 select_record: function(index) {
1877 this.popup.on_select_elements([this.dataset.ids[index]]);
1879 do_select: function(ids, records) {
1880 this._super(ids, records);
1881 this.popup.on_click_element(ids);
1885 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1886 init: function(view, node) {
1887 this._super(view, node);
1888 this.template = "FieldReference";
1892 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1893 init: function(view, node) {
1894 this._super(view, node);
1895 this.iframe = this.element_id + '_iframe';
1896 this.binary_value = false;
1899 this._super.apply(this, arguments);
1900 this.$element.find('input.oe-binary-file').change(this.on_file_change);
1901 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1902 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1904 set_value_from_ui: function() {
1906 human_filesize : function(size) {
1907 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1909 while (size >= 1024) {
1913 return size.toFixed(2) + ' ' + units[i];
1915 on_file_change: function(e) {
1916 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1917 // http://www.html5rocks.com/tutorials/file/dndfiles/
1918 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1919 window[this.iframe] = this.on_file_uploaded;
1920 if ($(e.target).val() != '') {
1921 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1922 this.$element.find('form.oe-binary-form').submit();
1923 this.toggle_progress();
1926 toggle_progress: function() {
1927 this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1929 on_file_uploaded: function(size, name, content_type, file_base64) {
1930 delete(window[this.iframe]);
1931 if (size === false) {
1932 this.notification.warn("File Upload", "There was a problem while uploading your file");
1933 // TODO: use openerp web exception handler
1934 console.log("Error while uploading file : ", name);
1936 this.on_file_uploaded_and_valid.apply(this, arguments);
1937 this.on_ui_change();
1939 this.toggle_progress();
1941 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1943 on_save_as: function() {
1944 if (!this.view.datarecord.id) {
1945 this.notification.warn("Can't save file", "The record has not yet been saved");
1947 var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1948 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1949 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1953 on_clear: function() {
1954 if (this.value !== false) {
1956 this.binary_value = false;
1957 this.on_ui_change();
1963 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1964 init: function(view, node) {
1965 this._super(view, node);
1966 this.template = "FieldBinaryFile";
1968 set_value: function(value) {
1969 this._super.apply(this, arguments);
1970 var show_value = (value != null && value !== false) ? value : '';
1971 this.$element.find('input').eq(0).val(show_value);
1973 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1974 this.value = file_base64;
1975 this.binary_value = true;
1976 var show_value = this.human_filesize(size);
1977 this.$element.find('input').eq(0).val(show_value);
1978 this.set_filename(name);
1980 set_filename: function(value) {
1981 var filename = this.node.attrs.filename;
1982 if (this.view.fields[filename]) {
1983 this.view.fields[filename].set_value(value);
1984 this.view.fields[filename].on_ui_change();
1987 on_clear: function() {
1988 this._super.apply(this, arguments);
1989 this.$element.find('input').eq(0).val('');
1990 this.set_filename('');
1994 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1995 init: function(view, node) {
1996 this._super(view, node);
1997 this.template = "FieldBinaryImage";
2000 this._super.apply(this, arguments);
2001 this.$image = this.$element.find('img.oe-binary-image');
2003 set_image_maxwidth: function() {
2004 this.$image.css('max-width', this.$element.width());
2006 on_file_change: function() {
2007 this.set_image_maxwidth();
2008 this._super.apply(this, arguments);
2010 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2011 this.value = file_base64;
2012 this.binary_value = true;
2013 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2015 on_clear: function() {
2016 this._super.apply(this, arguments);
2017 this.$image.attr('src', '/base/static/src/img/placeholder.png');
2019 set_value: function(value) {
2020 this._super.apply(this, arguments);
2021 this.set_image_maxwidth();
2022 var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
2023 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
2024 this.$image.attr('src', url);
2029 * Registry of form widgets, called by :js:`openerp.base.FormView`
2031 openerp.base.form.widgets = new openerp.base.Registry({
2032 'frame' : 'openerp.base.form.WidgetFrame',
2033 'group' : 'openerp.base.form.WidgetFrame',
2034 'notebook' : 'openerp.base.form.WidgetNotebook',
2035 'separator' : 'openerp.base.form.WidgetSeparator',
2036 'label' : 'openerp.base.form.WidgetLabel',
2037 'button' : 'openerp.base.form.WidgetButton',
2038 'char' : 'openerp.base.form.FieldChar',
2039 'email' : 'openerp.base.form.FieldEmail',
2040 'url' : 'openerp.base.form.FieldUrl',
2041 'text' : 'openerp.base.form.FieldText',
2042 'text_wiki' : 'openerp.base.form.FieldText',
2043 'date' : 'openerp.base.form.FieldDate',
2044 'datetime' : 'openerp.base.form.FieldDatetime',
2045 'selection' : 'openerp.base.form.FieldSelection',
2046 'many2one' : 'openerp.base.form.FieldMany2One',
2047 'many2many' : 'openerp.base.form.FieldMany2Many',
2048 'one2many' : 'openerp.base.form.FieldOne2Many',
2049 'one2many_list' : 'openerp.base.form.FieldOne2Many',
2050 'reference' : 'openerp.base.form.FieldReference',
2051 'boolean' : 'openerp.base.form.FieldBoolean',
2052 'float' : 'openerp.base.form.FieldFloat',
2053 'integer': 'openerp.base.form.FieldInteger',
2054 'progressbar': 'openerp.base.form.FieldProgressBar',
2055 'float_time': 'openerp.base.form.FieldFloatTime',
2056 'image': 'openerp.base.form.FieldBinaryImage',
2057 'binary': 'openerp.base.form.FieldBinaryFile'
2062 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: