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;
19 this._super.apply(this, arguments);
20 this.breadcrumb = new instance.web.BreadCrumb(this);
22 dialog_stop: function () {
24 this.dialog_viewmanager.destroy();
25 this.dialog_viewmanager = null;
26 this.dialog.destroy();
30 content_stop: function () {
31 // TODO: problem with bread crumb here. Check if those references are needed
32 if (this.inner_viewmanager) {
33 this.inner_viewmanager.destroy();
34 this.inner_viewmanager = null;
36 if (this.client_widget) {
37 this.client_widget.destroy();
38 this.client_widget = null;
41 do_push_state: function(state) {
42 if (this.getParent() && this.getParent().do_push_state) {
43 if (this.inner_action) {
44 state['title'] = this.inner_action.name;
45 state['model'] = this.inner_action.res_model;
46 if (this.inner_action.id) {
47 state['action_id'] = this.inner_action.id;
50 this.getParent().do_push_state(state);
53 do_load_state: function(state, warm) {
56 if (state.action_id) {
57 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
60 action_loaded = this.do_action(state.action_id);
61 instance.webclient.menu.has_been_loaded.then(function() {
62 instance.webclient.menu.open_action(state.action_id);
65 } else if (state.model && state.id) {
66 // TODO handle context & domain ?
69 res_model: state.model,
71 type: 'ir.actions.act_window',
72 views: [[false, 'form']]
74 action_loaded = this.do_action(action);
75 } else if (state.sa) {
76 // load session action
79 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
81 return self.do_action(action);
84 } else if (state.client_action) {
86 var action = state.client_action;
87 if(_.isString(action)) {
93 this.ir_actions_client(action);
96 $.when(action_loaded || null).then(function() {
97 if (self.inner_viewmanager) {
98 self.inner_viewmanager.do_load_state(state, warm);
102 do_action: function(action, on_close) {
103 if (_.isNumber(action)) {
105 return self.rpc("/web/action/load", { action_id: action }, function(result) {
106 self.do_action(result.result, on_close);
110 console.error("No type for action", action);
113 var type = action.type.replace(/\./g,'_');
114 var popup = action.target === 'new';
115 var inline = action.target === 'inline';
116 action.flags = _.extend({
117 views_switcher : !popup && !inline,
118 search_view : !popup && !inline,
119 action_buttons : !popup && !inline,
120 sidebar : !popup && !inline,
121 pager : !popup && !inline,
122 display_title : !popup
123 }, action.flags || {});
124 if (!(type in this)) {
125 console.error("Action manager can't handle action of type " + action.type, action);
128 return this[type](action, on_close);
130 null_action: function() {
134 ir_actions_act_window: function (action, on_close) {
136 if (_(['base.module.upgrade', 'base.setup.installer'])
137 .contains(action.res_model)) {
138 var old_close = on_close;
139 on_close = function () {
140 instance.webclient.do_reload().then(old_close);
143 if (action.target === 'new') {
144 if (this.dialog === null) {
145 this.dialog = new instance.web.Dialog(this, { width: '80%' });
147 this.dialog.on_close.add(on_close);
149 this.dialog_viewmanager.destroy();
151 this.dialog.dialog_title = action.name;
152 this.dialog_viewmanager = new instance.web.ViewManagerAction(this.dialog, action);
153 this.dialog_viewmanager.appendTo(this.dialog.$element);
154 this.dialog_viewmanager.$element.addClass("oe_view_manager_" + action.target);
158 //this.content_stop();
159 this.breadcrumb.hide_items();
161 return this.getParent().do_action(action, function () {
162 instance.webclient.menu.open_menu(action.menu_id);
165 this.inner_action = action;
166 var inner_viewmanager = this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
167 this.breadcrumb.push_actionmanager(inner_viewmanager);
168 this.inner_viewmanager.appendTo(this.$element);
169 this.inner_viewmanager.$element.addClass("oe_view_manager_" + action.target);
172 ir_actions_act_window_close: function (action, on_closed) {
173 if (!this.dialog && on_closed) {
178 ir_actions_server: function (action, on_closed) {
180 this.rpc('/web/action/run', {
181 action_id: action.id,
182 context: action.context || {}
183 }).then(function (action) {
184 self.do_action(action, on_closed)
187 ir_actions_client: function (action) {
188 //this.content_stop();
190 this.breadcrumb.hide_items();
191 var ClientWidget = instance.web.client_actions.get_object(action.tag);
192 this.client_widget = new ClientWidget(this, action.params);
193 this.breadcrumb.push({
194 widget: this.client_widget,
197 this.client_widget.appendTo(this.$element);
199 ir_actions_report_xml: function(action, on_closed) {
202 self.rpc("/web/session/eval_domain_and_context", {
203 contexts: [action.context],
205 }).then(function(res) {
206 action = _.clone(action);
207 action.context = res.context;
208 self.session.get_file({
210 data: {action: JSON.stringify(action)},
211 complete: $.unblockUI,
213 if (!self.dialog && on_closed) {
218 error: instance.webclient.crashmanager.on_rpc_error
222 ir_actions_act_url: function (action) {
223 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
225 ir_ui_menu: function (action) {
226 this.getParent().do_action(action);
230 instance.web.BreadCrumb = instance.web.CallbackEnabled.extend({
231 init: function(parent) {
233 this.action_manager = parent;
235 this.action_manager.$element.on('click', '.oe_breadcrumb_item', this.on_item_clicked);
237 push: function(item) {
238 item.show = item.show || function() {
239 item.widget.$element.show();
241 item.hide = item.hide || function() {
242 item.widget.$element.hide();
244 item.destroy = item.destroy || function() {
245 item.widget.destroy();
247 item.get_title = item.get_title || function() {
248 return item.title || item.widget.get('title');
250 console.log("breadcrumb push", item);
251 this.items.push(item);
253 push_actionmanager: function(am, view_type) {
255 var bookmarked_view = view_type || am.active_view || am.views_src[0].view_type;
260 if (am.active_view !== bookmarked_view) {
261 am.on_mode_switch(bookmarked_view);
265 get_title: function() {
266 return am.views[bookmarked_view].controller.get('title');
269 if (bookmarked_view !== 'form') {
270 am.on_mode_switch.add_first(function(mode) {
271 if (mode === 'form') {
272 self.push_actionmanager(am, 'form');
274 // select previous to form and remove form
280 this.remove_item(this.items.length - 1);
281 this.select_item(this.items.length - 1);
283 get_title: function() {
284 return QWeb.render('BreadCrumb', { widget: this });
286 hide_items: function() {
287 _.each(this.items, function(i) {
291 on_item_clicked: function(ev) {
292 var $e = $(ev.target);
293 var index = $e.data('index');
294 this.select_item(index);
296 select_item: function(index) {
297 for (var i = index + 1; i < this.items.length; i += 1) {
300 var item = this.items[index];
304 console.warn("Breadcrumb: Can't select item at index", index);
307 remove_item: function(index) {
308 console.log("Breadcrumb remove index", index);
309 var item = this.items.splice(index, 1)[0];
311 var dups = _.filter(this.items, function(it) {
312 return item.widget === it.widget;
314 if (dups.length === 0) {
315 console.log("Breadcrumb Destroy", item);
319 console.warn("Breadcrumb: Can't remove item at index", index);
323 while (this.items.length) {
329 instance.web.ViewManager = instance.web.Widget.extend({
330 template: "ViewManager",
331 init: function(parent, dataset, views, flags) {
333 this.model = dataset ? dataset.model : undefined;
334 this.dataset = dataset;
335 this.searchview = null;
336 this.active_view = null;
337 this.views_src = _.map(views, function(x) {
338 if (x instanceof Array) {
339 var View = instance.web.views.get_object(x[1], true);
343 label: View ? View.prototype.display_name : (void 'nope')
350 this.flags = flags || {};
351 this.registry = instance.web.views;
352 this.views_history = [];
355 * @returns {jQuery.Deferred} initial view loading promise
360 this.$element.find('.oe_view_manager_switch a').click(function() {
361 self.on_mode_switch($(this).data('view-type'));
364 _.each(this.views_src, function(view) {
365 self.views[view.view_type] = $.extend({}, view, {
366 deferred : $.Deferred(),
369 $buttons : self.$element.find('.oe_view_manager_buttons'),
370 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
371 $pager : self.$element.find('.oe_view_manager_pager'),
372 action : self.action,
373 action_views_ids : views_ids
374 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
376 views_ids[view.view_type] = view.view_id;
378 if (this.flags.views_switcher === false) {
379 this.$element.find('.oe_view_manager_switch').hide();
381 // If no default view defined, switch to the first one in sequence
382 var default_view = this.flags.default_view || this.views_src[0].view_type;
383 return this.on_mode_switch(default_view);
386 * Asks the view manager to switch visualization mode.
388 * @param {String} view_type type of view to display
389 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
390 * @returns {jQuery.Deferred} new view loading promise
392 on_mode_switch: function(view_type, no_store, view_options) {
394 var view = this.views[view_type];
397 return $.Deferred().reject();
400 this.views_history.push(view_type);
402 this.active_view = view_type;
404 if (!view.controller) {
405 view_promise = this.do_create_view(view_type);
406 } else if (this.searchview
407 && self.flags.auto_search
408 && view.controller.searchable !== false) {
409 this.searchview.ready.then(this.searchview.do_search);
412 if (this.searchview) {
413 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
417 .find('.oe_view_manager_switch a').parent().removeClass('active');
419 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
420 .parent().addClass('active');
422 $.when(view_promise).then(function () {
423 _.each(_.keys(self.views), function(view_name) {
424 var controller = self.views[view_name].controller;
426 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
427 if (view_name === view_type) {
429 controller.do_show(view_options || {});
432 controller.do_hide();
439 do_create_view: function(view_type) {
440 // Lazy loading of views
442 var view = this.views[view_type];
443 var controllerclass = this.registry.get_object(view_type);
444 var options = _.clone(view.options);
445 if (view_type === "form" && this.action) {
446 switch (this.action.target) {
449 options.initial_mode = 'edit';
453 var controller = new controllerclass(this, this.dataset, view.view_id, options);
455 controller.on("change:title", this, function() {
456 if (self.active_view === view_type) {
457 self.set_title(controller.get('title'));
461 if (view.embedded_view) {
462 controller.set_embedded_view(view.embedded_view);
464 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
466 controller.do_prev_view.add_last(this.on_prev_view);
467 var container = this.$element.find(".oe_view_manager_view_" + view_type);
468 var view_promise = controller.appendTo(container);
469 this.views[view_type].controller = controller;
470 this.views[view_type].deferred.resolve(view_type);
471 return $.when(view_promise).then(function() {
472 self.on_controller_inited(view_type, controller);
474 && self.flags.auto_search
475 && view.controller.searchable !== false) {
476 self.searchview.ready.then(self.searchview.do_search);
480 set_title: function(title) {
481 this.$element.find('.oe_view_title_text:first').text(title);
484 * Method used internally when a view asks to switch view. This method is meant
485 * to be extended by child classes to change the default behavior, which simply
486 * consist to switch to the asked view.
488 switch_view: function(view_type, no_store, options) {
489 return this.on_mode_switch(view_type, no_store, options);
492 * Returns to the view preceding the caller view in this manager's
493 * navigation history (the navigation history is appended to via
496 * @param {Object} [options]
497 * @param {Boolean} [options.created=false] resource was created
498 * @param {String} [options.default=null] view to switch to if no previous view
499 * @returns {$.Deferred} switching end signal
501 on_prev_view: function (options) {
502 options = options || {};
503 var current_view = this.views_history.pop();
504 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
505 if (options.created && current_view === 'form' && previous_view === 'list') {
506 // APR special case: "If creation mode from list (and only from a list),
507 // after saving, go to page view (don't come back in list)"
508 return this.on_mode_switch('form');
509 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
510 // APR special case: "If creation from dashboard, we have no previous view
511 return this.on_mode_switch('form');
513 return this.on_mode_switch(previous_view, true);
516 * Sets up the current viewmanager's search view.
518 * @param {Number|false} view_id the view to use or false for a default one
519 * @returns {jQuery.Deferred} search view startup deferred
521 setup_search_view: function(view_id, search_defaults) {
523 if (this.searchview) {
524 this.searchview.destroy();
526 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
528 this.searchview.on_search.add(this.do_searchview_search);
529 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
531 do_searchview_search: function(domains, contexts, groupbys) {
533 controller = this.views[this.active_view].controller,
534 action_context = this.action.context || {};
535 this.rpc('/web/session/eval_domain_and_context', {
536 domains: [this.action.domain || []].concat(domains || []),
537 contexts: [action_context].concat(contexts || []),
538 group_by_seq: groupbys || []
539 }, function (results) {
540 self.dataset._model = new instance.web.Model(
541 self.dataset.model, results.context, results.domain);
542 var groupby = results.group_by.length
544 : action_context.group_by;
545 if (_.isString(groupby)) {
548 controller.do_search(results.domain, results.context, groupby || []);
552 * Event launched when a controller has been inited.
554 * @param {String} view_type type of view
555 * @param {String} view the inited controller
557 on_controller_inited: function(view_type, view) {
560 * Called when one of the view want to execute an action
562 on_action: function(action) {
564 on_create: function() {
566 on_remove: function() {
568 on_edit: function() {
571 * Called by children view after executing an action
573 on_action_executed: function () {
577 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
578 template:"ViewManagerAction",
580 * @constructs instance.web.ViewManagerAction
581 * @extends instance.web.ViewManager
583 * @param {instance.web.ActionManager} parent parent object/widget
584 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
586 init: function(parent, action) {
587 // dataset initialization will take the session from ``this``, so if we
588 // do not have it yet (and we don't, because we've not called our own
589 // ``_super()``) rpc requests will blow up.
590 var flags = action.flags || {};
591 if (!('auto_search' in flags)) {
592 flags.auto_search = action.auto_search !== false;
594 if (action.res_model == 'board.board' && action.view_mode === 'form') {
595 // Special case for Dashboards
597 views_switcher : false,
598 display_title : false,
602 action_buttons : false
605 this._super(parent, null, action.views, flags);
606 this.session = parent.session;
607 this.action = action;
608 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
610 dataset.ids.push(action.res_id);
613 this.dataset = dataset;
615 // setup storage for session-wise menu hiding
616 if (this.session.hidden_menutips) {
619 this.session.hidden_menutips = {};
622 * Initializes the ViewManagerAction: sets up the searchview (if the
623 * searchview is enabled in the manager's action flags), calls into the
624 * parent to initialize the primary view and (if the VMA has a searchview)
625 * launches an initial search after both views are done rendering.
630 search_defaults = {};
631 _.each(this.action.context, function (value, key) {
632 var match = /^search_default_(.*)$/.exec(key);
634 search_defaults[match[1]] = value;
638 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
640 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
642 var main_view_loaded = this._super();
644 var manager_ready = $.when(searchview_loaded, main_view_loaded);
646 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
648 if (this.action.help && !this.flags.low_profile) {
649 var Users = new instance.web.DataSet(self, 'res.users'),
650 $tips = this.$element.find('.oe_view_manager_menu_tips');
651 $tips.delegate('blockquote button', 'click', function() {
653 //noinspection FallthroughInSwitchStatementJS
654 switch ($this.attr('name')) {
656 Users.write(self.session.uid, {menu_tips:false});
658 $this.closest('blockquote').hide();
659 self.session.hidden_menutips[self.action.id] = true;
662 if (!(self.action.id in self.session.hidden_menutips)) {
663 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
665 if (!(user && user.id === self.session.uid)) {
668 $tips.find('blockquote').toggle(user.menu_tips);
673 return manager_ready;
675 on_debug_changed: function (evt) {
677 $sel = $(evt.currentTarget),
678 $option = $sel.find('option:selected'),
680 current_view = this.views[this.active_view].controller;
683 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
684 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
687 var ids = current_view.get_selected_ids();
688 if (ids.length === 1) {
689 this.dataset.call('perm_read', [ids]).then(function(result) {
690 var dialog = new instance.web.Dialog(this, {
691 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
693 }, QWeb.render('ViewManagerDebugViewLog', {
695 format : instance.web.format_value
700 case 'toggle_layout_outline':
701 current_view.rendering_engine.toggle_layout_debugging();
704 this.dataset.call_and_eval(
705 'fields_get', [false, {}], null, 1).then(function (fields) {
706 var $root = $('<dl>');
707 _(fields).each(function (attributes, name) {
708 $root.append($('<dt>').append($('<h4>').text(name)));
709 var $attrs = $('<dl>').appendTo(
710 $('<dd>').appendTo($root));
711 _(attributes).each(function (def, name) {
712 if (def instanceof Object) {
713 def = JSON.stringify(def);
716 .append($('<dt>').text(name))
717 .append($('<dd style="white-space: pre-wrap;">').text(def));
720 new instance.web.Dialog(self, {
721 title: _.str.sprintf(_t("Model %s fields"),
723 width: '95%'}, $root).open();
727 if (current_view.fields_view && current_view.fields_view.arch) {
728 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
731 this.do_warn(_t("Manage Views"),
732 _t("Could not find current view declaration"));
735 case 'edit_workflow':
736 return this.do_action({
737 res_model : 'workflow',
738 domain : [['osv', '=', this.dataset.model]],
739 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
740 type : 'ir.actions.act_window',
746 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
748 case 'manage_filters':
750 res_model: 'ir.filters',
751 views: [[false, 'list'], [false, 'form']],
752 type: 'ir.actions.act_window',
754 search_default_my_filters: true,
755 search_default_model_id: this.dataset.model
761 console.log("No debug handler for ", val);
764 evt.currentTarget.selectedIndex = 0;
766 do_edit_resource: function(model, id, action) {
767 var action = _.extend({
770 type : 'ir.actions.act_window',
773 views : [[false, 'form']],
776 action_buttons : true,
778 resize_textareas : true
782 this.do_action(action);
784 on_mode_switch: function (view_type, no_store, options) {
787 return $.when(this._super.apply(this, arguments)).then(function () {
788 var controller = self.views[self.active_view].controller,
789 fvg = controller.fields_view,
790 view_id = (fvg && fvg.view_id) || '--';
791 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
795 if (!self.action.name && fvg) {
796 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
801 do_create_view: function(view_type) {
802 var r = this._super.apply(this, arguments);
803 var view = this.views[view_type].controller;
804 view.set({ 'title': this.action.name });
807 set_title: function(title) {
808 var breadcrumb = this.getParent().breadcrumb;
810 this.$element.find('.oe_breadcrumb_title:first').html(breadcrumb.get_title());
813 do_push_state: function(state) {
814 if (this.getParent() && this.getParent().do_push_state) {
815 state["view_type"] = this.active_view;
816 this.getParent().do_push_state(state);
819 do_load_state: function(state, warm) {
822 if (state.view_type && state.view_type !== this.active_view) {
824 this.views[this.active_view].deferred.pipe(function() {
825 return self.on_mode_switch(state.view_type, true);
830 $.when(defs).then(function() {
831 self.views[self.active_view].controller.do_load_state(state, warm);
836 instance.web.Sidebar = instance.web.Widget.extend({
837 init: function(parent) {
840 var view = this.getParent();
842 { 'name' : 'print', 'label' : _t('Print'), },
843 { 'name' : 'files', 'label' : _t('Attachment'), },
844 { 'name' : 'other', 'label' : _t('More'), }
851 if (this.session.uid === 1) {
852 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
853 this.items.other.push(item);
855 this.fileupload_id = _.uniqueId('oe_fileupload');
856 $(window).on(this.fileupload_id, function() {
857 var args = [].slice.call(arguments).slice(1);
858 if (args[0] && args[0].error) {
859 alert(args[0].error);
861 self.do_attachement_update(self.dataset, self.model_id);
870 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
871 var section = $(this).data('section');
872 var index = $(this).data('index');
873 var item = self.items[section][index];
875 item.callback.apply(self, [item]);
876 } else if (item.action) {
877 self.on_item_action_clicked(item);
878 } else if (item.url) {
881 event.preventDefault();
886 self.$element.html(QWeb.render('Sidebar', {widget: self}));
888 // Hides Sidebar sections when item list is empty
889 this.$('.oe_form_dropdown_section').each(function() {
890 $(this).toggle(!!$(this).find('li').length);
894 * For each item added to the section:
897 * will be used as the item's name in the sidebar, can be html
900 * descriptor for the action which will be executed, ``action`` and
901 * ``callback`` should be exclusive
904 * function to call when the item is clicked in the sidebar, called
905 * with the item descriptor as its first argument (so information
906 * can be stored as additional keys on the object passed to
909 * ``classname`` (optional)
910 * ``@class`` set on the sidebar serialization of the item
912 * ``title`` (optional)
913 * will be set as the item's ``@title`` (tooltip)
915 * @param {String} section_code
916 * @param {Array<{label, action | callback[, classname][, title]}>} items
918 add_items: function(section_code, items) {
921 this.items[section_code].push.apply(this.items[section_code],items);
925 add_toolbar: function(toolbar) {
927 _.each(['print','action','relate'], function(type) {
928 var items = toolbar[type];
930 for (var i = 0; i < items.length; i++) {
932 label: items[i]['name'],
934 classname: 'oe_sidebar_' + type
937 self.add_items(type=='print' ? 'print' : 'other', items);
941 on_item_action_clicked: function(item) {
943 self.getParent().sidebar_context().then(function (context) {
944 var ids = self.getParent().get_selected_ids();
945 if (ids.length == 0) {
946 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
949 var additional_context = _.extend({
952 active_model: self.getParent().dataset.model
954 self.rpc("/web/action/load", {
955 action_id: item.action.id,
956 context: additional_context
957 }, function(result) {
958 result.result.context = _.extend(result.result.context || {},
960 result.result.flags = result.result.flags || {};
961 result.result.flags.new_window = true;
962 self.do_action(result.result, function () {
964 self.getParent().reload();
969 do_attachement_update: function(dataset, model_id) {
970 this.dataset = dataset;
971 this.model_id = model_id;
973 this.on_attachments_loaded([]);
975 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
976 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
977 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
980 on_attachments_loaded: function(attachments) {
983 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
984 _.each(attachments,function(a) {
986 if(a.type === "binary") {
987 a.url = prefix + a.id + '&t=' + (new Date().getTime());
990 self.items['files'] = attachments;
992 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
993 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
995 on_attachment_changed: function(e) {
996 var $e = $(e.target);
997 if ($e.val() !== '') {
998 this.$element.find('form.oe_form_binary_form').submit();
999 $e.parent().find('input[type=file]').prop('disabled', true);
1000 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1001 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1005 on_attachment_delete: function(e) {
1008 e.stopPropagation();
1010 var $e = $(e.currentTarget);
1011 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1012 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1013 self.do_attachement_update(self.dataset, self.model_id);
1019 instance.web.TranslateDialog = instance.web.Dialog.extend({
1020 dialog_title: {toString: function () { return _t("Translations"); }},
1021 init: function(view) {
1022 // TODO fme: should add the language to fields_view_get because between the fields view get
1023 // and the moment the user opens the translation dialog, the user language could have been changed
1024 this.view_language = view.session.user_context.lang;
1025 this['on_button_' + _t("Save")] = this.on_btn_save;
1026 this['on_button_' + _t("Close")] = this.on_btn_close;
1032 this.view_type = view.fields_view.type || '';
1033 this.$fields_form = null;
1034 this.$view_form = null;
1035 this.$sidebar_form = null;
1036 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
1037 this.languages = null;
1038 this.languages_loaded = $.Deferred();
1039 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
1040 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
1045 $.when(this.languages_loaded).then(function() {
1046 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
1047 self.$fields_form = self.$element.find('.oe_translation_form');
1048 self.$fields_form.find('.oe_trad_field').change(function() {
1049 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
1054 on_languages_loaded: function(langs) {
1055 this.languages = langs;
1056 this.languages_loaded.resolve();
1058 do_load_fields_values: function(callback) {
1061 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1062 _.each(self.languages, function(lg) {
1063 var deff = $.Deferred();
1064 deffered.push(deff);
1065 var callback = function(values) {
1066 _.each(self.translatable_fields_keys, function(f) {
1067 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1071 if (lg.code === self.view_language) {
1073 _.each(self.translatable_fields_keys, function(field) {
1074 values[field] = self.view.fields[field].get_value();
1078 self.rpc('/web/dataset/get', {
1079 model: self.view.dataset.model,
1080 ids: [self.view.datarecord.id],
1081 fields: self.translatable_fields_keys,
1082 context: self.view.dataset.get_context({
1087 $.when.apply(null, deffered).then(callback);
1089 open: function(field) {
1092 $.when(this.languages_loaded).then(function() {
1093 if (self.view.translatable_fields && self.view.translatable_fields.length) {
1094 self.do_load_fields_values(function() {
1097 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1098 self.$element.scrollTo($field_input);
1099 $field_input.focus();
1107 on_btn_save: function() {
1110 trads_mutex = new $.Mutex();
1111 self.$fields_form.find('.oe_trad_field.touched').each(function() {
1112 var field = $(this).attr('name').split('-');
1113 if (!trads[field[0]]) {
1114 trads[field[0]] = {};
1116 trads[field[0]][field[1]] = $(this).val();
1118 _.each(trads, function(data, code) {
1119 if (code === self.view_language) {
1120 _.each(data, function(value, field) {
1121 self.view.fields[field].set_value(value);
1124 trads_mutex.exec(function() {
1125 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1130 on_btn_close: function() {
1135 instance.web.View = instance.web.Widget.extend({
1136 template: "EmptyComponent",
1137 // name displayed in view switchers
1140 * Define a view type for each view to allow automatic call to fields_view_get.
1142 view_type: undefined,
1143 init: function(parent, dataset, view_id, options) {
1144 this._super(parent);
1145 this.dataset = dataset;
1146 this.view_id = view_id;
1147 this.set_default_options(options);
1150 return this.load_view();
1152 load_view: function() {
1153 if (this.embedded_view) {
1154 var def = $.Deferred();
1156 $.async_when().then(function() {def.resolve(self.embedded_view);});
1157 return def.pipe(this.on_loaded);
1159 var context = new instance.web.CompoundContext(this.dataset.get_context());
1160 if (! this.view_type)
1161 console.warn("view_type is not defined", this);
1162 return this.rpc("/web/view/load", {
1163 "model": this.dataset.model,
1164 "view_id": this.view_id,
1165 "view_type": this.view_type,
1166 toolbar: !!this.options.$sidebar,
1168 }).pipe(this.on_loaded);
1172 * Called after a successful call to fields_view_get.
1173 * Must return a promise.
1175 on_loaded: function(fields_view_get) {
1177 set_default_options: function(options) {
1178 this.options = options || {};
1179 _.defaults(this.options, {
1180 // All possible views options should be defaulted here
1184 action_views_ids: {}
1187 open_translate_dialog: function(field) {
1188 if (!this.translate_dialog) {
1189 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1191 this.translate_dialog.open(field);
1194 * Fetches and executes the action identified by ``action_data``.
1196 * @param {Object} action_data the action descriptor data
1197 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1198 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1199 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1200 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1201 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1202 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1203 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1205 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1207 var result_handler = function () {
1208 if (on_closed) { on_closed.apply(null, arguments); }
1209 if (self.getParent() && self.getParent().on_action_executed) {
1210 return self.getParent().on_action_executed.apply(null, arguments);
1213 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1215 var handler = function (r) {
1216 var action = r.result;
1217 if (action && action.constructor == Object) {
1218 var ncontext = new instance.web.CompoundContext(context);
1221 active_id: record_id,
1222 active_ids: [record_id],
1223 active_model: dataset.model
1226 ncontext.add(action.context || {});
1227 return self.rpc('/web/session/eval_domain_and_context', {
1228 contexts: [ncontext],
1230 }).pipe(function (results) {
1231 action.context = results.context;
1232 /* niv: previously we were overriding once more with action_data.context,
1233 * I assumed this was not a correct behavior and removed it
1235 return self.do_action(action, result_handler);
1238 return result_handler();
1242 if (action_data.special) {
1243 return handler({result: {"type":"ir.actions.act_window_close"}});
1244 } else if (action_data.type=="object") {
1245 var args = [[record_id]], additional_args = [];
1246 if (action_data.args) {
1248 // Warning: quotes and double quotes problem due to json and xml clash
1249 // Maybe we should force escaping in xml or do a better parse of the args array
1250 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1251 args = args.concat(additional_args);
1253 console.error("Could not JSON.parse arguments", action_data.args);
1257 return dataset.call_button(action_data.name, args, handler);
1258 } else if (action_data.type=="action") {
1259 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1261 return dataset.exec_workflow(record_id, action_data.name, handler);
1265 * Directly set a view to use instead of calling fields_view_get. This method must
1266 * be called before start(). When an embedded view is set, underlying implementations
1267 * of instance.web.View must use the provided view instead of any other one.
1269 * @param embedded_view A view.
1271 set_embedded_view: function(embedded_view) {
1272 this.embedded_view = embedded_view;
1274 do_show: function () {
1275 this.$element.show();
1277 do_hide: function () {
1278 this.$element.hide();
1280 do_push_state: function(state) {
1281 if (this.getParent() && this.getParent().do_push_state) {
1282 this.getParent().do_push_state(state);
1285 do_load_state: function(state, warm) {
1288 * Switches to a specific view type
1290 * @param {String} view view type to switch to
1292 do_switch_view: function(view) {
1295 * Cancels the switch to the current view, switches to the previous one
1297 * @param {Object} [options]
1298 * @param {Boolean} [options.created=false] resource was created
1299 * @param {String} [options.default=null] view to switch to if no previous view
1301 do_prev_view: function (options) {
1303 do_search: function(view) {
1305 on_sidebar_import: function() {
1306 var import_view = new instance.web.DataImport(this, this.dataset);
1307 import_view.start();
1309 on_sidebar_export: function() {
1310 var export_view = new instance.web.DataExport(this, this.dataset);
1311 export_view.start();
1313 on_sidebar_translate: function() {
1314 return this.do_action({
1315 res_model : 'ir.translation',
1316 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1317 views: [[false, 'list'], [false, 'form']],
1318 type : 'ir.actions.act_window',
1323 sidebar_context: function () {
1327 * Asks the view to reload itself, if the reloading is asynchronous should
1328 * return a {$.Deferred} indicating when the reloading is done.
1330 reload: function () {
1335 instance.web.xml_to_json = function(node) {
1336 switch (node.nodeType) {
1342 var attrs = $(node).getAttributes();
1343 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1346 attrs[key] = JSON.parse(attrs[key]);
1351 tag: node.tagName.toLowerCase(),
1353 children: _.map(node.childNodes, instance.web.xml_to_json)
1357 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1358 // For debugging purpose, this function will convert a json node back to xml
1359 // Maybe useful for xml view editor
1360 indent = indent || 0;
1361 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1362 r = sindent + '<' + node.tag,
1363 cr = human_readable ? '\n' : '';
1365 if (typeof(node) === 'string') {
1366 return sindent + node;
1367 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1368 throw("Node a json node");
1370 for (var attr in node.attrs) {
1371 var vattr = node.attrs[attr];
1372 if (typeof(vattr) !== 'string') {
1374 vattr = JSON.stringify(vattr);
1376 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1377 if (human_readable) {
1378 vattr = vattr.replace(/"/g, "'");
1380 r += ' ' + attr + '="' + vattr + '"';
1382 if (node.children && node.children.length) {
1385 for (var i = 0, ii = node.children.length; i < ii; i++) {
1386 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1388 r += childs.join(cr);
1389 r += cr + sindent + '</' + node.tag + '>';
1395 instance.web.xml_to_str = function(node) {
1396 if (window.ActiveXObject) {
1399 return (new XMLSerializer()).serializeToString(node);
1402 instance.web.str_to_xml = function(s) {
1403 if (window.DOMParser) {
1404 var dp = new DOMParser();
1405 var r = dp.parseFromString(s, "text/xml");
1406 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1407 throw new Error("Could not parse string to xml");
1413 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1415 throw new Error("Could not find a DOM Parser: " + e.message);
1418 xDoc.preserveWhiteSpace = true;
1424 * Registry for all the main views
1426 instance.web.views = new instance.web.Registry();
1430 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: