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);
55 _.each(this.widgets, function(w) {
59 on_loaded: function(data) {
61 this.fields_view = data.fields_view;
62 var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
64 this.$element.html(QWeb.render(this.template, { 'frame': frame, 'view': this }));
65 _.each(this.widgets, function(w) {
68 this.$form_header = this.$element.find('#' + this.element_id + '_header');
69 this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
70 var action = $(this).data('pager-action');
71 self.on_pager_action(action);
74 this.$form_header.find('button.oe_form_button_save').click(this.do_save);
75 this.$form_header.find('button.oe_form_button_save_edit').click(this.do_save_edit);
76 this.$form_header.find('button.oe_form_button_cancel').click(this.do_cancel);
77 this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
79 this.view_manager.sidebar.set_toolbar(data.fields_view.toolbar);
80 this.has_been_loaded.resolve();
82 do_show: function () {
84 if (this.dataset.index === null) {
85 // null index means we should start a new record
88 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
91 this.view_manager.sidebar.do_refresh(true);
93 do_hide: function () {
96 on_record_loaded: function(record) {
98 throw("Form: No record received");
101 this.$form_header.find('.oe_form_on_create').show();
102 this.$form_header.find('.oe_form_on_update').hide();
103 this.$form_header.find('button.oe_form_button_new').hide();
105 this.$form_header.find('.oe_form_on_create').hide();
106 this.$form_header.find('.oe_form_on_update').show();
107 this.$form_header.find('button.oe_form_button_new').show();
109 this.touched = false;
110 this.datarecord = record;
111 for (var f in this.fields) {
112 var field = this.fields[f];
113 field.touched = false;
114 field.set_value(this.datarecord[f] || false);
118 // New record: Second pass in order to trigger the onchanges
120 this.show_invalid = false;
121 for (var f in record) {
122 var field = this.fields[f];
124 field.touched = true;
125 this.do_onchange(field);
129 this.on_form_changed();
130 this.show_invalid = this.ready = true;
131 this.do_update_pager(record.id == null);
132 this.do_update_sidebar();
133 if (this.default_focus_field) {
134 this.default_focus_field.focus();
137 on_form_changed: function() {
138 for (var w in this.widgets) {
140 w.process_modifiers();
144 on_pager_action: function(action) {
147 this.dataset.index = 0;
150 this.dataset.previous();
156 this.dataset.index = this.dataset.ids.length - 1;
161 do_update_pager: function(hide_index) {
162 var $pager = this.$element.find('#' + this.element_id + '_header div.oe_form_pager');
163 var index = hide_index ? '-' : this.dataset.index + 1;
164 $pager.find('span.oe_pager_index').html(index);
165 $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
167 do_onchange: function(widget, processed) {
168 processed = processed || [];
169 if (widget.node.attrs.on_change) {
172 var onchange = _.trim(widget.node.attrs.on_change);
173 var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
175 var method = call[1], args = [];
176 var context_index = null;
177 var argument_replacement = {
178 'False' : function() {return false;},
179 'True' : function() {return true;},
180 'None' : function() {return null;},
181 'context': function(i) {
183 var ctx = widget.build_context ? widget.build_context() : {};
187 var parent_fields = null;
188 _.each(call[2].split(','), function(a, i) {
189 var field = _.trim(a);
190 if (field in argument_replacement) {
191 args.push(argument_replacement[field](i));
193 } else if (self.fields[field]) {
194 var value = self.fields[field].get_on_change_value();
195 args.push(value == null ? false : value);
198 var splitted = field.split('.');
199 if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
200 if (parent_fields === null) {
201 parent_fields = self.dataset.parent_view.get_fields_values();
203 var p_val = parent_fields[_.trim(splitted[1])];
204 if (p_val !== undefined) {
205 args.push(p_val == null ? false : p_val);
210 throw "Could not get field with name '" + field +
211 "' for onchange '" + onchange + "'";
214 url: '/base/dataset/call',
217 return this.rpc(ajax, {
218 model: this.dataset.model,
220 args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args),
221 context_id: context_index === null ? null : context_index + 1
222 }, function(response) {
223 self.on_processed_onchange(response, processed);
226 this.log("Wrong on_change format", on_change);
230 on_processed_onchange: function(response, processed) {
231 var result = response.result;
233 for (var f in result.value) {
234 var field = this.fields[f];
236 var value = result.value[f];
237 processed.push(field.name);
238 if (field.get_value() != value) {
239 field.set_value(value);
240 field.touched = true;
241 if (_.indexOf(processed, field.name) < 0) {
242 this.do_onchange(field, processed);
246 // this is a common case, the normal behavior should be to ignore it
249 this.on_form_changed();
251 if (!_.isEmpty(result.warning)) {
252 $(QWeb.render("DialogWarning", result.warning)).dialog({
256 $(this).dialog("close");
266 on_button_new: function() {
268 $.when(this.has_been_loaded).then(function() {
269 self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
270 self.on_record_loaded(result.result);
275 * Triggers saving the form's record. Chooses between creating a new
276 * record or saving an existing one depending on whether the record
277 * already has an id property.
279 * @param {Function} success callback on save success
280 * @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)
282 do_save: function(success, prepend_on_create) {
289 first_invalid_field = null;
290 for (var f in this.fields) {
295 if (!first_invalid_field) {
296 first_invalid_field = f;
298 } else if (f.touched) {
299 values[f.name] = f.get_value();
303 first_invalid_field.focus();
307 this.log("About to save", values);
308 if (!this.datarecord.id) {
309 this.dataset.create(values, function(r) {
310 self.on_created(r, success, prepend_on_create);
313 this.dataset.write(this.datarecord.id, values, function(r) {
314 self.on_saved(r, success);
320 do_save_edit: function() {
322 //this.switch_readonly(); Use promises
324 switch_readonly: function() {
326 switch_editable: function() {
328 on_invalid: function() {
330 _.each(this.fields, function(f) {
332 msg += "<li>" + f.string + "</li>";
336 this.notification.warn("The following fields are invalid :", msg);
338 on_saved: function(r, success) {
340 this.notification.warn("Record not saved", "Problem while saving record.");
342 this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
350 * Updates the form' dataset to contain the new record:
352 * * Adds the newly created record to the current dataset (at the end by
354 * * Selects that record (sets the dataset's index to point to the new
356 * * Updates the pager and sidebar displays
359 * @param {Function} success callback to execute after having updated the dataset
360 * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
362 on_created: function(r, success, prepend_on_create) {
364 this.notification.warn("Record not created", "Problem while creating record.");
366 this.datarecord.id = r.result;
367 if (!prepend_on_create) {
368 this.dataset.ids.push(this.datarecord.id);
369 this.dataset.index = this.dataset.ids.length - 1;
371 this.dataset.ids.unshift(this.datarecord.id);
372 this.dataset.index = 0;
374 this.do_update_pager();
375 this.do_update_sidebar();
376 this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
378 success(_.extend(r, {created: true}));
383 do_search: function (domains, contexts, groupbys) {
384 this.notification.notify("Searching form");
386 on_action: function (action) {
387 this.notification.notify('Executing action ' + action);
389 do_cancel: function () {
390 this.notification.notify("Cancelling form");
392 do_update_sidebar: function() {
393 if (this.flags.sidebar === false) {
396 if (!this.datarecord.id) {
397 this.on_attachments_loaded([]);
399 // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
400 /*(new openerp.base.DataSetSearch(
401 this.session, 'ir.attachment', this.dataset.get_context(),
402 [['res_model', '=', this.dataset.model],
403 ['res_id', '=', this.datarecord.id],
404 ['type', 'in', ['binary', 'url']]])).read_slice(
405 ['name', 'url', 'type'], false, false,
406 this.on_attachments_loaded);*/
409 on_attachments_loaded: function(attachments) {
410 this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
411 this.attachments = attachments;
412 this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
413 this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
414 this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
416 on_attachment_changed: function(e) {
417 window[this.element_id + '_iframe'] = this.do_update_sidebar;
418 var $e = $(e.target);
419 if ($e.val() != '') {
420 this.$sidebar.find('form.oe-binary-form').submit();
421 $e.parent().find('input[type=file]').attr('disabled', 'true');
422 $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
425 on_attachment_delete: function(e) {
426 var self = this, $e = $(e.currentTarget);
427 var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
428 if (confirm("Do you really want to delete the attachment " + name + " ?")) {
429 this.rpc('/base/dataset/unlink', {
430 model: 'ir.attachment',
431 ids: [parseInt($e.attr('data-id'))]
433 $e.parent().remove();
434 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
439 if (this.datarecord.id) {
440 this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
442 this.on_button_new();
445 get_fields_values: function() {
447 _.each(this.fields, function(value, key) {
448 var val = value.get_value();
456 openerp.base.form = {};
458 openerp.base.form.compute_domain = function(expr, fields) {
460 for (var i = expr.length - 1; i >= 0; i--) {
462 if (ex.length == 1) {
463 var top = stack.pop();
466 stack.push(stack.pop() || top);
469 stack.push(stack.pop() && top);
475 throw new Error('Unknown domain operator ' + ex);
479 var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
483 switch (op.toLowerCase()) {
486 stack.push(field == val);
490 stack.push(field != val);
493 stack.push(field < val);
496 stack.push(field > val);
499 stack.push(field <= val);
502 stack.push(field >= val);
505 stack.push(_(val).contains(field));
508 stack.push(!_(val).contains(field));
511 this.log("Unsupported operator in modifiers :", op);
517 openerp.base.form.Widget = openerp.base.Controller.extend({
519 init: function(view, node) {
522 this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
523 this.type = this.type || node.tag;
524 this.element_name = this.element_name || this.type;
525 this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
527 this._super(this.view.session, this.element_id);
529 this.view.widgets[this.element_id] = this;
530 this.children = node.children;
531 this.colspan = parseInt(node.attrs.colspan || 1);
533 this.string = this.string || node.attrs.string;
534 this.help = this.help || node.attrs.help;
535 this.invisible = this.modifiers['invisible'] === true;
538 this.$element = $('#' + this.element_id);
541 this.$element.remove();
543 process_modifiers: function() {
544 var compute_domain = openerp.base.form.compute_domain;
545 for (var a in this.modifiers) {
546 this[a] = compute_domain(this.modifiers[a], this.view.fields);
549 update_dom: function() {
550 this.$element.toggle(!this.invisible);
553 var template = this.template;
554 return QWeb.render(template, { "widget": this });
558 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
559 template: 'WidgetFrame',
560 init: function(view, node) {
561 this._super(view, node);
562 this.columns = node.attrs.col || 4;
567 for (var i = 0; i < node.children.length; i++) {
568 var n = node.children[i];
569 if (n.tag == "newline") {
575 this.set_row_cells_with(this.table[this.table.length - 1]);
578 if (this.table.length) {
579 this.set_row_cells_with(this.table[this.table.length - 1]);
582 this.table.push(row);
587 set_row_cells_with: function(row) {
588 for (var i = 0; i < row.length; i++) {
590 if (w.is_field_label) {
593 row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
595 } else if (w.width === undefined) {
596 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
600 handle_node: function(node) {
602 if (node.tag == 'field') {
603 type = this.view.fields_view.fields[node.attrs.name] || {};
605 var widget = new (this.view.registry.get_any(
606 [node.attrs.widget, type.type, node.tag])) (this.view, node);
607 if (node.tag == 'field') {
608 if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
609 this.view.default_focus_field = widget;
611 if (node.attrs.nolabel != '1') {
612 var label = new (this.view.registry.get_object('label')) (this.view, node);
613 label["for"] = widget;
614 this.add_widget(label);
617 this.add_widget(widget);
619 add_widget: function(widget) {
620 var current_row = this.table[this.table.length - 1];
621 if (current_row.length && (this.x + widget.colspan) > this.columns) {
622 current_row = this.add_row();
624 current_row.push(widget);
625 this.x += widget.colspan;
630 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
631 template: 'WidgetNotebook',
632 init: function(view, node) {
633 this._super(view, node);
635 for (var i = 0; i < node.children.length; i++) {
636 var n = node.children[i];
637 if (n.tag == "page") {
638 var page = new openerp.base.form.WidgetNotebookPage(this.view, n, this, this.pages.length);
639 this.pages.push(page);
644 this._super.apply(this, arguments);
645 this.$element.tabs();
649 openerp.base.form.WidgetNotebookPage = openerp.base.form.WidgetFrame.extend({
650 template: 'WidgetNotebookPage',
651 init: function(view, node, notebook, index) {
652 this.notebook = notebook;
654 this.element_name = 'page_' + index;
655 this._super(view, node);
656 this.element_tab_id = this.element_id + '_tab';
659 this._super.apply(this, arguments);
660 this.$element_tab = $('#' + this.element_tab_id);
662 update_dom: function() {
663 if (this.invisible) {
664 this.notebook.$element.tabs('select', 0);
666 this.$element_tab.toggle(!this.invisible);
667 this.$element.toggle(!this.invisible);
671 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
672 init: function(view, node) {
673 this._super(view, node);
674 this.template = "WidgetSeparator";
678 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
679 init: function(view, node) {
680 this._super(view, node);
681 this.template = "WidgetButton";
682 if (node.attrs.default_focus == '1') {
683 // TODO fme: provide enter key binding to widgets
684 this.view.default_focus_button = this;
688 this._super.apply(this, arguments);
689 this.$element.click(this.on_click);
691 on_click: function(saved) {
693 if (!this.node.attrs.special && this.view.touched && saved !== true) {
694 this.view.do_save(function() {
698 if (this.node.attrs.confirm) {
699 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
705 $(this).dialog("close");
708 $(this).dialog("close");
717 on_confirmed: function() {
720 this.view.execute_action(
721 this.node.attrs, this.view.dataset, this.session.action_manager,
722 this.view.datarecord.id, function (result) {
723 self.log("Button returned", result);
731 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
732 init: function(view, node) {
733 this.element_name = 'label_' + node.attrs.name;
735 this._super(view, node);
737 // TODO fme: support for attrs.align
738 if (this.node.tag == 'label' && this.node.attrs.colspan) {
739 this.is_field_label = false;
740 this.template = "WidgetParagraph";
742 this.is_field_label = true;
743 this.template = "WidgetLabel";
747 render: function () {
748 if (this['for'] && this.type !== 'label') {
749 return QWeb.render(this.template, {widget: this['for']});
751 // Actual label widgets should not have a false and have type label
752 return QWeb.render(this.template, {widget: this});
756 openerp.base.form.Field = openerp.base.form.Widget.extend({
757 init: function(view, node) {
758 this.name = node.attrs.name;
759 this.value = undefined;
760 view.fields[this.name] = this;
761 this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
762 this.element_name = "field_" + this.name + "_" + this.type;
764 this._super(view, node);
766 if (node.attrs.nolabel != '1' && this.colspan > 1) {
769 this.field = view.fields_view.fields[node.attrs.name] || {};
770 this.string = node.attrs.string || this.field.string;
771 this.help = node.attrs.help || this.field.help;
772 this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
773 this.readonly = this.modifiers['readonly'] === true;
774 this.required = this.modifiers['required'] === true;
775 this.invalid = false;
776 this.touched = false;
778 set_value: function(value) {
780 this.invalid = false;
783 set_value_from_ui: function() {
784 this.value = undefined;
786 get_value: function() {
789 get_on_change_value: function() {
790 return this.get_value();
792 update_dom: function() {
793 this._super.apply(this, arguments);
794 this.$element.toggleClass('disabled', this.readonly);
795 this.$element.toggleClass('required', this.required);
796 if (this.view.show_invalid) {
797 this.$element.toggleClass('invalid', this.invalid);
800 on_ui_change: function() {
801 this.touched = this.view.touched = true;
804 this.set_value_from_ui();
805 this.view.do_onchange(this);
806 this.view.on_form_changed();
811 validate: function() {
812 this.invalid = false;
816 _build_view_fields_values: function() {
817 var a_dataset = this.view.dataset || {};
818 var fields_values = this.view.get_fields_values();
819 var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
820 fields_values.parent = parent_values;
821 return fields_values;
824 * Builds a new context usable for operations related to fields by merging
825 * the fields'context with the action's context.
827 build_context: function() {
828 var a_context = this.view.dataset.get_context() || {};
829 var f_context = this.field.context || {};
830 var v_context1 = this.node.attrs.default_get || {};
831 var v_context2 = this.node.attrs.context || {};
832 var v_context = new openerp.base.CompoundContext(v_context1, v_context2);
833 if (v_context1.__ref || v_context2.__ref || true) { //TODO niv: remove || true
834 var fields_values = this._build_view_fields_values();
835 v_context.set_eval_context(fields_values);
837 var ctx = new openerp.base.CompoundContext(a_context, f_context, v_context);
840 build_domain: function() {
841 var f_domain = this.field.domain || [];
842 var v_domain = this.node.attrs.domain || [];
843 if (!(v_domain instanceof Array) || true) { //TODO niv: remove || true
844 var fields_values = this._build_view_fields_values();
845 v_domain = new openerp.base.CompoundDomain(v_domain).set_eval_context(fields_values);
847 return new openerp.base.CompoundDomain(f_domain, v_domain);
851 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
852 init: function(view, node) {
853 this._super(view, node);
854 this.template = "FieldChar";
857 this._super.apply(this, arguments);
858 this.$element.find('input').change(this.on_ui_change);
860 set_value: function(value) {
861 this._super.apply(this, arguments);
862 var show_value = (value != null && value !== false) ? value : '';
863 this.$element.find('input').val(show_value);
865 update_dom: function() {
866 this._super.apply(this, arguments);
867 this.$element.find('input').attr('disabled', this.readonly);
869 set_value_from_ui: function() {
870 this.value = this.$element.find('input').val();
872 validate: function() {
873 this.invalid = false;
874 var value = this.$element.find('input').val();
876 this.invalid = this.required;
877 } else if (this.validation_regex) {
878 this.invalid = !this.validation_regex.test(value);
882 this.$element.find('input').focus();
886 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
887 init: function(view, node) {
888 this._super(view, node);
889 this.template = "FieldEmail";
890 this.validation_regex = /@/;
893 this._super.apply(this, arguments);
894 this.$element.find('button').click(this.on_button_clicked);
896 on_button_clicked: function() {
897 if (!this.value || this.invalid) {
898 this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
900 location.href = 'mailto:' + this.value;
903 set_value: function(value) {
904 this._super.apply(this, arguments);
905 var show_value = (value != null && value !== false) ? value : '';
906 this.$element.find('a').attr('href', 'mailto:' + show_value);
910 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
911 init: function(view, node) {
912 this._super(view, node);
913 this.template = "FieldUrl";
916 this._super.apply(this, arguments);
917 this.$element.find('button').click(this.on_button_clicked);
919 on_button_clicked: function() {
921 this.notification.warn("Resource error", "This resource is empty");
923 window.open(this.value);
928 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
929 init: function(view, node) {
930 this._super(view, node);
931 this.validation_regex = /^-?\d+(\.\d+)?$/;
933 set_value: function(value) {
934 this._super.apply(this, [value]);
935 if (value === false || value === undefined) {
936 // As in GTK client, floats default to 0
940 var show_value = value.toFixed(2);
941 this.$element.find('input').val(show_value);
943 set_value_from_ui: function() {
944 this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
948 openerp.base.form.FieldInteger = openerp.base.form.FieldFloat.extend({
949 init: function(view, node) {
950 this._super(view, node);
951 this.validation_regex = /^-?\d+$/;
953 set_value: function(value) {
954 this._super.apply(this, [value]);
955 if (value === false || value === undefined) {
956 // TODO fme: check if GTK client default integers to 0 (like it does with floats)
960 var show_value = parseInt(value, 10);
961 this.$element.find('input').val(show_value);
963 set_value_from_ui: function() {
964 this.value = Number(this.$element.find('input').val());
968 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
969 init: function(view, node) {
970 this._super(view, node);
971 this.template = "FieldDate";
972 this.jqueryui_object = 'datetimepicker';
973 this.validation_regex = /^\d+-\d+-\d+( \d+:\d+(:\d+)?)?$/;
976 this._super.apply(this, arguments);
977 this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
978 dateFormat: 'yy-mm-dd',
979 timeFormat: 'hh:mm:ss',
981 buttonImage: '/base/static/src/img/ui/field_calendar.png',
982 buttonImageOnly: true,
983 constrainInput: false
986 set_value: function(value) {
987 this._super.apply(this, arguments);
989 this.$element.find('input').val('');
991 this.$element.find('input').unbind('change');
992 // jQuery UI date picker wrongly call on_change event herebelow
993 this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
994 this.$element.find('input').change(this.on_ui_change);
997 set_value_from_ui: function() {
998 this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
1000 this.value = this.format(this.value);
1003 update_dom: function() {
1004 this._super.apply(this, arguments);
1005 this.$element.find('input').datepicker(this.readonly ? 'disable' : 'enable');
1007 validate: function() {
1008 this.invalid = false;
1009 var value = this.$element.find('input').val();
1011 this.invalid = this.required;
1012 } else if (this.validation_regex) {
1013 this.invalid = !this.validation_regex.test(value);
1015 this.invalid = !this.$element.find('input')[this.jqueryui_object]('getDate');
1019 this.$element.find('input').focus();
1021 parse: openerp.base.parse_datetime,
1022 format: openerp.base.format_datetime
1025 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
1026 init: function(view, node) {
1027 this._super(view, node);
1028 this.jqueryui_object = 'datepicker';
1029 this.validation_regex = /^\d+-\d+-\d+$/;
1031 parse: openerp.base.parse_date,
1032 format: openerp.base.format_date
1035 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
1036 init: function(view, node) {
1037 this._super(view, node);
1038 this.validation_regex = /^\d+:\d+$/;
1040 set_value: function(value) {
1041 this._super.apply(this, [value]);
1042 if (value === false || value === undefined) {
1043 // As in GTK client, floats default to 0
1045 this.touched = true;
1047 var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
1048 this.$element.find('input').val(show_value);
1050 set_value_from_ui: function() {
1051 var time = this.$element.find('input').val().split(':');
1052 this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
1056 openerp.base.form.FieldText = openerp.base.form.Field.extend({
1057 init: function(view, node) {
1058 this._super(view, node);
1059 this.template = "FieldText";
1060 this.validation_regex = null;
1063 this._super.apply(this, arguments);
1064 this.$element.find('textarea').change(this.on_ui_change);
1066 set_value: function(value) {
1067 this._super.apply(this, arguments);
1068 var show_value = (value != null && value !== false) ? value : '';
1069 this.$element.find('textarea').val(show_value);
1071 update_dom: function() {
1072 this._super.apply(this, arguments);
1073 this.$element.find('textarea').attr('disabled', this.readonly);
1075 set_value_from_ui: function() {
1076 this.value = this.$element.find('textarea').val();
1078 validate: function() {
1079 this.invalid = false;
1080 var value = this.$element.find('textarea').val();
1082 this.invalid = this.required;
1083 } else if (this.validation_regex) {
1084 this.invalid = !this.validation_regex.test(value);
1088 this.$element.find('textarea').focus();
1092 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
1093 init: function(view, node) {
1094 this._super(view, node);
1095 this.template = "FieldBoolean";
1099 this._super.apply(this, arguments);
1100 this.$element.find('input').click(function() {
1101 if ($(this).is(':checked') != self.value) {
1102 self.on_ui_change();
1106 set_value: function(value) {
1107 this._super.apply(this, arguments);
1108 this.$element.find('input')[0].checked = value;
1110 set_value_from_ui: function() {
1111 this.value = this.$element.find('input').is(':checked');
1113 update_dom: function() {
1114 this._super.apply(this, arguments);
1115 this.$element.find('input').attr('disabled', this.readonly);
1117 validate: function() {
1118 this.invalid = this.required && !this.$element.find('input').is(':checked');
1121 this.$element.find('input').focus();
1125 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1126 init: function(view, node) {
1127 this._super(view, node);
1128 this.template = "FieldProgressBar";
1131 this._super.apply(this, arguments);
1132 this.$element.find('div').progressbar({
1134 disabled: this.readonly
1137 set_value: function(value) {
1138 this._super.apply(this, arguments);
1139 var show_value = Number(value);
1140 if (isNaN(show_value)) {
1143 this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1147 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1148 // to replace view editor
1151 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1152 init: function(view, node) {
1153 this._super(view, node);
1154 this.template = "FieldSelection";
1155 this.field_index = _.map(this.field.selection, function(x, index) {
1156 return {"ikey": "" + index, "ekey": x[0], "label": x[1]};
1160 // Flag indicating whether we're in an event chain containing a change
1161 // event on the select, in order to know what to do on keyup[RETURN]:
1162 // * If the user presses [RETURN] as part of changing the value of a
1163 // selection, we should just let the value change and not let the
1164 // event broadcast further (e.g. to validating the current state of
1165 // the form in editable list view, which would lead to saving the
1166 // current row or switching to the next one)
1167 // * If the user presses [RETURN] with a select closed (side-effect:
1168 // also if the user opened the select and pressed [RETURN] without
1169 // changing the selected value), takes the action as validating the
1171 var ischanging = false;
1172 this._super.apply(this, arguments);
1173 this.$element.find('select')
1174 .change(this.on_ui_change)
1175 .change(function () { ischanging = true; })
1176 .click(function () { ischanging = false; })
1177 .keyup(function (e) {
1178 if (e.which !== 13 || !ischanging) { return; }
1179 e.stopPropagation();
1183 set_value: function(value) {
1184 value = value === null ? false : value;
1185 value = value instanceof Array ? value[0] : value;
1187 var option = _.detect(this.field_index, function(x) {return x.ekey === value;});
1188 this.$element.find('select').val(option === undefined ? '' : option.ikey);
1190 set_value_from_ui: function() {
1191 var ikey = this.$element.find('select').val();
1192 var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1193 this.value = option === undefined ? false : option.ekey;
1195 update_dom: function() {
1196 this._super.apply(this, arguments);
1197 this.$element.find('select').attr('disabled', this.readonly);
1199 validate: function() {
1200 var ikey = this.$element.find('select').val();
1201 var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1202 this.invalid = this.required && (option === undefined || option.ekey === false);
1205 this.$element.find('select').focus();
1209 // jquery autocomplete tweak to allow html
1211 var proto = $.ui.autocomplete.prototype,
1212 initSource = proto._initSource;
1214 function filter( array, term ) {
1215 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1216 return $.grep( array, function(value) {
1217 return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1222 _initSource: function() {
1223 if ( this.options.html && $.isArray(this.options.source) ) {
1224 this.source = function( request, response ) {
1225 response( filter( this.options.source, request.term ) );
1228 initSource.call( this );
1232 _renderItem: function( ul, item) {
1233 return $( "<li></li>" )
1234 .data( "item.autocomplete", item )
1235 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1241 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1242 init: function(view, node) {
1243 this._super(view, node);
1244 this.template = "FieldMany2One";
1247 this.cm_id = _.uniqueId('m2o_cm_');
1248 this.last_search = [];
1249 this.tmp_value = undefined;
1254 this.$input = this.$element.find("input");
1255 this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1256 this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1260 bindings[this.cm_id + "_search"] = function() {
1261 self._search_create_popup("search");
1263 bindings[this.cm_id + "_create"] = function() {
1264 self._search_create_popup("form");
1266 bindings[this.cm_id + "_open"] = function() {
1270 self.session.action_manager.do_action({
1271 "res_model": self.field.relation,
1272 "views":[[false,"form"]],
1273 "res_id": self.value[0],
1274 "type":"ir.actions.act_window",
1276 "context": self.build_context()
1279 var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1280 bindings: bindings, itemStyle: {"color": ""},
1281 onContextMenu: function() {
1283 $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1285 $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1291 // some behavior for input
1292 this.$input.keyup(function() {
1293 if (self.$input.val() === "") {
1294 self._change_int_value(null);
1295 } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1296 self._change_int_value(undefined);
1299 this.$drop_down.click(function() {
1300 if (self.$input.autocomplete("widget").is(":visible")) {
1301 self.$input.autocomplete("close");
1304 self.$input.autocomplete("search", "");
1306 self.$input.autocomplete("search");
1308 self.$input.focus();
1311 var anyoneLoosesFocus = function() {
1312 if (!self.$input.is(":focus") &&
1313 !self.$input.autocomplete("widget").is(":visible") &&
1315 if(self.value === undefined && self.last_search.length > 0) {
1316 self._change_int_ext_value(self.last_search[0]);
1318 self._change_int_ext_value(null);
1322 this.$input.focusout(anyoneLoosesFocus);
1324 var isSelecting = false;
1326 this.$input.autocomplete({
1327 source: function(req, resp) { self.get_search_result(req, resp); },
1328 select: function(event, ui) {
1332 self._change_int_value([item.id, item.name]);
1333 } else if (item.action) {
1334 self._change_int_value(undefined);
1339 focus: function(e, ui) {
1343 close: anyoneLoosesFocus,
1347 // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1348 this.$input.keyup(function(e) {
1349 if (e.which === 13) {
1351 e.stopPropagation();
1353 isSelecting = false;
1356 // autocomplete component content handling
1357 get_search_result: function(request, response) {
1358 var search_val = request.term;
1361 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1363 dataset.name_search(search_val, self.build_domain(), 'ilike',
1364 this.limit + 1, function(data) {
1365 self.last_search = data.result;
1366 // possible selections for the m2o
1367 var values = _.map(data.result, function(x) {
1368 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1371 // search more... if more results that max
1372 if (values.length > self.limit) {
1373 values = values.slice(0, self.limit);
1374 values.push({label: "<em>Â Â Â Search More...</em>", action: function() {
1375 dataset.name_search(search_val, self.build_domain(), 'ilike'
1376 , false, function(data) {
1377 self._change_int_value(null);
1378 self._search_create_popup("search", data.result);
1383 var raw_result = _(data.result).map(function(x) {return x[1];})
1384 if (search_val.length > 0 &&
1385 !_.include(raw_result, search_val) &&
1386 (!self.value || search_val !== self.value[1])) {
1387 values.push({label: '<em>Â Â Â Create "<strong>' +
1388 $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1389 self._quick_create(search_val);
1393 values.push({label: "<em>Â Â Â Create and Edit...</em>", action: function() {
1394 self._change_int_value(null);
1395 self._search_create_popup("form", undefined, {"default_name": search_val});
1401 _quick_create: function(name) {
1403 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1404 dataset.name_create(name, function(data) {
1405 self._change_int_ext_value(data.result);
1406 }).fail(function(error, event) {
1407 event.preventDefault();
1408 self._change_int_value(null);
1409 self._search_create_popup("form", undefined, {"default_name": name});
1412 // all search/create popup handling
1413 _search_create_popup: function(view, ids, context) {
1415 var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1416 pop.select_element(self.field.relation,{
1417 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1419 disable_multiple_selection: true
1420 }, self.build_domain(),
1421 new openerp.base.CompoundContext(self.build_context(), context || {}));
1422 pop.on_select_elements.add(function(element_ids) {
1423 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1424 dataset.name_get([element_ids[0]], function(data) {
1425 self._change_int_ext_value(data.result[0]);
1430 _change_int_ext_value: function(value) {
1431 this._change_int_value(value);
1432 this.$input.val(this.value ? this.value[1] : "");
1434 _change_int_value: function(value) {
1436 var back_orig_value = this.original_value;
1437 if (this.value === null || this.value) {
1438 this.original_value = this.value;
1440 if (back_orig_value === undefined) { // first use after a set_value()
1443 if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1444 !== (this.value ? this.value[0] : null))) {
1445 this.on_ui_change();
1448 set_value_from_ui: function() {},
1449 set_value: function(value) {
1450 value = value || null;
1452 var _super = this._super;
1453 this.tmp_value = value;
1454 var real_set_value = function(rval) {
1455 self.tmp_value = undefined;
1456 _super.apply(self, rval);
1457 self.original_value = undefined;
1458 self._change_int_ext_value(rval);
1460 if(typeof(value) === "number") {
1461 var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1462 dataset.name_get([value], function(data) {
1463 real_set_value(data.result[0]);
1464 }).fail(function() {self.tmp_value = undefined;});
1466 setTimeout(function() {real_set_value(value);}, 0);
1469 get_value: function() {
1470 if (this.tmp_value !== undefined) {
1471 if (this.tmp_value instanceof Array) {
1472 return this.tmp_value[0];
1474 return this.tmp_value ? this.tmp_value : false;
1476 if (this.value === undefined)
1477 return this.original_value ? this.original_value[0] : false;
1478 return this.value ? this.value[0] : false;
1480 validate: function() {
1481 this.invalid = false;
1482 if (this.value === null) {
1483 this.invalid = this.required;
1489 # Values: (0, 0, { fields }) create
1490 # (1, ID, { fields }) update
1491 # (2, ID) remove (delete)
1492 # (3, ID) unlink one (target id or target of relation)
1494 # (5) unlink all (only valid for one2many)
1499 'create': function (values) {
1500 return [commands.CREATE, false, values];
1502 // (1, id, {values})
1504 'update': function (id, values) {
1505 return [commands.UPDATE, id, values];
1509 'delete': function (id) {
1510 return [commands.DELETE, id, false];
1512 // (3, id[, _]) removes relation, but not linked record itself
1514 'forget': function (id) {
1515 return [commands.FORGET, id, false];
1519 'link_to': function (id) {
1520 return [commands.LINK_TO, id, false];
1524 'delete_all': function () {
1525 return [5, false, false];
1527 // (6, _, ids) replaces all linked records with provided ids
1529 'replace_with': function (ids) {
1530 return [6, false, ids];
1533 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1534 multi_selection: false,
1535 init: function(view, node) {
1536 this._super(view, node);
1537 this.template = "FieldOne2Many";
1538 this.is_started = $.Deferred();
1541 this._super.apply(this, arguments);
1545 this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1546 this.dataset.o2m = this;
1547 this.dataset.parent_view = this.view;
1548 this.dataset.on_change.add_last(function() {
1549 self.on_ui_change();
1552 var modes = this.node.attrs.mode;
1553 modes = !!modes ? modes.split(",") : ["tree", "form"];
1555 _.each(modes, function(mode) {
1556 var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1557 if (self.field.views && self.field.views[mode]) {
1558 view.embedded_view = self.field.views[mode];
1560 if(view.view_type === "list") {
1562 'selectable': self.multi_selection
1569 this.viewmanager = new openerp.base.ViewManager(this.view.session,
1570 this.element_id, this.dataset, views);
1571 this.viewmanager.registry = openerp.base.views.clone({
1572 list: 'openerp.base.form.One2ManyListView'
1575 this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1576 if (view_type == "list") {
1577 controller.o2m = self;
1578 } else if (view_type == "form") {
1581 self.is_started.resolve();
1583 setTimeout(function () {
1584 self.viewmanager.start();
1587 reload_current_view: function() {
1589 var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1590 if(self.viewmanager.active_view === "list") {
1591 view.reload_content();
1592 } else if (self.viewmanager.active_view === "form") {
1593 // TODO niv: implement
1596 set_value_from_ui: function() {},
1597 set_value: function(value) {
1598 value = value || [];
1600 this.dataset.reset_ids([]);
1601 if(value.length >= 1 && value[0] instanceof Array) {
1603 _.each(value, function(command) {
1604 var obj = {values: command[2]};
1605 switch (command[0]) {
1606 case commands.CREATE:
1607 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1608 self.dataset.to_create.push(obj);
1609 self.dataset.cache.push(_.clone(obj));
1612 case commands.UPDATE:
1613 obj['id'] = command[1];
1614 self.dataset.to_write.push(obj);
1615 self.dataset.cache.push(_.clone(obj));
1618 case commands.DELETE:
1619 self.dataset.to_delete.push({id: command[1]});
1621 case commands.LINK_TO:
1622 ids.push(command[1]);
1624 case commands.DELETE_ALL:
1625 self.dataset.delete_all = true;
1630 this.dataset.set_ids(ids);
1631 } else if (value.length >= 1 && typeof(value[0]) === "object") {
1633 this.dataset.delete_all = true;
1634 _.each(value, function(command) {
1635 var obj = {values: command};
1636 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1637 self.dataset.to_create.push(obj);
1638 self.dataset.cache.push(_.clone(obj));
1642 this.dataset.set_ids(ids);
1645 this.dataset.reset_ids(value);
1647 $.when(this.is_started).then(function() {
1648 self.reload_current_view();
1651 get_value: function() {
1655 var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1656 val = val.concat(_.map(this.dataset.ids, function(id) {
1657 var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1659 return commands.create(alter_order.values);
1661 alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1663 return commands.update(alter_order.id, alter_order.values);
1665 return commands.link_to(id);
1667 return val.concat(_.map(
1668 this.dataset.to_delete, function(x) {
1669 return commands['delete'](x.id);}));
1671 validate: function() {
1672 this.invalid = false;
1677 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1678 get_context: function() {
1679 this.context = this.o2m.build_context();
1680 return this.context;
1684 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1685 do_add_record: function () {
1686 if (this.options.editable) {
1687 this._super.apply(this, arguments);
1690 var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1691 pop.select_element(self.o2m.field.relation,{
1692 initial_view: "form",
1693 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1695 parent_view: self.o2m.view
1696 }, self.o2m.build_domain(), self.o2m.build_context());
1697 pop.on_create.add(function(data) {
1698 self.o2m.dataset.create(data, function(r) {
1699 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1700 self.o2m.dataset.on_change();
1702 self.o2m.reload_current_view();
1709 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1710 multi_selection: false,
1711 init: function(view, node) {
1712 this._super(view, node);
1713 this.template = "FieldMany2Many";
1714 this.list_id = _.uniqueId("many2many");
1715 this.is_started = $.Deferred();
1718 this._super.apply(this, arguments);
1722 this.dataset = new openerp.base.form.Many2ManyDataSet(
1723 this.session, this.field.relation);
1724 this.dataset.m2m = this;
1725 this.dataset.on_unlink.add_last(function(ids) {
1726 self.on_ui_change();
1729 this.list_view = new openerp.base.form.Many2ManyListView(
1730 null, this.view.session, this.list_id, this.dataset, false, {
1732 'selectable': self.multi_selection
1734 this.list_view.m2m_field = this;
1735 this.list_view.on_loaded.add_last(function() {
1736 self.is_started.resolve();
1738 setTimeout(function () {
1739 self.list_view.start();
1742 set_value: function(value) {
1743 value = value || [];
1744 if (value.length >= 1 && value[0] instanceof Array) {
1745 value = value[0][2];
1748 this.dataset.set_ids(value);
1750 $.when(this.is_started).then(function() {
1751 self.list_view.reload_content();
1754 get_value: function() {
1755 return [commands.replace_with(this.dataset.ids)];
1757 set_value_from_ui: function() {},
1758 validate: function() {
1759 this.invalid = false;
1764 openerp.base.form.Many2ManyDataSet = openerp.base.DataSetStatic.extend({
1765 get_context: function() {
1766 this.context = this.m2m.build_context();
1767 return this.context;
1771 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1772 do_add_record: function () {
1773 var pop = new openerp.base.form.SelectCreatePopup(
1774 null, this.m2m_field.view.session);
1775 pop.select_element(this.model, {},
1776 new openerp.base.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
1777 this.m2m_field.build_context());
1779 pop.on_select_elements.add(function(element_ids) {
1780 _.each(element_ids, function(element_id) {
1781 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1782 self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1783 self.m2m_field.on_ui_change();
1784 self.reload_content();
1790 do_activate_record: function(index, id) {
1791 this.m2m_field.view.session.action_manager.do_action({
1792 "res_model": this.dataset.model,
1793 "views": [[false,"form"]],
1795 "type": "ir.actions.act_window",
1796 "view_type": "form",
1797 "view_mode": "form",
1799 "context": this.m2m_field.build_context()
1804 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1805 identifier_prefix: "selectcreatepopup",
1806 template: "SelectCreatePopup",
1810 * - initial_view: form or search (default search)
1811 * - disable_multiple_selection
1812 * - alternative_form_view
1813 * - auto_create (default true)
1816 select_element: function(model, options, domain, context) {
1818 this.domain = domain || [];
1819 this.context = context || {};
1820 this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1821 this.initial_ids = this.options.initial_ids;
1822 jQuery(this.render()).dialog({title: '',
1830 this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1832 this.dataset.parent_view = this.options.parent_view;
1833 if (this.options.initial_view == "search") {
1834 this.setup_search_view();
1839 setup_search_view: function() {
1841 if (this.searchview) {
1842 this.searchview.stop();
1844 this.searchview = new openerp.base.SearchView(null, this.session,
1845 this.element_id + "_search", this.dataset, false, {
1846 "selectable": !this.options.disable_multiple_selection,
1849 this.searchview.on_search.add(function(domains, contexts, groupbys) {
1850 if (self.initial_ids) {
1851 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]], self.domain]),
1852 contexts, groupbys);
1853 self.initial_ids = undefined;
1855 self.view_list.do_search.call(self, domains.concat([self.domain]), contexts, groupbys);
1858 this.searchview.on_loaded.add_last(function () {
1859 var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1860 $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1861 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1862 $cbutton.click(function() {
1865 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1866 if(self.options.disable_multiple_selection) {
1869 $sbutton.click(function() {
1870 self.on_select_elements(self.selected_ids);
1872 self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1873 self.element_id + "_view_list", self.dataset, false,
1874 {'deletable': false});
1875 self.view_list.popup = self;
1876 self.view_list.do_show();
1877 self.view_list.start().then(function() {
1878 self.searchview.do_search();
1881 this.searchview.start();
1883 on_create: function(data) {
1884 if (!this.options.auto_create)
1887 var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1888 wdataset = this.options.parent_view;
1889 wdataset.create(data, function(r) {
1890 self.on_select_elements([r.result]);
1893 on_select_elements: function(element_ids) {
1895 on_click_element: function(ids) {
1896 this.selected_ids = ids || [];
1897 if(this.selected_ids.length > 0) {
1898 this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1900 this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1903 new_object: function() {
1905 if (this.searchview) {
1906 this.searchview.hide();
1908 if (this.view_list) {
1909 this.view_list.$element.hide();
1911 this.dataset.index = null;
1912 this.view_form = new openerp.base.FormView(null, this.session,
1913 this.element_id + "_view_form", this.dataset, false);
1914 if (this.options.alternative_form_view) {
1915 this.view_form.set_embedded_view(this.options.alternative_form_view);
1917 this.view_form.start();
1918 this.view_form.on_loaded.add_last(function() {
1919 var $buttons = self.view_form.$element.find(".oe_form_buttons");
1920 $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1921 var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1922 $nbutton.click(function() {
1923 self.view_form.do_save();
1925 var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1926 $cbutton.click(function() {
1930 this.dataset.on_create.add(this.on_create);
1931 this.view_form.do_show();
1935 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1936 do_add_record: function () {
1937 this.popup.new_object();
1939 select_record: function(index) {
1940 this.popup.on_select_elements([this.dataset.ids[index]]);
1942 do_select: function(ids, records) {
1943 this._super(ids, records);
1944 this.popup.on_click_element(ids);
1948 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1949 init: function(view, node) {
1950 this._super(view, node);
1951 this.template = "FieldReference";
1955 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1956 init: function(view, node) {
1957 this._super(view, node);
1958 this.iframe = this.element_id + '_iframe';
1959 this.binary_value = false;
1962 this._super.apply(this, arguments);
1963 this.$element.find('input.oe-binary-file').change(this.on_file_change);
1964 this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1965 this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1967 set_value_from_ui: function() {
1969 human_filesize : function(size) {
1970 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1972 while (size >= 1024) {
1976 return size.toFixed(2) + ' ' + units[i];
1978 on_file_change: function(e) {
1979 // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1980 // http://www.html5rocks.com/tutorials/file/dndfiles/
1981 // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1982 window[this.iframe] = this.on_file_uploaded;
1983 if ($(e.target).val() != '') {
1984 this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1985 this.$element.find('form.oe-binary-form').submit();
1986 this.toggle_progress();
1989 toggle_progress: function() {
1990 this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1992 on_file_uploaded: function(size, name, content_type, file_base64) {
1993 delete(window[this.iframe]);
1994 if (size === false) {
1995 this.notification.warn("File Upload", "There was a problem while uploading your file");
1996 // TODO: use openerp web exception handler
1997 console.log("Error while uploading file : ", name);
1999 this.on_file_uploaded_and_valid.apply(this, arguments);
2000 this.on_ui_change();
2002 this.toggle_progress();
2004 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2006 on_save_as: function() {
2007 if (!this.view.datarecord.id) {
2008 this.notification.warn("Can't save file", "The record has not yet been saved");
2010 var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
2011 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
2012 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
2016 on_clear: function() {
2017 if (this.value !== false) {
2019 this.binary_value = false;
2020 this.on_ui_change();
2026 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
2027 init: function(view, node) {
2028 this._super(view, node);
2029 this.template = "FieldBinaryFile";
2031 set_value: function(value) {
2032 this._super.apply(this, arguments);
2033 var show_value = (value != null && value !== false) ? value : '';
2034 this.$element.find('input').eq(0).val(show_value);
2036 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2037 this.value = file_base64;
2038 this.binary_value = true;
2039 var show_value = this.human_filesize(size);
2040 this.$element.find('input').eq(0).val(show_value);
2041 this.set_filename(name);
2043 set_filename: function(value) {
2044 var filename = this.node.attrs.filename;
2045 if (this.view.fields[filename]) {
2046 this.view.fields[filename].set_value(value);
2047 this.view.fields[filename].on_ui_change();
2050 on_clear: function() {
2051 this._super.apply(this, arguments);
2052 this.$element.find('input').eq(0).val('');
2053 this.set_filename('');
2057 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
2058 init: function(view, node) {
2059 this._super(view, node);
2060 this.template = "FieldBinaryImage";
2063 this._super.apply(this, arguments);
2064 this.$image = this.$element.find('img.oe-binary-image');
2066 set_image_maxwidth: function() {
2067 this.$image.css('max-width', this.$element.width());
2069 on_file_change: function() {
2070 this.set_image_maxwidth();
2071 this._super.apply(this, arguments);
2073 on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2074 this.value = file_base64;
2075 this.binary_value = true;
2076 this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2078 on_clear: function() {
2079 this._super.apply(this, arguments);
2080 this.$image.attr('src', '/base/static/src/img/placeholder.png');
2082 set_value: function(value) {
2083 this._super.apply(this, arguments);
2084 this.set_image_maxwidth();
2085 var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
2086 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
2087 this.$image.attr('src', url);
2092 * Registry of form widgets, called by :js:`openerp.base.FormView`
2094 openerp.base.form.widgets = new openerp.base.Registry({
2095 'frame' : 'openerp.base.form.WidgetFrame',
2096 'group' : 'openerp.base.form.WidgetFrame',
2097 'notebook' : 'openerp.base.form.WidgetNotebook',
2098 'separator' : 'openerp.base.form.WidgetSeparator',
2099 'label' : 'openerp.base.form.WidgetLabel',
2100 'button' : 'openerp.base.form.WidgetButton',
2101 'char' : 'openerp.base.form.FieldChar',
2102 'email' : 'openerp.base.form.FieldEmail',
2103 'url' : 'openerp.base.form.FieldUrl',
2104 'text' : 'openerp.base.form.FieldText',
2105 'text_wiki' : 'openerp.base.form.FieldText',
2106 'date' : 'openerp.base.form.FieldDate',
2107 'datetime' : 'openerp.base.form.FieldDatetime',
2108 'selection' : 'openerp.base.form.FieldSelection',
2109 'many2one' : 'openerp.base.form.FieldMany2One',
2110 'many2many' : 'openerp.base.form.FieldMany2Many',
2111 'one2many' : 'openerp.base.form.FieldOne2Many',
2112 'one2many_list' : 'openerp.base.form.FieldOne2Many',
2113 'reference' : 'openerp.base.form.FieldReference',
2114 'boolean' : 'openerp.base.form.FieldBoolean',
2115 'float' : 'openerp.base.form.FieldFloat',
2116 'integer': 'openerp.base.form.FieldInteger',
2117 'progressbar': 'openerp.base.form.FieldProgressBar',
2118 'float_time': 'openerp.base.form.FieldFloatTime',
2119 'image': 'openerp.base.form.FieldBinaryImage',
2120 'binary': 'openerp.base.form.FieldBinaryFile'
2125 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: