1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
9 instance.web.ActionManager = instance.web.Widget.extend({
10 init: function(parent) {
12 this.inner_action = null;
13 this.inner_viewmanager = null;
15 this.dialog_viewmanager = null;
16 this.client_widget = null;
18 dialog_stop: function () {
20 this.dialog_viewmanager.destroy();
21 this.dialog_viewmanager = null;
22 this.dialog.destroy();
26 content_stop: function () {
27 if (this.inner_viewmanager) {
28 this.inner_viewmanager.destroy();
29 this.inner_viewmanager = null;
31 if (this.client_widget) {
32 this.client_widget.destroy();
33 this.client_widget = null;
36 do_push_state: function(state) {
37 if (this.getParent() && this.getParent().do_push_state) {
38 if (this.inner_action) {
39 state['model'] = this.inner_action.res_model;
40 if (this.inner_action.id) {
41 state['action_id'] = this.inner_action.id;
44 this.getParent().do_push_state(state);
47 do_load_state: function(state, warm) {
50 if (state.action_id) {
51 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
54 action_loaded = this.do_action(state.action_id);
55 instance.webclient.menu.has_been_loaded.then(function() {
56 instance.webclient.menu.open_action(state.action_id);
59 } else if (state.model && state.id) {
60 // TODO handle context & domain ?
63 res_model: state.model,
65 type: 'ir.actions.act_window',
66 views: [[false, 'form']]
68 action_loaded = this.do_action(action);
69 } else if (state.sa) {
70 // load session action
73 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
75 return self.do_action(action);
78 } else if (state.client_action) {
80 var action = state.client_action;
81 if(_.isString(action)) {
87 this.ir_actions_client(action);
90 $.when(action_loaded || null).then(function() {
91 if (self.inner_viewmanager) {
92 self.inner_viewmanager.do_load_state(state, warm);
96 do_action: function(action, on_close) {
97 if (_.isNumber(action)) {
99 return self.rpc("/web/action/load", { action_id: action }, function(result) {
100 self.do_action(result.result, on_close);
104 console.error("No type for action", action);
107 var type = action.type.replace(/\./g,'_');
108 var popup = action.target === 'new';
109 var inline = action.target === 'inline';
110 action.flags = _.extend({
111 views_switcher : !popup && !inline,
112 search_view : !popup && !inline,
113 action_buttons : !popup && !inline,
114 sidebar : !popup && !inline,
115 pager : !popup && !inline,
116 display_title : !popup
117 }, action.flags || {});
118 if (!(type in this)) {
119 console.error("Action manager can't handle action of type " + action.type, action);
122 return this[type](action, on_close);
124 null_action: function() {
128 ir_actions_act_window: function (action, on_close) {
130 if (_(['base.module.upgrade', 'base.setup.installer'])
131 .contains(action.res_model)) {
132 var old_close = on_close;
133 on_close = function () {
134 instance.webclient.do_reload().then(old_close);
137 if (action.target === 'new') {
138 if (this.dialog == null) {
139 this.dialog = new instance.web.Dialog(this, { width: '80%' });
141 this.dialog.on_close.add(on_close);
143 this.dialog_viewmanager.destroy();
145 this.dialog.dialog_title = action.name;
146 this.dialog_viewmanager = new instance.web.ViewManagerAction(this, action);
147 this.dialog_viewmanager.appendTo(this.dialog.$element);
153 return this.getParent().do_action(action, function () {
154 instance.webclient.menu.open_menu(action.menu_id);
157 this.inner_action = action;
158 this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
159 this.inner_viewmanager.appendTo(this.$element);
160 this.inner_viewmanager.$element.addClass("oe_view_manager_global");
163 ir_actions_act_window_close: function (action, on_closed) {
164 if (!this.dialog && on_closed) {
169 ir_actions_server: function (action, on_closed) {
171 this.rpc('/web/action/run', {
172 action_id: action.id,
173 context: action.context || {}
174 }).then(function (action) {
175 self.do_action(action, on_closed)
178 ir_actions_client: function (action) {
181 var ClientWidget = instance.web.client_actions.get_object(action.tag);
182 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
184 ir_actions_report_xml: function(action, on_closed) {
187 self.rpc("/web/session/eval_domain_and_context", {
188 contexts: [action.context],
190 }).then(function(res) {
191 action = _.clone(action);
192 action.context = res.context;
193 self.session.get_file({
195 data: {action: JSON.stringify(action)},
196 complete: $.unblockUI,
198 if (!self.dialog && on_closed) {
203 error: instance.webclient.crashmanager.on_rpc_error
207 ir_actions_act_url: function (action) {
208 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
210 ir_ui_menu: function (action) {
211 this.getParent().do_action(action);
215 instance.web.ViewManager = instance.web.Widget.extend({
216 template: "ViewManager",
217 init: function(parent, dataset, views, flags) {
219 this.model = dataset ? dataset.model : undefined;
220 this.dataset = dataset;
221 this.searchview = null;
222 this.active_view = null;
223 this.views_src = _.map(views, function(x) {
224 if (x instanceof Array) {
225 var View = instance.web.views.get_object(x[1], true);
229 label: View ? View.prototype.display_name : (void 'nope')
236 this.flags = flags || {};
237 this.registry = instance.web.views;
238 this.views_history = [];
241 * @returns {jQuery.Deferred} initial view loading promise
246 this.$element.find('.oe_view_manager_switch a').click(function() {
247 self.on_mode_switch($(this).data('view-type'));
250 _.each(this.views_src, function(view) {
251 self.views[view.view_type] = $.extend({}, view, {
252 deferred : $.Deferred(),
255 $buttons : self.$element.find('.oe_view_manager_buttons'),
256 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
257 $pager : self.$element.find('.oe_view_manager_pager'),
258 action : self.action,
259 action_views_ids : views_ids
260 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
262 views_ids[view.view_type] = view.view_id;
264 if (this.flags.views_switcher === false) {
265 this.$element.find('.oe_view_manager_switch').hide();
267 // If no default view defined, switch to the first one in sequence
268 var default_view = this.flags.default_view || this.views_src[0].view_type;
269 return this.on_mode_switch(default_view);
272 * Asks the view manager to switch visualization mode.
274 * @param {String} view_type type of view to display
275 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
276 * @returns {jQuery.Deferred} new view loading promise
278 on_mode_switch: function(view_type, no_store, view_options) {
280 var view = this.views[view_type];
283 return $.Deferred().reject();
286 this.views_history.push(view_type);
288 this.active_view = view_type;
290 if (!view.controller) {
291 // Lazy loading of views
292 var controllerclass = this.registry.get_object(view_type);
293 var options = _.clone(view.options);
294 if (view_type === "form" && this.action) {
295 switch (this.action.target) {
298 options.initial_mode = 'edit';
302 var controller = new controllerclass(this, this.dataset, view.view_id, options);
303 if (view.embedded_view) {
304 controller.set_embedded_view(view.embedded_view);
306 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
307 controller.do_prev_view.add_last(this.on_prev_view);
308 var container = this.$element.find(".oe_view_manager_view_" + view_type);
309 view_promise = controller.appendTo(container);
310 this.views[view_type].controller = controller;
311 this.views[view_type].deferred.resolve(view_type);
312 $.when(view_promise).then(function() {
313 self.on_controller_inited(view_type, controller);
315 && self.flags.auto_search
316 && view.controller.searchable !== false) {
317 self.searchview.ready.then(self.searchview.do_search);
320 } else if (this.searchview
321 && self.flags.auto_search
322 && view.controller.searchable !== false) {
323 this.searchview.ready.then(this.searchview.do_search);
326 if (this.searchview) {
327 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
331 .find('.oe_view_manager_switch a').parent().removeClass('active');
333 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
334 .parent().addClass('active');
336 $.when(view_promise).then(function () {
337 _.each(_.keys(self.views), function(view_name) {
338 var controller = self.views[view_name].controller;
340 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
341 if (view_name === view_type) {
343 controller.do_show(view_options || {});
346 controller.do_hide();
351 self.$element.find('.oe_view_title_text:first').text(
352 self.display_title());
357 * Method used internally when a view asks to switch view. This method is meant
358 * to be extended by child classes to change the default behavior, which simply
359 * consist to switch to the asked view.
361 switch_view: function(view_type, no_store, options) {
362 return this.on_mode_switch(view_type, no_store, options);
365 * Returns to the view preceding the caller view in this manager's
366 * navigation history (the navigation history is appended to via
369 * @param {Object} [options]
370 * @param {Boolean} [options.created=false] resource was created
371 * @param {String} [options.default=null] view to switch to if no previous view
372 * @returns {$.Deferred} switching end signal
374 on_prev_view: function (options) {
375 options = options || {};
376 var current_view = this.views_history.pop();
377 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
378 if (options.created && current_view === 'form' && previous_view === 'list') {
379 // APR special case: "If creation mode from list (and only from a list),
380 // after saving, go to page view (don't come back in list)"
381 return this.on_mode_switch('form');
382 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
383 // APR special case: "If creation from dashboard, we have no previous view
384 return this.on_mode_switch('form');
386 return this.on_mode_switch(previous_view, true);
389 * Sets up the current viewmanager's search view.
391 * @param {Number|false} view_id the view to use or false for a default one
392 * @returns {jQuery.Deferred} search view startup deferred
394 setup_search_view: function(view_id, search_defaults) {
396 if (this.searchview) {
397 this.searchview.destroy();
399 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
401 this.searchview.on_search.add(this.do_searchview_search);
402 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
404 do_searchview_search: function(domains, contexts, groupbys) {
406 controller = this.views[this.active_view].controller,
407 action_context = this.action.context || {};
408 this.rpc('/web/session/eval_domain_and_context', {
409 domains: [this.action.domain || []].concat(domains || []),
410 contexts: [action_context].concat(contexts || []),
411 group_by_seq: groupbys || []
412 }, function (results) {
413 self.dataset._model = new instance.web.Model(
414 self.dataset.model, results.context, results.domain);
415 var groupby = results.group_by.length
417 : action_context.group_by;
418 if (_.isString(groupby)) {
421 controller.do_search(results.domain, results.context, groupby || []);
425 * Event launched when a controller has been inited.
427 * @param {String} view_type type of view
428 * @param {String} view the inited controller
430 on_controller_inited: function(view_type, view) {
433 * Called when one of the view want to execute an action
435 on_action: function(action) {
437 on_create: function() {
439 on_remove: function() {
441 on_edit: function() {
444 * Called by children view after executing an action
446 on_action_executed: function () {
448 display_title: function () {
449 var view = this.views[this.active_view];
452 return view.controller.fields_view.arch.attrs.string;
458 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
459 template:"ViewManagerAction",
461 * @constructs instance.web.ViewManagerAction
462 * @extends instance.web.ViewManager
464 * @param {instance.web.ActionManager} parent parent object/widget
465 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
467 init: function(parent, action) {
468 // dataset initialization will take the session from ``this``, so if we
469 // do not have it yet (and we don't, because we've not called our own
470 // ``_super()``) rpc requests will blow up.
471 var flags = action.flags || {};
472 if (!('auto_search' in flags)) {
473 flags.auto_search = action.auto_search !== false;
475 if (action.res_model == 'board.board' && action.view_mode === 'form') {
476 // Special case for Dashboards
478 views_switcher : false,
479 display_title : false,
483 action_buttons : false
486 this._super(parent, null, action.views, flags);
487 this.session = parent.session;
488 this.action = action;
489 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
491 dataset.ids.push(action.res_id);
494 this.dataset = dataset;
496 // setup storage for session-wise menu hiding
497 if (this.session.hidden_menutips) {
500 this.session.hidden_menutips = {}
503 * Initializes the ViewManagerAction: sets up the searchview (if the
504 * searchview is enabled in the manager's action flags), calls into the
505 * parent to initialize the primary view and (if the VMA has a searchview)
506 * launches an initial search after both views are done rendering.
511 search_defaults = {};
512 _.each(this.action.context, function (value, key) {
513 var match = /^search_default_(.*)$/.exec(key);
515 search_defaults[match[1]] = value;
519 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
521 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
523 var main_view_loaded = this._super();
525 var manager_ready = $.when(searchview_loaded, main_view_loaded);
527 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
529 if (this.action.help && !this.flags.low_profile) {
530 var Users = new instance.web.DataSet(self, 'res.users'),
531 $tips = this.$element.find('.oe_view_manager_menu_tips');
532 $tips.delegate('blockquote button', 'click', function() {
534 //noinspection FallthroughInSwitchStatementJS
535 switch ($this.attr('name')) {
537 Users.write(self.session.uid, {menu_tips:false});
539 $this.closest('blockquote').hide();
540 self.session.hidden_menutips[self.action.id] = true;
543 if (!(self.action.id in self.session.hidden_menutips)) {
544 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
546 if (!(user && user.id === self.session.uid)) {
549 $tips.find('blockquote').toggle(user.menu_tips);
554 return manager_ready;
556 on_debug_changed: function (evt) {
558 $sel = $(evt.currentTarget),
559 $option = $sel.find('option:selected'),
561 current_view = this.views[this.active_view].controller;
564 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
565 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
568 var ids = current_view.get_selected_ids();
569 if (ids.length === 1) {
570 this.dataset.call('perm_read', [ids]).then(function(result) {
571 var dialog = new instance.web.Dialog(this, {
572 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
574 }, QWeb.render('ViewManagerDebugViewLog', {
576 format : instance.web.format_value
581 case 'toggle_layout_outline':
582 current_view.rendering_engine.toggle_layout_debugging();
585 this.dataset.call_and_eval(
586 'fields_get', [false, {}], null, 1).then(function (fields) {
587 var $root = $('<dl>');
588 _(fields).each(function (attributes, name) {
589 $root.append($('<dt>').append($('<h4>').text(name)));
590 var $attrs = $('<dl>').appendTo(
591 $('<dd>').appendTo($root));
592 _(attributes).each(function (def, name) {
593 if (def instanceof Object) {
594 def = JSON.stringify(def);
597 .append($('<dt>').text(name))
598 .append($('<dd style="white-space: pre-wrap;">').text(def));
601 new instance.web.Dialog(self, {
602 title: _.str.sprintf(_t("Model %s fields"),
604 width: '95%'}, $root).open();
608 if (current_view.fields_view && current_view.fields_view.arch) {
609 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
612 this.do_warn(_t("Manage Views"),
613 _t("Could not find current view declaration"));
616 case 'edit_workflow':
617 return this.do_action({
618 res_model : 'workflow',
619 domain : [['osv', '=', this.dataset.model]],
620 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
621 type : 'ir.actions.act_window',
627 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
629 case 'manage_filters':
631 res_model: 'ir.filters',
632 views: [[false, 'list'], [false, 'form']],
633 type: 'ir.actions.act_window',
635 search_default_my_filters: true,
636 search_default_model_id: this.dataset.model
642 console.log("No debug handler for ", val);
645 evt.currentTarget.selectedIndex = 0;
647 do_edit_resource: function(model, id, action) {
648 var action = _.extend({
651 type : 'ir.actions.act_window',
654 views : [[false, 'form']],
657 action_buttons : true,
659 resize_textareas : true
663 this.do_action(action);
665 on_mode_switch: function (view_type, no_store, options) {
668 return $.when(this._super.apply(this, arguments)).then(function () {
669 var controller = self.views[self.active_view].controller,
670 fvg = controller.fields_view,
671 view_id = (fvg && fvg.view_id) || '--';
672 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
676 if (!self.action.name && fvg) {
677 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
682 do_push_state: function(state) {
683 if (this.getParent() && this.getParent().do_push_state) {
684 state["view_type"] = this.active_view;
685 this.getParent().do_push_state(state);
688 do_load_state: function(state, warm) {
691 if (state.view_type && state.view_type !== this.active_view) {
693 this.views[this.active_view].deferred.pipe(function() {
694 return self.on_mode_switch(state.view_type, true);
699 $.when(defs).then(function() {
700 self.views[self.active_view].controller.do_load_state(state, warm);
703 display_title: function () {
704 return this.action.name;
708 instance.web.Sidebar = instance.web.Widget.extend({
709 init: function(parent) {
712 var view = this.getParent();
714 { 'name' : 'print', 'label' : _t('Print'), },
715 { 'name' : 'files', 'label' : _t('Attachment'), },
716 { 'name' : 'other', 'label' : _t('More'), }
723 if (this.session.uid === 1) {
724 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
725 this.items.other.push(item);
727 this.fileupload_id = _.uniqueId('oe_fileupload');
728 $(window).on(this.fileupload_id, function() {
729 var args = [].slice.call(arguments).slice(1);
730 if (args[0] && args[0].error) {
731 alert(args[0].error);
733 self.do_attachement_update(self.dataset, self.model_id);
742 this.$element.on('click','.oe_cropdown_menu li a', function(event) {
743 var section = $(this).data('section');
744 var index = $(this).data('index');
745 var item = self.items[section][index];
747 item.callback.apply(self, [item]);
748 } else if (item.action) {
749 self.on_item_action_clicked(item);
750 } else if (item.url) {
753 event.preventDefault();
758 self.$element.html(QWeb.render('Sidebar', {widget: self}));
760 // Hides Sidebar sections when item list is empty
761 this.$('.oe_form_dropdown_section').each(function() {
762 $(this).toggle(!!$(this).find('li').length);
766 * For each item added to the section:
769 * will be used as the item's name in the sidebar, can be html
772 * descriptor for the action which will be executed, ``action`` and
773 * ``callback`` should be exclusive
776 * function to call when the item is clicked in the sidebar, called
777 * with the item descriptor as its first argument (so information
778 * can be stored as additional keys on the object passed to
781 * ``classname`` (optional)
782 * ``@class`` set on the sidebar serialization of the item
784 * ``title`` (optional)
785 * will be set as the item's ``@title`` (tooltip)
787 * @param {String} section_code
788 * @param {Array<{label, action | callback[, classname][, title]}>} items
790 add_items: function(section_code, items) {
793 this.items[section_code].push.apply(this.items[section_code],items);
797 add_toolbar: function(toolbar) {
799 _.each(['print','action','relate'], function(type) {
800 var items = toolbar[type];
802 for (var i = 0; i < items.length; i++) {
804 label: items[i]['name'],
806 classname: 'oe_sidebar_' + type
809 self.add_items(type=='print' ? 'print' : 'other', items);
813 on_item_action_clicked: function(item) {
815 self.getParent().sidebar_context().then(function (context) {
816 var ids = self.getParent().get_selected_ids();
817 if (ids.length == 0) {
818 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
821 var additional_context = _.extend({
824 active_model: self.getParent().dataset.model
826 self.rpc("/web/action/load", {
827 action_id: item.action.id,
828 context: additional_context
829 }, function(result) {
830 result.result.context = _.extend(result.result.context || {},
832 result.result.flags = result.result.flags || {};
833 result.result.flags.new_window = true;
834 self.do_action(result.result, function () {
836 self.getParent().reload();
841 do_attachement_update: function(dataset, model_id) {
842 this.dataset = dataset;
843 this.model_id = model_id;
845 this.on_attachments_loaded([]);
847 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
848 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
849 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
852 on_attachments_loaded: function(attachments) {
855 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
856 _.each(attachments,function(a) {
858 if(a.type === "binary") {
859 a.url = prefix + a.id + '&t=' + (new Date().getTime());
862 self.items['files'] = attachments;
864 this.$('.oe_sidebar_add_attachment .oe-binary-file').change(this.on_attachment_changed);
865 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
867 on_attachment_changed: function(e) {
868 var $e = $(e.target);
869 if ($e.val() !== '') {
870 this.$element.find('form.oe-binary-form').submit();
871 $e.parent().find('input[type=file]').prop('disabled', true);
872 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
873 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
877 on_attachment_delete: function(e) {
882 var $e = $(e.currentTarget);
883 if (confirm(_t("Do you really want to delete this attachment ?"))) {
884 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
885 self.do_attachement_update(self.dataset, self.model_id);
891 instance.web.TranslateDialog = instance.web.Dialog.extend({
892 dialog_title: {toString: function () { return _t("Translations"); }},
893 init: function(view) {
894 // TODO fme: should add the language to fields_view_get because between the fields view get
895 // and the moment the user opens the translation dialog, the user language could have been changed
896 this.view_language = view.session.user_context.lang;
897 this['on_button' + _t("Save")] = this.on_button_Save;
898 this['on_button' + _t("Close")] = this.on_button_Close;
904 this.view_type = view.fields_view.type || '';
905 this.$fields_form = null;
906 this.$view_form = null;
907 this.$sidebar_form = null;
908 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
909 this.languages = null;
910 this.languages_loaded = $.Deferred();
911 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
912 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
917 $.when(this.languages_loaded).then(function() {
918 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
919 self.$fields_form = self.$element.find('.oe_translation_form');
920 self.$fields_form.find('.oe_trad_field').change(function() {
921 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
926 on_languages_loaded: function(langs) {
927 this.languages = langs;
928 this.languages_loaded.resolve();
930 do_load_fields_values: function(callback) {
933 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
934 _.each(self.languages, function(lg) {
935 var deff = $.Deferred();
937 var callback = function(values) {
938 _.each(self.translatable_fields_keys, function(f) {
939 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
943 if (lg.code === self.view_language) {
945 _.each(self.translatable_fields_keys, function(field) {
946 values[field] = self.view.fields[field].get_value();
950 self.rpc('/web/dataset/get', {
951 model: self.view.dataset.model,
952 ids: [self.view.datarecord.id],
953 fields: self.translatable_fields_keys,
954 context: self.view.dataset.get_context({
959 $.when.apply(null, deffered).then(callback);
961 open: function(field) {
964 $.when(this.languages_loaded).then(function() {
965 if (self.view.translatable_fields && self.view.translatable_fields.length) {
966 self.do_load_fields_values(function() {
969 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
970 self.$element.scrollTo($field_input);
971 $field_input.focus();
979 on_button_Save: function() {
982 trads_mutex = new $.Mutex();
983 self.$fields_form.find('.oe_trad_field.touched').each(function() {
984 var field = $(this).attr('name').split('-');
985 if (!trads[field[0]]) {
986 trads[field[0]] = {};
988 trads[field[0]][field[1]] = $(this).val();
990 _.each(trads, function(data, code) {
991 if (code === self.view_language) {
992 _.each(data, function(value, field) {
993 self.view.fields[field].set_value(value);
996 trads_mutex.exec(function() {
997 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1002 on_button_Close: function() {
1007 instance.web.View = instance.web.Widget.extend({
1008 template: "EmptyComponent",
1009 // name displayed in view switchers
1012 * Define a view type for each view to allow automatic call to fields_view_get.
1014 view_type: undefined,
1015 init: function(parent, dataset, view_id, options) {
1016 this._super(parent);
1017 this.dataset = dataset;
1018 this.view_id = view_id;
1019 this.set_default_options(options);
1022 return this.load_view();
1024 load_view: function() {
1025 if (this.embedded_view) {
1026 var def = $.Deferred();
1028 $.async_when().then(function() {def.resolve(self.embedded_view);});
1029 return def.pipe(this.on_loaded);
1031 var context = new instance.web.CompoundContext(this.dataset.get_context());
1032 if (! this.view_type)
1033 console.warn("view_type is not defined", this);
1034 return this.rpc("/web/view/load", {
1035 "model": this.dataset.model,
1036 "view_id": this.view_id,
1037 "view_type": this.view_type,
1038 toolbar: !!this.options.$sidebar,
1040 }).pipe(this.on_loaded);
1044 * Called after a successful call to fields_view_get.
1045 * Must return a promise.
1047 on_loaded: function(fields_view_get) {
1049 set_default_options: function(options) {
1050 this.options = options || {};
1051 _.defaults(this.options, {
1052 // All possible views options should be defaulted here
1056 action_views_ids: {}
1059 open_translate_dialog: function(field) {
1060 if (!this.translate_dialog) {
1061 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1063 this.translate_dialog.open(field);
1066 * Fetches and executes the action identified by ``action_data``.
1068 * @param {Object} action_data the action descriptor data
1069 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1070 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1071 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1072 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1073 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1074 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1075 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1077 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1079 var result_handler = function () {
1080 if (on_closed) { on_closed.apply(null, arguments); }
1081 if (self.getParent() && self.getParent().on_action_executed) {
1082 return self.getParent().on_action_executed.apply(null, arguments);
1085 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1087 var handler = function (r) {
1088 var action = r.result;
1089 if (action && action.constructor == Object) {
1090 var ncontext = new instance.web.CompoundContext(context);
1093 active_id: record_id,
1094 active_ids: [record_id],
1095 active_model: dataset.model
1098 ncontext.add(action.context || {});
1099 return self.rpc('/web/session/eval_domain_and_context', {
1100 contexts: [ncontext],
1102 }).pipe(function (results) {
1103 action.context = results.context;
1104 /* niv: previously we were overriding once more with action_data.context,
1105 * I assumed this was not a correct behavior and removed it
1107 return self.do_action(action, result_handler);
1110 return result_handler();
1114 if (action_data.special) {
1115 return handler({result: {"type":"ir.actions.act_window_close"}});
1116 } else if (action_data.type=="object") {
1117 var args = [[record_id]], additional_args = [];
1118 if (action_data.args) {
1120 // Warning: quotes and double quotes problem due to json and xml clash
1121 // Maybe we should force escaping in xml or do a better parse of the args array
1122 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1123 args = args.concat(additional_args);
1125 console.error("Could not JSON.parse arguments", action_data.args);
1129 return dataset.call_button(action_data.name, args, handler);
1130 } else if (action_data.type=="action") {
1131 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1133 return dataset.exec_workflow(record_id, action_data.name, handler);
1137 * Directly set a view to use instead of calling fields_view_get. This method must
1138 * be called before start(). When an embedded view is set, underlying implementations
1139 * of instance.web.View must use the provided view instead of any other one.
1141 * @param embedded_view A view.
1143 set_embedded_view: function(embedded_view) {
1144 this.embedded_view = embedded_view;
1146 do_show: function () {
1147 this.$element.show();
1149 do_hide: function () {
1150 this.$element.hide();
1152 do_push_state: function(state) {
1153 if (this.getParent() && this.getParent().do_push_state) {
1154 this.getParent().do_push_state(state);
1157 do_load_state: function(state, warm) {
1160 * Switches to a specific view type
1162 * @param {String} view view type to switch to
1164 do_switch_view: function(view) {
1167 * Cancels the switch to the current view, switches to the previous one
1169 * @param {Object} [options]
1170 * @param {Boolean} [options.created=false] resource was created
1171 * @param {String} [options.default=null] view to switch to if no previous view
1173 do_prev_view: function (options) {
1175 do_search: function(view) {
1177 on_sidebar_import: function() {
1178 var import_view = new instance.web.DataImport(this, this.dataset);
1179 import_view.start();
1181 on_sidebar_export: function() {
1182 var export_view = new instance.web.DataExport(this, this.dataset);
1183 export_view.start();
1185 on_sidebar_translate: function() {
1186 return this.do_action({
1187 res_model : 'ir.translation',
1188 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1189 views: [[false, 'list'], [false, 'form']],
1190 type : 'ir.actions.act_window',
1195 sidebar_context: function () {
1199 * Asks the view to reload itself, if the reloading is asynchronous should
1200 * return a {$.Deferred} indicating when the reloading is done.
1202 reload: function () {
1207 instance.web.xml_to_json = function(node) {
1208 switch (node.nodeType) {
1214 var attrs = $(node).getAttributes();
1215 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1218 attrs[key] = JSON.parse(attrs[key]);
1223 tag: node.tagName.toLowerCase(),
1225 children: _.map(node.childNodes, instance.web.xml_to_json)
1229 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1230 // For debugging purpose, this function will convert a json node back to xml
1231 // Maybe useful for xml view editor
1232 indent = indent || 0;
1233 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1234 r = sindent + '<' + node.tag,
1235 cr = human_readable ? '\n' : '';
1237 if (typeof(node) === 'string') {
1238 return sindent + node;
1239 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1240 throw("Node a json node");
1242 for (var attr in node.attrs) {
1243 var vattr = node.attrs[attr];
1244 if (typeof(vattr) !== 'string') {
1246 vattr = JSON.stringify(vattr);
1248 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1249 if (human_readable) {
1250 vattr = vattr.replace(/"/g, "'");
1252 r += ' ' + attr + '="' + vattr + '"';
1254 if (node.children && node.children.length) {
1257 for (var i = 0, ii = node.children.length; i < ii; i++) {
1258 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1260 r += childs.join(cr);
1261 r += cr + sindent + '</' + node.tag + '>';
1267 instance.web.xml_to_str = function(node) {
1268 if (window.ActiveXObject) {
1271 return (new XMLSerializer()).serializeToString(node);
1274 instance.web.str_to_xml = function(s) {
1275 if (window.DOMParser) {
1276 var dp = new DOMParser();
1277 var r = dp.parseFromString(s, "text/xml");
1278 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1279 throw new Error("Could not parse string to xml");
1285 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1287 throw new Error("Could not find a DOM Parser: " + e.message);
1290 xDoc.preserveWhiteSpace = true;
1296 * Registry for all the main views
1298 instance.web.views = new instance.web.Registry();
1302 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: