};
instance.web.views.add('form', 'instance.web.FormView');
-instance.web.FormView = instance.web.View.extend(_.extend({}, instance.web.form.FieldManagerMixin, {
+instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerMixin, {
/**
* Indicates that this view is not searchable, and thus that no search
* view should be displayed (if there is one active).
this.mutating_mutex = new $.Mutex();
this.on_change_mutex = new $.Mutex();
this.reload_mutex = new $.Mutex();
+ this.__clicked_inside = false;
+ this.__blur_timeout = null;
this.rendering_engine = new instance.web.form.FormRenderingEngineReadonly(this);
this.qweb = null; // A QWeb instance will be created if the view is a QWeb template
},
destroy: function() {
_.each(this.get_widgets(), function(w) {
+ w.off('focused blurred');
w.destroy();
});
+ this.$element.off('.formBlur');
this._super();
},
on_loaded: function(data) {
this.rendering_engine.render_to($dest);
}
+ this.$element.on('mousedown.formBlur', function () {
+ self.__clicked_inside = true;
+ });
this.$buttons = $(QWeb.render("FormView.buttons", {'widget':self}));
if (this.options.$buttons) {
this.translatable_fields = [];
this.$element.find('.oe_form_container').empty();
},
+
+ widgetFocused: function() {
+ // Clear click flag if used to focus a widget
+ this.__clicked_inside = false;
+ if (this.__blur_timeout) {
+ clearTimeout(this.__blur_timeout);
+ this.__blur_timeout = null;
+ }
+ },
+ widgetBlurred: function() {
+ if (this.__clicked_inside) {
+ // clicked in an other section of the form (than the currently
+ // focused widget) => just ignore the blurring entirely?
+ this.__clicked_inside = false;
+ return;
+ }
+ var self = this;
+ // clear timeout, if any
+ this.widgetFocused();
+ this.__blur_timeout = setTimeout(function () {
+ self.trigger('blurred');
+ }, 0);
+ },
+
do_load_state: function(state, warm) {
if (state.id && this.datarecord.id != state.id) {
if (!this.dataset.get_id_index(state.id)) {
}
}
},
- do_show: function () {
+ do_show: function (options) {
var self = this;
+ options = options || {};
if (this.sidebar) {
this.sidebar.$element.show();
}
}).pipe(self.on_record_loaded);
}
result.pipe(function() {
+ if (options.editable) {
+ self.set({mode: "edit"});
+ }
self.$element.css('visibility', 'visible');
});
return result;
return self.on_processed_onchange(response, processed);
} catch(e) {
console.error(e);
+ instance.webclient.crashmanager.on_javascript_exception(e);
return $.Deferred().reject();
}
});
},
- on_processed_onchange: function(response, processed) {
+ on_processed_onchange: function(result, processed) {
try {
- var result = response;
if (result.value) {
for (var f in result.value) {
if (!result.value.hasOwnProperty(f)) { continue; }
this.on_form_changed();
}
if (!_.isEmpty(result.warning)) {
- instance.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
+ instance.web.dialog($(QWeb.render("CrashManager.warning", result.warning)), {
+ title:result.warning.title,
modal: true,
buttons: [
{text: _t("Ok"), click: function() { $(this).dialog("close"); }}
}
if (result.domain) {
function edit_domain(node) {
+ if (typeof node !== "object") {
+ return;
+ }
var new_domain = result.domain[node.attrs.name];
if (new_domain) {
node.attrs.domain = new_domain;
return $.Deferred().resolve();
} catch(e) {
console.error(e);
+ instance.webclient.crashmanager.on_javascript_exception(e);
return $.Deferred().reject();
}
},
switch_mode: function() {
var self = this;
if(this.get("mode") == "view") {
+ self.$element.removeClass('oe_form_editable').addClass('oe_form_readonly');
self.$buttons.find('.oe_form_buttons_edit').hide();
self.$buttons.find('.oe_form_buttons_view').show();
self.$sidebar.show();
field.set({"force_readonly": true});
});
} else {
+ self.$element.removeClass('oe_form_readonly').addClass('oe_form_editable');
self.$buttons.find('.oe_form_buttons_edit').show();
self.$buttons.find('.oe_form_buttons_view').hide();
self.$sidebar.hide();
on_button_cancel: function(event) {
if (this.can_be_discarded()) {
this.set({mode: "view"});
+ this.on_record_loaded(this.datarecord);
}
return false;
},
* record or saving an existing one depending on whether the record
* already has an id property.
*
- * @param {Function} success callback on save success
+ * @param {Function} [success] callback on save success
* @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)
*/
do_save: function(success, prepend_on_create) {
}
if (form_invalid) {
self.set({'display_invalid_fields': true});
+ for (var f in self.fields) {
+ self.fields[f]._check_css_flags();
+ }
first_invalid_field.focus();
self.on_invalid();
return $.Deferred().reject();
return $.Deferred().reject();
} else {
return $.when(this.reload()).pipe(function () {
- return $.when(r).then(success); }, null);
+ return r; })
+ .then(success);
}
},
/**
if (this.sidebar) {
this.sidebar.do_attachement_update(this.dataset, this.datarecord.id);
}
- //instance.log("The record has been created with id #" + this.datarecord.id);
- this.reload();
- return $.when(_.extend(r, {created: true})).then(success);
+ //openerp.log("The record has been created with id #" + this.datarecord.id);
+ return $.when(this.reload()).pipe(function () {
+ return _.extend(r, {created: true}); })
+ .then(success);
}
},
on_action: function (action) {
register_field: function(field, name) {
this.fields[name] = field;
this.fields_order.push(name);
+
+ field.on('focused', null, this.proxy('widgetFocused'))
+ .on('blurred', null, this.proxy('widgetBlurred'));
if (this.get_field(name).translate) {
this.translatable_fields.push(field);
}
is_create_mode: function() {
return !this.datarecord.id;
},
-}));
+});
/**
* Interface to be implemented by rendering engines for the form view.
},
set_fields_view: function(fvg) {
this.fvg = fvg;
+ this.version = parseFloat(this.fvg.arch.attrs.version);
+ if (isNaN(this.version)) {
+ this.version = 6.1;
+ }
},
set_tags_registry: function(tags_registry) {
this.tags_registry = tags_registry;
set_fields_registry: function(fields_registry) {
this.fields_registry = fields_registry;
},
+ // Backward compatibility tools, current default version: v6.1
+ process_version: function() {
+ if (this.version < 7.0) {
+ this.$form.find('form:first').wrapInner('<group col="4"/>');
+ this.$form.find('page').each(function() {
+ if (!$(this).parents('field').length) {
+ $(this).wrapInner('<group col="4"/>');
+ }
+ });
+ }
+ selector = 'form[version!="7.0"] page,form[version!="7.0"]';
+ },
render_to: function($target) {
var self = this;
this.$target = $target;
// but one day, we will have to get rid of xml2json
var xml = instance.web.json_node_to_xml(this.fvg.arch);
this.$form = $('<div class="oe_form">' + xml + '</div>');
- if (this.fvg.arch.attrs && this.fvg.arch.attrs['layout'] !== 'manual') {
- this.$form.attr('layout', 'auto');
- }
+
+ this.process_version();
this.fields_to_init = [];
this.tags_to_init = [];
var obj = self.tags_registry.get_object(tag_name);
var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
w.replace($elem);
- })
+ });
// TODO: return a deferred
},
- render_element: function(template, layout/* dictionaries */) {
- var dicts = [].slice.call(arguments).slice(2);
- dicts.unshift({ 'layout' : layout });
+ render_element: function(template /* dictionaries */) {
+ var dicts = [].slice.call(arguments).slice(1);
var dict = _.extend.apply(_, dicts);
dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
- var alt_template = template + '.' + layout;
- template = QWeb.has_template(alt_template) ? alt_template : template;
return $(QWeb.render(template, dict));
},
alter_field: function(field) {
}
this.$target.toggleClass('oe_layout_debugging');
},
- process: function($tag, layout) {
+ process: function($tag) {
var self = this;
- layout = $tag.attr('layout') || layout || 'auto';
- $tag.removeAttr('layout');
var tagname = $tag[0].nodeName.toLowerCase();
if (this.tags_registry.contains(tagname)) {
this.tags_to_init.push($tag);
if (fn) {
var args = [].slice.call(arguments);
args[0] = $tag;
- args[1] = layout;
return fn.apply(self, args);
} else {
// generic tag handling, just process children
$tag.children().each(function() {
- self.process($(this), layout);
+ self.process($(this));
});
self.handle_common_properties($tag, $tag);
$tag.removeAttr("modifiers");
return $tag;
}
},
- process_sheet: function($sheet, layout) {
- var $new_sheet = this.render_element('FormRenderingSheet', layout, $sheet.getAttributes());
+ process_sheet: function($sheet) {
+ var $new_sheet = this.render_element('FormRenderingSheet', $sheet.getAttributes());
this.handle_common_properties($new_sheet, $sheet);
- var $dst = (layout === 'auto') ? $new_sheet.find('group:first') : $new_sheet.find('.oe_form_sheet');
- $sheet.children().appendTo($dst);
+ var $dst = $new_sheet.find('.oe_form_sheet');
+ $sheet.contents().appendTo($dst);
$sheet.before($new_sheet).remove();
- this.process($new_sheet, layout);
+ this.process($new_sheet);
},
- process_form: function($form, layout) {
- var $new_form = this.render_element('FormRenderingForm', layout, $form.getAttributes());
+ process_form: function($form) {
+ if ($form.find('> sheet').length === 0) {
+ $form.addClass('oe_form_nosheet');
+ }
+ var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
this.handle_common_properties($new_form, $form);
- var $dst = (layout === 'auto') ? $new_form.find('group:first') : $new_form;
- $form.children().appendTo($dst);
+ $form.contents().appendTo($new_form);
if ($form[0] === this.$form[0]) {
// If root element, replace it
this.$form = $new_form;
} else {
$form.before($new_form).remove();
}
- this.process($new_form, layout);
+ this.process($new_form);
},
+ /*
+ * Used by direct <field> children of a <group> tag only
+ * This method will add the implicit <label...> for every field
+ * in the <group>
+ */
preprocess_field: function($field) {
var self = this;
var name = $field.attr('name'),
"modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
"string": $field.attr('string'),
"help": $field.attr('help'),
+ "class": $field.attr('class'),
});
$label.insertBefore($field);
if (field_colspan > 1) {
}
return $label;
},
- process_field: function($field, layout) {
- var $label = this.preprocess_field($field);
- if ($label)
- this.process($label, layout);
+ process_field: function($field) {
+ if ($field.parent().is('group')) {
+ // No implicit labels for normal fields, only for <group> direct children
+ var $label = this.preprocess_field($field);
+ if ($label) {
+ this.process($label);
+ }
+ }
this.fields_to_init.push($field);
return $field;
},
- process_group: function($group, layout) {
+ process_group: function($group) {
var self = this;
- if ($group.parent().is('.oe_form_group_cell')) {
- $group.parent().addClass('oe_form_group_nested');
- }
$group.children('field').each(function() {
self.preprocess_field($(this));
});
- var $new_group = this.render_element('FormRenderingGroup', layout, $group.getAttributes()),
- $table;
- if ($new_group.is('table')) {
+ var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
+ var $table;
+ if ($new_group.first().is('table.oe_form_group')) {
$table = $new_group;
+ } else if ($new_group.filter('table.oe_form_group').length) {
+ $table = $new_group.filter('table.oe_form_group').first();
} else {
- $table = $new_group.find('table:first');
+ $table = $new_group.find('table.oe_form_group').first();
}
- $table.addClass('oe_form_group');
+
var $tr, $td,
- cols = parseInt($group.attr('col') || 4, 10),
+ cols = parseInt($group.attr('col') || 2, 10),
row_cols = cols;
var children = [];
var tagName = $child[0].tagName.toLowerCase();
var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
var newline = tagName === 'newline';
+
+ // Note FME: those classes are used in layout debug mode
if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
$tr.addClass('oe_form_group_row_incomplete');
if (newline) {
}
$group.before($new_group).remove();
- // Now compute width of cells
$table.find('> tbody > tr').each(function() {
var to_compute = [],
row_cols = cols,
if ($child.attr('orientation') === 'vertical') {
$td.addClass('oe_vertical_separator').attr('width', '1');
$td.empty();
- row_cols--;
+ row_cols-= $td.attr('colspan') || 1;
+ total--;
}
break;
case 'label':
if ($child.attr('for')) {
$td.attr('width', '1%').addClass('oe_form_group_cell_label');
- row_cols--;
+ row_cols-= $td.attr('colspan') || 1;
total--;
}
break;
}
$td.attr('width', width);
$child.removeAttr('width');
- row_cols--;
+ row_cols-= $td.attr('colspan') || 1;
} else {
to_compute.push($td);
}
}
});
- var unit = Math.floor(total / row_cols);
- if (!$(this).is('.oe_form_group_row_incomplete')) {
- _.each(to_compute, function($td, i) {
- var width = parseInt($td.attr('colspan'), 10) * unit;
- $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
- total -= width;
- });
+ if (row_cols) {
+ var unit = Math.floor(total / row_cols);
+ if (!$(this).is('.oe_form_group_row_incomplete')) {
+ _.each(to_compute, function($td, i) {
+ var width = parseInt($td.attr('colspan'), 10) * unit;
+ $td.attr('width', width + '%');
+ total -= width;
+ });
+ }
}
});
_.each(children, function(el) {
this.handle_common_properties($new_group, $group);
return $new_group;
},
- process_notebook: function($notebook, layout) {
+ process_notebook: function($notebook) {
var self = this;
var pages = [];
$notebook.find('> page').each(function() {
var $page = $(this);
var page_attrs = $page.getAttributes();
page_attrs.id = _.uniqueId('notebook_page_');
- pages.push(page_attrs);
- var $new_page = self.render_element('FormRenderingNotebookPage', layout, page_attrs);
- var $dst = (layout === 'auto') ? $new_page.find('group:first') : $new_page;
- $page.children().appendTo($dst);
+ var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
+ $page.contents().appendTo($new_page);
$page.before($new_page).remove();
- self.handle_common_properties($new_page, $page);
+ var ic = self.handle_common_properties($new_page, $page).invisibility_changer;
+ page_attrs.__page = $new_page;
+ page_attrs.__ic = ic;
+ pages.push(page_attrs);
+
+ $new_page.children().each(function() {
+ self.process($(this));
+ });
});
- var $new_notebook = this.render_element('FormRenderingNotebook', layout, { pages : pages });
- $notebook.children().appendTo($new_notebook);
+ var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
+ $notebook.contents().appendTo($new_notebook);
$notebook.before($new_notebook).remove();
- $new_notebook.children().each(function() {
- self.process($(this));
- });
+ self.process($($new_notebook.children()[0]));
+ //tabs and invisibility handling
$new_notebook.tabs();
+ _.each(pages, function(page, i) {
+ if (! page.__ic)
+ return;
+ page.__ic.on("change:effective_invisible", null, function() {
+ var current = $new_notebook.tabs("option", "selected");
+ if (! pages[current].__ic || ! pages[current].__ic.get("effective_invisible"))
+ return;
+ var first_visible = _.find(_.range(pages.length), function(i2) {
+ return (! pages[i2].__ic) || (! pages[i2].__ic.get("effective_invisible"));
+ });
+ if (first_visible !== undefined) {
+ $new_notebook.tabs('select', first_visible);
+ }
+ });
+ });
+
this.handle_common_properties($new_notebook, $notebook);
return $new_notebook;
},
- process_separator: function($separator, layout) {
- var $new_separator = this.render_element('FormRenderingSeparator', layout, $separator.getAttributes());
+ process_separator: function($separator) {
+ var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
$separator.before($new_separator).remove();
this.handle_common_properties($new_separator, $separator);
return $new_separator;
},
- process_label: function($label, layout) {
+ process_label: function($label) {
var name = $label.attr("for"),
field_orm = this.fvg.fields[name];
var dict = {
align = 'center';
}
dict.align = align;
- var $new_label = this.render_element('FormRenderingLabel', layout, dict);
+ var $new_label = this.render_element('FormRenderingLabel', dict);
$label.before($new_label).remove();
this.handle_common_properties($new_label, $label);
if (name) {
handle_common_properties: function($new_element, $node) {
var str_modifiers = $node.attr("modifiers") || "{}"
var modifiers = JSON.parse(str_modifiers);
+ var ic = null;
if (modifiers.invisible !== undefined)
- new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
+ ic = new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
$new_element.addClass($node.attr("class") || "");
$new_element.attr('style', $node.attr('style'));
+ return {invisibility_changer: ic,};
},
});
_.bind(check, this)();
},
start: function() {
- var check_visibility = function() {
- if (this.get("effective_invisible")) {
- this.$element.hide();
- } else {
- this.$element.show();
- }
- };
- this.on("change:effective_invisible", this, check_visibility);
- _.bind(check_visibility, this)();
+ this.on("change:effective_invisible", this, this._check_visibility);
+ this._check_visibility();
+ },
+ _check_visibility: function() {
+ this.$element.toggleClass('oe_form_invisible', this.get("effective_invisible"));
},
};
-instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
+instance.web.form.InvisibilityChanger = instance.web.Class.extend(instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
init: function(parent, field_manager, invisible_domain, $element) {
this.setParent(parent);
instance.web.PropertiesMixin.init.call(this);
this.$element = $element;
this.start();
},
-}));
+});
-instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
+instance.web.form.FormWidget = instance.web.Widget.extend(instance.web.form.InvisibilityChangerMixin, {
/**
* @constructs instance.web.form.FormWidget
* @extends instance.web.Widget
$.fn.tipsy.clear();
this._super.apply(this, arguments);
},
+ /**
+ * Sets up blur/focus forwarding from DOM elements to a widget (`this`)
+ *
+ * @param {jQuery} $e jQuery object of elements to bind focus/blur on
+ */
+ setupFocus: function ($e) {
+ var self = this;
+ $e.on({
+ focus: function () { self.trigger('focused'); },
+ blur: function () { self.trigger('blurred'); }
+ });
+ },
process_modifiers: function() {
var compute_domain = instance.web.form.compute_domain;
var to_set = {};
}
return final_domain;
}
-}));
+});
instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
template: 'WidgetButton',
},
start: function() {
this._super.apply(this, arguments);
- this.$element.click(this.on_click);
+ var $button = this.$element.find('button');
+ $button.click(this.on_click);
if (this.node.attrs.help || instance.connection.debug) {
this.do_attach_tooltip();
}
+ this.setupFocus($button);
},
on_click: function() {
var self = this;
* - changed_value: triggered to inform the view to check on_changes
*
*/
-instance.web.form.FieldMixin = {
+instance.web.form.FieldInterface = {
/**
* Constructor takes 2 arguments:
* - field_manager: Implements FieldManagerMixin
};
/**
- * Abstract class for classes implementing FieldMixin.
+ * Abstract class for classes implementing FieldInterface.
*
* Properties:
* - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
* a 'changed_value' event that inform the view to trigger on_changes.
*
*/
-instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
+instance.web.form.AbstractField = instance.web.form.FormWidget.extend(instance.web.form.FieldInterface, {
/**
* @constructs instance.web.form.AbstractField
* @extends instance.web.form.FormWidget
this.on("change:required", this, this._set_required);
this._set_required();
}
+ this._check_visibility();
+ this._check_css_flags();
},
/**
* Private. Do not use.
return this.get('value');
},
is_valid: function() {
- return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
+ return this.is_syntax_valid() && !(this.get('required') && this.is_false());
},
is_syntax_valid: function() {
return true;
set_input_id: function(id) {
this.id_for_label = id;
},
-}));
+});
/**
* A mixin to apply on any field that has to completely re-render when its readonly state
render_value: function() {},
};
-instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldChar = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
template: 'FieldChar',
+ widget_class: 'oe_form_field_char',
init: function (field_manager, node) {
this._super(field_manager, node);
this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
},
initialize_content: function() {
var self = this;
- this.$element.find('input').change(function() {
- self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
+ var $input = this.$element.find('input');
+ $input.change(function() {
+ self.set({'value': instance.web.parse_value($input.val(), self)});
});
+ this.setupFocus($input);
},
set_value: function(value_) {
this._super(value_);
return true;
},
is_false: function() {
- return this.get('value') === '';
+ return this.get('value') === '' || this._super();
},
focus: function() {
this.delay_focus(this.$element.find('input:first'));
}
-}));
+});
instance.web.form.FieldID = instance.web.form.FieldChar.extend({
template: 'FieldEmail',
initialize_content: function() {
this._super();
- this.$element.find('button').click(this.on_button_clicked);
+ var $button = this.$element.find('button');
+ $button.click(this.on_button_clicked);
+ this.setupFocus($button);
},
render_value: function() {
if (!this.get("effective_readonly")) {
template: 'FieldUrl',
initialize_content: function() {
this._super();
- this.$element.find('button').click(this.on_button_clicked);
+ var $button = this.$element.find('button');
+ $button.click(this.on_button_clicked);
+ this.setupFocus($button);
},
render_value: function() {
if (!this.get("effective_readonly")) {
instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
is_field_number: true,
+ widget_class: 'oe_form_field_float',
init: function (field_manager, node) {
this._super(field_manager, node);
this.set({'value': 0});
if (this.node.attrs.digits) {
- this.digits = py.eval(node.attrs.digits);
+ this.digits = this.node.attrs.digits;
} else {
this.digits = this.field.digits;
}
});
instance.web.DateTimeWidget = instance.web.OldWidget.extend({
- template: "web.datetimepicker",
+ template: "web.datepicker",
jqueryui_object: 'datetimepicker',
type_of_date: "datetime",
init: function(parent) {
this.$input_picker = this.$element.find('input.oe_datepicker_container');
this.$input.change(this.on_change);
this.picker({
+ onClose: this.on_picker_select,
onSelect: this.on_picker_select,
changeMonth: true,
changeYear: true,
showButtonPanel: true
});
this.$element.find('img.oe_datepicker_trigger').click(function() {
- if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
- self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
- self.$input_picker.show();
- self.picker('show');
- self.$input_picker.hide();
+ if (self.get("effective_readonly") || self.picker('widget').is(':visible')) {
+ self.$input.focus();
+ return;
}
+ self.picker('setDate', self.value ? instance.web.auto_str_to_date(self.value) : new Date());
+ self.$input_picker.show();
+ self.picker('show');
+ self.$input_picker.hide();
});
this.set_readonly(false);
this.set({'value': false});
},
on_picker_select: function(text, instance_) {
var date = this.picker('getDate');
- this.$input.val(date ? this.format_client(date) : '').change();
+ this.$input
+ .val(date ? this.format_client(date) : '')
+ .change()
+ .focus();
},
set_value: function(value_) {
this.set({'value': value_});
type_of_date: "date"
});
-instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
- template: "EmptyComponent",
+instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
+ template: "FieldDatetime",
build_widget: function() {
return new instance.web.DateTimeWidget(this);
},
this.set({'value': this.datewidget.get_value()});
}, this));
this.datewidget.appendTo(this.$element);
+ this.setupFocus(this.datewidget.$input);
}
},
set_value: function(value_) {
return true;
},
is_false: function() {
- return this.get('value') === '';
+ return this.get('value') === '' || this._super();
},
focus: function() {
if (this.datewidget && this.datewidget.$input)
this.delay_focus(this.datewidget.$input);
}
-}));
+});
instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
+ template: "FieldDate",
build_widget: function() {
return new instance.web.DateWidget(this);
}
});
-instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldText = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
template: 'FieldText',
initialize_content: function() {
this.$textarea = this.$element.find('textarea');
} else {
this.$textarea.attr('disabled', 'disabled');
}
+ this.setupFocus(this.$textarea);
},
set_value: function(value_) {
this._super.apply(this, arguments);
return true;
},
is_false: function() {
- return this.get('value') === '';
+ return this.get('value') === '' || this._super();
},
focus: function($element) {
this.delay_focus(this.$textarea);
$div.remove();
$input.height(new_height);
},
-}));
+});
instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
template: 'FieldBoolean',
start: function() {
this._super.apply(this, arguments);
this.$checkbox = $("input", this.$element);
+ this.setupFocus(this.$checkbox);
this.$element.click(_.bind(function() {
this.set({'value': this.$checkbox.is(':checked')});
}, this));
// to replace view editor
});
-instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
template: 'FieldSelection',
init: function(field_manager, node) {
var self = this;
// changing the selected value), takes the action as validating the
// row
var ischanging = false;
- this.$element.find('select')
+ var $select = this.$element.find('select')
.change(_.bind(function() {
this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
}, this))
e.stopPropagation();
ischanging = false;
});
+ this.setupFocus($select);
},
set_value: function(value_) {
value_ = value_ === null ? false : value_;
focus: function() {
this.delay_focus(this.$element.find('select:first'));
}
-}));
+});
// jquery autocomplete tweak to allow html
(function() {
}
// create...
values.push({label: _t("<em>Â Â Â Create and Edit...</em>"), action: function() {
- self._search_create_popup("form", undefined, {"default_name": search_val});
+ self._search_create_popup("form", undefined, {});
}});
return values;
);
pop.on_select_elements.add(function(element_ids) {
self.add_id(element_ids[0]);
+ self.focus();
});
},
/**
add_id: function(id) {},
};
-instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
- instance.web.form.CompletionFieldMixin, {
+instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(instance.web.form.CompletionFieldMixin, instance.web.form.ReinitializeFieldMixin, {
template: "FieldMany2One",
init: function(field_manager, node) {
this._super(field_manager, node);
this.$follow_button.click(function() {
if (!self.get('value')) {
+ self.focus();
return;
}
var pop = new instance.web.form.FormOpenPopup(self.view);
pop.on_write_completed.add_last(function() {
self.display_value = {};
self.render_value();
+ self.focus();
});
});
this.$drop_down.click(function() {
if (self.$input.autocomplete("widget").is(":visible")) {
self.$input.autocomplete("close");
+ self.$input.focus();
} else {
if (self.get("value") && ! self.floating) {
self.$input.autocomplete("search", "");
} else {
self.$input.autocomplete("search");
}
- self.$input.focus();
}
});
var tip_def = $.Deferred();
var tip_delay = 200;
var tip_duration = 3000;
var anyoneLoosesFocus = function() {
+ var used = false;
if (self.floating) {
if (self.last_search.length > 0) {
if (self.last_search[0][0] != self.get("value")) {
self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
self.set({value: self.last_search[0][0]});
} else {
+ used = true;
self.render_value();
}
} else {
+ used = true;
self.set({value: false});
+ self.render_value();
}
+ self.floating = false;
}
- if (! self.get("value")) {
+ if (used) {
tip_def.reject();
untip_def.reject();
tip_def = $.Deferred();
e.preventDefault();
},
html: true,
- close: anyoneLoosesFocus,
+ // disabled to solve a bug, but may cause others
+ //close: anyoneLoosesFocus,
minLength: 0,
delay: 0
});
}
isSelecting = false;
});
+ this.setupFocus(this.$input.add(this.$follow_button));
},
render_value: function(no_recurse) {
focus: function () {
this.delay_focus(this.$input);
}
-}));
+});
/*
# Values: (0, 0, { fields }) create
},
start: function() {
this._super.apply(this, arguments);
+ this.$element.addClass('oe_form_field_one2many');
var self = this;
this.dataset.o2m = this;
this.dataset.parent_view = this.view;
this.dataset.child_name = this.name;
- //this.dataset.child_name =
this.dataset.on_change.add_last(function() {
self.trigger_on_change();
});
modes = !!modes ? modes.split(",") : ["tree"];
var views = [];
_.each(modes, function(mode) {
+ if (! _.include(["list", "tree", "graph", "kanban"], mode)) {
+ try {
+ throw new Error(_.str.sprintf("View type '%s' is not supported in One2Many.", mode));
+ } catch(e) {
+ instance.webclient.crashmanager.on_javascript_exception(e)
+ }
+ }
var view = {
view_id: false,
view_type: mode == "tree" ? "list" : mode,
}
if(view.view_type === "list") {
view.options.selectable = self.multi_selection;
+ view.options.sortable = false;
if (self.get("effective_readonly")) {
view.options.addable = null;
view.options.deletable = null;
+ view.options.reorderable = false;
}
} else if (view.view_type === "form") {
if (self.get("effective_readonly")) {
this.views = views;
this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
+ this.viewmanager.$element.addClass("oe_view_manager_one2many");
this.viewmanager.o2m = self;
var once = $.Deferred().then(function() {
self.init_form_last_update.resolve();
if (!this.viewmanager.views[this.viewmanager.active_view])
return true;
var view = this.viewmanager.views[this.viewmanager.active_view].controller;
- if (this.viewmanager.active_view === "form") {
- for (var f in view.fields) {
- f = view.fields[f];
- if (!f.is_valid()) {
- return false;
- }
- }
+ switch (this.viewmanager.active_view) {
+ case 'form':
+ return _(view.fields).chain()
+ .invoke('is_valid')
+ .all(_.identity)
+ .value();
+ break;
+ case 'list':
+ return view.is_valid();
}
return true;
},
instance.web.form.One2ManyListView = instance.web.ListView.extend({
_template: 'One2Many.listview',
+ init: function (parent, dataset, view_id, options) {
+ this._super(parent, dataset, view_id, _.extend(options || {}, {
+ ListType: instance.web.form.One2ManyList
+ }));
+ },
+ is_valid: function () {
+ var form;
+ // A list not being edited is always valid
+ if (!(form = this.first_edition_form())) {
+ return true;
+ }
+ // If the form has not been modified, the view can only be valid
+ // NB: is_dirty will also be set on defaults/onchanges/whatever?
+ // oe_form_dirty seems to only be set on actual user actions
+ if (!form.$element.is('.oe_form_dirty')) {
+ return true;
+ }
+
+ // Otherwise validate internal form
+ return _(form.fields).chain()
+ .invoke(function () {
+ this._check_css_flag();
+ return this.is_valid();
+ })
+ .all(_.identity)
+ .value();
+ },
+ first_edition_form: function () {
+ var get_form = function (group_or_list) {
+ if (group_or_list.edition) {
+ return group_or_list.edition_form;
+ }
+ return _(group_or_list.children).chain()
+ .map(get_form)
+ .compact()
+ .first()
+ .value();
+ };
+ return get_form(this.groups);
+ },
do_add_record: function () {
if (this.options.editable) {
this._super.apply(this, arguments);
});
},
do_button_action: function (name, id, callback) {
+ var _super = _.bind(this._super, this);
+
+ this.o2m.view.do_save().then(function () {
+ _super(name, id, callback);
+ });
+ }
+});
+instance.web.form.One2ManyList = instance.web.ListView.List.extend({
+ KEY_RETURN: 13,
+ // blurring caused by hitting the [Return] key, should skip the
+ // autosave-on-blur and let the handler for [Return] do its thing
+ __return_blur: false,
+ render_row_as_form: function () {
var self = this;
- var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
- return this._super(name, id, _.bind(def.resolve, def));
+ return this._super.apply(this, arguments).then(function () {
+ // Replace the "Save Row" button with "Cancel Edition"
+ self.edition_form.$element
+ .undelegate('button.oe-edit-row-save', 'click')
+ .delegate('button.oe-edit-row-save', 'click', function () {
+ self.cancel_pending_edition();
+ });
+
+ // Overload execute_action on the edition form to perform a simple
+ // reload_record after the action is done, rather than fully
+ // reload the parent view (or something)
+ var _execute_action = self.edition_form.do_execute_action;
+ self.edition_form.do_execute_action = function (action, dataset, record_id, _callback) {
+ return _execute_action.call(this, action, dataset, record_id, function () {
+ self.view.reload_record(
+ self.view.records.get(record_id));
+ });
+ };
+
+ self.edition_form.on('blurred', null, function () {
+ if (self.__return_blur) {
+ delete self.__return_blur;
+ return;
+ }
+ if (!self.edition_form.widget_is_stopped) {
+ self.view.ensure_saved();
+ }
+ });
+ });
+ },
+ on_row_keyup: function (e) {
+ if (e.which === this.KEY_RETURN) {
+ this.__return_blur = true;
+ }
+ this._super(e);
}
});
});
}
-instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
- instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(instance.web.form.CompletionFieldMixin, instance.web.form.ReinitializeFieldMixin, {
template: "FieldMany2ManyTags",
init: function() {
this._super.apply(this, arguments);
if (this.get("effective_readonly"))
return;
var self = this;
- self. $text = $("textarea", this.$element);
+ self.$text = $("textarea", this.$element);
self.$text.textext({
plugins : 'tags arrow autocomplete',
autocomplete: {
return _.extend(el, {index:i});
})});
});
- }).bind('tagClick', function(e, tag, value, callback) {
- var pop = new instance.web.form.FormOpenPopup(self.view);
- pop.show_element(
- self.field.relation,
- value.id,
- self.build_context(),
- {
- title: _t("Open: ") + (self.string || self.name)
- }
- );
- pop.on_write_completed.add_last(function() {
- self.render_value();
- });
}).bind('hideDropdown', function() {
self._drop_shown = false;
}).bind('showDropdown', function() {
self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
} else {
self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
- $(".oe_form_field_many2manytags_box", self.$element).click(function() {
- var index = Number($(this).data("index"));
- self.do_action({
- type: 'ir.actions.act_window',
- res_model: self.field.relation,
- res_id: self.get("value")[index],
- context: self.build_context(),
- views: [[false, 'form']],
- target: 'current'
- });
- });
}
};
if (! self.get('values') || self.get('values').length > 0) {
add_id: function(id) {
this.set({'value': _.uniq(this.get('value').concat([id]))});
},
-}));
+});
/*
* TODO niv: clean those deferred stuff, it could be better
},
start: function() {
this._super.apply(this, arguments);
+ this.$element.addClass('oe_form_field_many2many');
var self = this;
this.dataset.on_unlink.add_last(function(ids) {
self.dataset_changed();
});
-
+
this.is_setted.then(function() {
self.load_view();
});
});
});
});
- })
+ });
},
set_value: function(value_) {
value_ = value_ || [];
self.reload_content();
this.is_setted.resolve();
},
+ get_value: function() {
+ return [commands.replace_with(this.get('value'))];
+ },
+
+ is_false: function () {
+ return _(this.dataset.ids).isEmpty();
+ },
load_view: function() {
var self = this;
this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
'addable': self.get("effective_readonly") ? null : _t("Add"),
'deletable': self.get("effective_readonly") ? false : true,
'selectable': self.multi_selection,
+ 'sortable': false,
+ 'reorderable': false,
});
var embedded = (this.field.views || {}).tree;
if (embedded) {
});
},
dataset_changed: function() {
- this.set({'value': [commands.replace_with(this.dataset.ids)]});
+ this.set({'value': this.dataset.ids});
},
});
}
});
-instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
+instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(instance.web.form.CompletionFieldMixin, {
disable_utility_classes: true,
init: function(field_manager, node) {
this._super(field_manager, node);
add_id: function(id) {
this.quick_create.add_id(id);
},
-}));
+});
function m2m_kanban_lazy_init() {
if (instance.web.form.Many2ManyKanbanView)
self.view_list = new instance.web.form.SelectCreateListView(self,
self.dataset, false,
_.extend({'deletable': false,
- 'selectable': !self.options.disable_multiple_selection
+ 'selectable': !self.options.disable_multiple_selection,
+ 'read_only': true,
}, self.options.list_view_options || {}));
self.view_list.popup = self;
self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
}
});
-instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldReference = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
template: 'FieldReference',
init: function(field_manager, node) {
this._super(field_manager, node);
}
},
initialize_content: function() {
+ var self = this;
this.selection = new instance.web.form.FieldSelection(this, { attrs: {
name: 'selection'
}});
this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
this.selection.renderElement();
this.selection.start();
+ this.selection
+ .on('focused', null, function () {self.trigger('focused')})
+ .on('blurred', null, function () {self.trigger('blurred')});
this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
name: 'm2o'
this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
this.m2o.renderElement();
this.m2o.start();
+ this.m2o
+ .on('focused', null, function () {self.trigger('focused')})
+ .on('blurred', null, function () {self.trigger('blurred')});
},
is_false: function() {
return typeof(this.get_value()) !== 'string';
}
throw Exception("Should not happen");
},
-}));
+});
-instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
+instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(instance.web.form.ReinitializeFieldMixin, {
init: function(field_manager, node) {
+ var self = this;
this._super(field_manager, node);
- this.iframe = this.element_id + '_iframe';
this.binary_value = false;
+ this.fileupload_id = _.uniqueId('oe_fileupload');
+ $(window).on(this.fileupload_id, function() {
+ var args = [].slice.call(arguments).slice(1);
+ self.on_file_uploaded.apply(self, args);
+ });
+ },
+ stop: function() {
+ $(window).off(this.fileupload_id);
+ this._super.apply(this, arguments);
},
initialize_content: function() {
this.$element.find('input.oe-binary-file').change(this.on_file_change);
- this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
+ this.$element.find('button.oe_binary_file_save').click(this.on_save_as);
this.$element.find('.oe-binary-file-clear').click(this.on_clear);
},
human_filesize : function(size) {
// TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
// http://www.html5rocks.com/tutorials/file/dndfiles/
// http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
- window[this.iframe] = this.on_file_uploaded;
- if ($(e.target).val() != '') {
+
+ if ($(e.target).val() !== '') {
this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
this.$element.find('form.oe-binary-form').submit();
this.$element.find('.oe-binary-progress').show();
}
},
on_file_uploaded: function(size, name, content_type, file_base64) {
- delete(window[this.iframe]);
if (size === false) {
this.do_warn("File Upload", "There was a problem while uploading your file");
// TODO: use openerp web crashmanager
console.warn("Error while uploading file : ", name);
} else {
+ this.filename = name;
this.on_file_uploaded_and_valid.apply(this, arguments);
}
this.$element.find('.oe-binary-progress').hide();
},
on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
},
- on_save_as: function() {
- $.blockUI();
- this.session.get_file({
- url: '/web/binary/saveas_ajax',
- data: {data: JSON.stringify({
- model: this.view.dataset.model,
- id: (this.view.datarecord.id || ''),
- field: this.name,
- filename_field: (this.node.attrs.filename || ''),
- context: this.view.dataset.get_context()
- })},
- complete: $.unblockUI,
- error: instance.webclient.crashmanager.on_rpc_error
- });
+ on_save_as: function(ev) {
+ var value = this.get('value');
+ if (!value) {
+ this.do_warn(_t("Save As..."), _t("The field is empty, there's nothing to save !"));
+ ev.stopPropagation();
+ } else if (this._dirty_flag) {
+ var link = this.$('.oe_binary_file_save_data')[0];
+ link.download = this.filename || "download.bin"; // Works on only on Google Chrome
+ //link.target = '_blank';
+ link.href = "data:application/octet-stream;base64," + value;
+ } else {
+ $.blockUI();
+ this.session.get_file({
+ url: '/web/binary/saveas_ajax',
+ data: {data: JSON.stringify({
+ model: this.view.dataset.model,
+ id: (this.view.datarecord.id || ''),
+ field: this.name,
+ filename_field: (this.node.attrs.filename || ''),
+ context: this.view.dataset.get_context()
+ })},
+ complete: $.unblockUI,
+ error: instance.webclient.crashmanager.on_rpc_error
+ });
+ ev.stopPropagation();
+ return false;
+ }
+ },
+ set_filename: function(value) {
+ var filename = this.node.attrs.filename;
+ if (this.view.fields[filename]) {
+ this.view.fields[filename].set_value(value);
+ this.view.fields[filename].on_ui_change();
+ }
},
on_clear: function() {
if (this.get('value') !== false) {
}
return false;
}
-}));
+});
instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
template: 'FieldBinaryFile',
instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
template: 'FieldBinaryImage',
- initialize_content: function() {
- this._super();
- this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
- if (!this.get("effective_readonly"))
- this.$element.find('.oe-binary').show();
- else
- this.$element.find('.oe-binary').hide();
- },
set_value: function(value_) {
this._super.apply(this, arguments);
this.render_value();
} else {
url = "/web/static/src/img/placeholder.png";
}
- var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
- this.$placeholder.html(rendered);
+ var img = QWeb.render("FieldBinaryImage-img", { widget: this, url: url });
+ this.$element.find('> img').remove();
+ this.$element.prepend(img);
},
on_file_change: function() {
this.render_value();
});
instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
- template: "EmptyComponent",
+ tagName: "span",
start: function() {
this._super();
this.selected_value = null;
/**
* Registry of form fields, called by :js:`instance.web.FormView`.
*
- * All referenced classes must implement FieldMixin. Those represent the classes whose instances
+ * All referenced classes must implement FieldInterface. Those represent the classes whose instances
* will substitute to the <field> tags as defined in OpenERP's views.
*/
instance.web.form.widgets = new instance.web.Registry({