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_widget = null;
15 this.dialog_widget = null;
16 this.breadcrumbs = [];
17 this.on('history_back', this, function() {
18 return this.history_back();
22 this._super.apply(this, arguments);
23 this.$el.on('click', 'a.oe_breadcrumb_item', this.on_breadcrumb_clicked);
25 dialog_stop: function () {
27 this.dialog_widget.destroy();
28 this.dialog_widget = null;
29 this.dialog.destroy();
34 * Add a new item to the breadcrumb
36 * If the title of an item is an array, the multiple title mode is in use.
37 * (eg: a widget with multiple views might need to display a title for each view)
38 * In multiple title mode, the show() callback can check the index it receives
39 * in order to detect which of its titles has been clicked on by the user.
41 * @param {Object} item breadcrumb item
42 * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
43 * @param {Function} [item.show] triggered whenever the widget should be shown back
44 * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
45 * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
46 * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
47 * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
49 push_breadcrumb: function(item) {
50 var last = this.breadcrumbs.slice(-1)[0];
55 show: function(index) {
56 this.widget.$el.show();
59 this.widget.$el.hide();
62 this.widget.destroy();
64 get_title: function() {
65 return this.title || this.widget.get('title');
68 item.id = _.uniqueId('breadcrumb_');
69 this.breadcrumbs.push(item);
71 history_back: function() {
72 var last = this.breadcrumbs.slice(-1)[0];
76 var title = last.get_title();
77 if (_.isArray(title) && title.length > 1) {
78 return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
79 } else if (this.breadcrumbs.length === 1) {
80 // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
83 var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
84 title = prev.get_title();
85 return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
88 on_breadcrumb_clicked: function(ev) {
89 var $e = $(ev.target);
90 var id = $e.data('id');
92 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
93 if (this.breadcrumbs[i].id == id) {
98 var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
99 this.select_breadcrumb(index, subindex);
101 select_breadcrumb: function(index, subindex) {
102 var next_item = this.breadcrumbs[index + 1];
103 if (next_item && next_item.on_reverse_breadcrumb) {
104 next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
106 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
108 if (this.remove_breadcrumb(i) === false) {
113 var item = this.breadcrumbs[index];
115 this.inner_widget = item.widget;
116 this.inner_action = item.action;
119 clear_breadcrumbs: function() {
120 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
121 if (this.remove_breadcrumb(0) === false) {
126 remove_breadcrumb: function(index) {
127 var item = this.breadcrumbs.splice(index, 1)[0];
129 var dups = _.filter(this.breadcrumbs, function(it) {
130 return item.widget === it.widget;
133 if (this.getParent().has_uncommitted_changes()) {
134 this.inner_widget = item.widget;
135 this.inner_action = item.action;
136 this.breadcrumbs.splice(index, 0, item);
143 var last_widget = this.breadcrumbs.slice(-1)[0];
145 this.inner_widget = last_widget.widget;
146 this.inner_action = last_widget.action;
149 get_title: function() {
151 for (var i = 0; i < this.breadcrumbs.length; i += 1) {
152 var item = this.breadcrumbs[i];
153 var tit = item.get_title();
154 if (!_.isArray(tit)) {
157 for (var j = 0; j < tit.length; j += 1) {
158 var label = _.escape(tit[j]);
159 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
160 titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
162 titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
166 return titles.join(' <span class="oe_fade">/</span> ');
168 do_push_state: function(state) {
170 if (this.getParent() && this.getParent().do_push_state) {
171 if (this.inner_action) {
172 if (this.inner_action._push_me === false) {
173 // this action has been explicitly marked as not pushable
176 state['title'] = this.inner_action.name;
177 if(this.inner_action.type == 'ir.actions.act_window') {
178 state['model'] = this.inner_action.res_model;
180 if (this.inner_action.id) {
181 state['action'] = this.inner_action.id;
182 } else if (this.inner_action.type == 'ir.actions.client') {
183 state['action'] = this.inner_action.tag;
185 _.each(this.inner_action.params, function(v, k) {
186 if(_.isString(v) || _.isNumber(v)) {
190 state = _.extend(params || {}, state);
194 this.getParent().do_push_state(state);
198 do_load_state: function(state, warm) {
202 if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
203 var action_client = {type: "ir.actions.client", tag: state.action, params: state};
205 action_loaded = this.do_action(action_client);
207 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
210 action_loaded = this.do_action(state.action);
211 instance.webclient.menu.has_been_loaded.then(function() {
212 instance.webclient.menu.open_action(state.action);
216 } else if (state.model && state.id) {
217 // TODO handle context & domain ?
220 res_model: state.model,
222 type: 'ir.actions.act_window',
223 views: [[false, 'form']]
225 action_loaded = this.do_action(action);
226 } else if (state.sa) {
227 // load session action
229 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
231 return self.do_action(action);
236 $.when(action_loaded || null).then(function() {
237 if (self.inner_widget && self.inner_widget.do_load_state) {
238 self.inner_widget.do_load_state(state, warm);
242 do_action: function(action, options) {
243 options = _.defaults(options || {}, {
244 clear_breadcrumbs: false,
245 on_reverse_breadcrumb: function() {},
246 on_close: function() {},
248 if (_.isString(action) && instance.web.client_actions.contains(action)) {
249 var action_client = { type: "ir.actions.client", tag: action };
250 return this.do_action(action_client, options);
251 } else if (_.isNumber(action) || _.isString(action)) {
253 return self.rpc("/web/action/load", { action_id: action }).pipe(function(result) {
254 return self.do_action(result, options);
258 console.error("No type for action", action);
259 return $.Deferred().reject();
261 var type = action.type.replace(/\./g,'_');
262 var popup = action.target === 'new';
263 var inline = action.target === 'inline' || action.target === 'inlineview';
264 action.flags = _.extend({
265 views_switcher : !popup && !inline,
266 search_view : !popup && !inline,
267 action_buttons : !popup && !inline,
268 sidebar : !popup && !inline,
269 pager : !popup && !inline,
270 display_title : !popup
271 }, action.flags || {});
272 if (!(type in this)) {
273 console.error("Action manager can't handle action of type " + action.type, action);
274 return $.Deferred().reject();
276 return this[type](action, options);
278 null_action: function() {
280 this.clear_breadcrumbs();
284 * @param {Object} executor
285 * @param {Object} executor.action original action
286 * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
287 * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
288 * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
289 * @param {Object} options
292 ir_actions_common: function(executor, options) {
293 if (this.inner_widget && executor.action.target !== 'new') {
294 if (this.getParent().has_uncommitted_changes()) {
295 return $.Deferred().reject();
296 } else if (options.clear_breadcrumbs) {
297 this.clear_breadcrumbs();
300 var widget = executor.widget();
301 if (executor.action.target === 'new') {
302 if (this.dialog === null || this.dialog.isDestroyed()) {
303 this.dialog = new instance.web.Dialog(this, {
304 buttons: {"Close": function() {$(this).dialog("close")}},
305 dialogClass: executor.klass,
307 this.dialog.on("closing", null, options.on_close);
308 this.dialog.init_dialog();
310 this.dialog_widget.destroy();
312 this.dialog.dialog_title = executor.action.name;
313 if (widget instanceof instance.web.ViewManager) {
314 _.extend(widget.flags, {
315 $buttons: this.dialog.$buttons,
316 footer_to_buttons: true,
319 this.dialog_widget = widget;
320 var initialized = this.dialog_widget.appendTo(this.dialog.$el);
325 this.inner_action = executor.action;
326 this.inner_widget = widget;
327 executor.post_process(widget);
328 return this.inner_widget.appendTo(this.$el);
331 ir_actions_act_window: function (action, options) {
334 return this.ir_actions_common({
335 widget: function () { return new instance.web.ViewManagerAction(self, action); },
337 klass: 'oe_act_window',
338 post_process: function (widget) { widget.add_breadcrumb(options.on_reverse_breadcrumb); }
341 ir_actions_client: function (action, options) {
343 var ClientWidget = instance.web.client_actions.get_object(action.tag);
345 if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
347 if (next = ClientWidget(this, action.params)) {
348 return this.do_action(next, options);
353 return this.ir_actions_common({
354 widget: function () { return new ClientWidget(self, action.params); },
356 klass: 'oe_act_client',
357 post_process: function(widget) {
358 self.push_breadcrumb({
361 on_reverse_breadcrumb: options.on_reverse_breadcrumb,
363 if (action.tag !== 'reload') {
364 self.do_push_state({});
369 ir_actions_act_window_close: function (action, options) {
375 ir_actions_server: function (action, options) {
377 this.rpc('/web/action/run', {
378 action_id: action.id,
379 context: action.context || {}
380 }).then(function (action) {
381 self.do_action(action, options)
384 ir_actions_report_xml: function(action, options) {
386 instance.web.blockUI();
387 self.rpc("/web/session/eval_domain_and_context", {
388 contexts: [action.context],
390 }).then(function(res) {
391 action = _.clone(action);
392 action.context = res.context;
393 self.session.get_file({
395 data: {action: JSON.stringify(action)},
396 complete: instance.web.unblockUI,
403 error: instance.webclient.crashmanager.on_rpc_error
407 ir_actions_act_url: function (action) {
408 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
412 instance.web.ViewManager = instance.web.Widget.extend({
413 template: "ViewManager",
414 init: function(parent, dataset, views, flags) {
416 this.url_states = {};
417 this.model = dataset ? dataset.model : undefined;
418 this.dataset = dataset;
419 this.searchview = null;
420 this.active_view = null;
421 this.views_src = _.map(views, function(x) {
422 if (x instanceof Array) {
423 var View = instance.web.views.get_object(x[1], true);
427 label: View ? View.prototype.display_name : (void 'nope')
434 this.flags = flags || {};
435 this.registry = instance.web.views;
436 this.views_history = [];
439 * @returns {jQuery.Deferred} initial view loading promise
444 this.$el.find('.oe_view_manager_switch a').click(function() {
445 self.switch_mode($(this).data('view-type'));
448 _.each(this.views_src, function(view) {
449 self.views[view.view_type] = $.extend({}, view, {
450 deferred : $.Deferred(),
453 $buttons : self.$el.find('.oe_view_manager_buttons'),
454 $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
455 $pager : self.$el.find('.oe_view_manager_pager'),
456 action : self.action,
457 action_views_ids : views_ids
458 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
460 views_ids[view.view_type] = view.view_id;
462 if (this.flags.views_switcher === false) {
463 this.$el.find('.oe_view_manager_switch').hide();
465 // If no default view defined, switch to the first one in sequence
466 var default_view = this.flags.default_view || this.views_src[0].view_type;
467 return this.switch_mode(default_view);
469 switch_mode: function(view_type, no_store, view_options) {
471 var view = this.views[view_type];
473 var form = this.views['form'];
474 if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
475 self.trigger('switch_mode', view_type, no_store, view_options);
476 return $.Deferred().reject();
479 this.views_history.push(view_type);
481 this.active_view = view_type;
483 if (!view.controller) {
484 view_promise = this.do_create_view(view_type);
485 } else if (this.searchview
486 && self.flags.auto_search
487 && view.controller.searchable !== false) {
488 this.searchview.ready.then(this.searchview.do_search);
491 if (this.searchview) {
492 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
495 this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
497 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
498 .parent().addClass('active');
500 r = $.when(view_promise).then(function () {
501 _.each(_.keys(self.views), function(view_name) {
502 var controller = self.views[view_name].controller;
504 var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
505 if (view_name === view_type) {
507 controller.do_show(view_options || {});
510 controller.do_hide();
514 self.trigger('switch_mode', view_type, no_store, view_options);
518 do_create_view: function(view_type) {
519 // Lazy loading of views
521 var view = this.views[view_type];
522 var viewclass = this.registry.get_object(view_type);
523 var options = _.clone(view.options);
524 if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
525 options.initial_mode = 'edit';
527 var controller = new viewclass(this, this.dataset, view.view_id, options);
529 controller.on('history_back', this, function() {
530 var am = self.getParent();
531 if (am && am.trigger) {
532 return am.trigger('history_back');
536 controller.on("change:title", this, function() {
537 if (self.active_view === view_type) {
538 self.set_title(controller.get('title'));
542 if (view.embedded_view) {
543 controller.set_embedded_view(view.embedded_view);
545 controller.on('switch_mode', self, this.switch_mode);
546 controller.on('previous_view', self, this.prev_view);
548 var container = this.$el.find(".oe_view_manager_view_" + view_type);
549 var view_promise = controller.appendTo(container);
550 this.views[view_type].controller = controller;
551 this.views[view_type].deferred.resolve(view_type);
552 return $.when(view_promise).then(function() {
554 && self.flags.auto_search
555 && view.controller.searchable !== false) {
556 self.searchview.ready.then(self.searchview.do_search);
558 self.trigger("controller_inited",view_type,controller);
561 set_title: function(title) {
562 this.$el.find('.oe_view_title_text:first').text(title);
564 add_breadcrumb: function(on_reverse_breadcrumb) {
566 var views = [this.active_view || this.views_src[0].view_type];
567 this.on('switch_mode', self, function(mode) {
568 var last = views.slice(-1)[0];
570 if (mode !== 'form') {
576 this.getParent().push_breadcrumb({
579 show: function(index) {
580 var view_to_select = views[index];
581 var state = self.url_states[view_to_select];
582 self.do_push_state(state || {});
583 $.when(self.switch_mode(view_to_select)).then(function() {
587 get_title: function() {
590 _.each(self.getParent().breadcrumbs, function(bc, i) {
591 if (bc.widget === self) {
595 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
596 var titles = _.map(views, function(v) {
597 var controller = self.views[v].controller;
599 id = controller.datarecord.id;
601 return controller.get('title');
603 if (next && next.action && next.action.res_id && self.dataset &&
604 self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
605 // If the current active view is a formview and the next item in the breadcrumbs
606 // is an action on same object (model / res_id), then we omit the current formview's title
611 on_reverse_breadcrumb: on_reverse_breadcrumb,
615 * Returns to the view preceding the caller view in this manager's
616 * navigation history (the navigation history is appended to via
619 * @param {Object} [options]
620 * @param {Boolean} [options.created=false] resource was created
621 * @param {String} [options.default=null] view to switch to if no previous view
622 * @returns {$.Deferred} switching end signal
624 prev_view: function (options) {
625 options = options || {};
626 var current_view = this.views_history.pop();
627 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
628 if (options.created && current_view === 'form' && previous_view === 'list') {
629 // APR special case: "If creation mode from list (and only from a list),
630 // after saving, go to page view (don't come back in list)"
631 return this.switch_mode('form');
632 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
633 // APR special case: "If creation from dashboard, we have no previous view
634 return this.switch_mode('form');
636 return this.switch_mode(previous_view, true);
639 * Sets up the current viewmanager's search view.
641 * @param {Number|false} view_id the view to use or false for a default one
642 * @returns {jQuery.Deferred} search view startup deferred
644 setup_search_view: function(view_id, search_defaults) {
646 if (this.searchview) {
647 this.searchview.destroy();
649 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
651 this.searchview.on('search_data', self, this.do_searchview_search);
652 return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
654 do_searchview_search: function(domains, contexts, groupbys) {
656 controller = this.views[this.active_view].controller,
657 action_context = this.action.context || {};
658 this.rpc('/web/session/eval_domain_and_context', {
659 domains: [this.action.domain || []].concat(domains || []),
660 contexts: [action_context].concat(contexts || []),
661 group_by_seq: groupbys || []
662 }).then(function (results) {
663 self.dataset._model = new instance.web.Model(
664 self.dataset.model, results.context, results.domain);
665 var groupby = results.group_by.length
667 : action_context.group_by;
668 if (_.isString(groupby)) {
671 controller.do_search(results.domain, results.context, groupby || []);
675 * Called when one of the view want to execute an action
677 on_action: function(action) {
679 on_create: function() {
681 on_remove: function() {
683 on_edit: function() {
686 * Called by children view after executing an action
688 on_action_executed: function () {
692 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
693 template:"ViewManagerAction",
695 * @constructs instance.web.ViewManagerAction
696 * @extends instance.web.ViewManager
698 * @param {instance.web.ActionManager} parent parent object/widget
699 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
701 init: function(parent, action) {
702 // dataset initialization will take the session from ``this``, so if we
703 // do not have it yet (and we don't, because we've not called our own
704 // ``_super()``) rpc requests will blow up.
705 var flags = action.flags || {};
706 if (!('auto_search' in flags)) {
707 flags.auto_search = action.auto_search !== false;
709 if (action.res_model == 'board.board' && action.view_mode === 'form') {
710 // Special case for Dashboards
712 views_switcher : false,
713 display_title : false,
717 action_buttons : false
720 this._super(parent, null, action.views, flags);
721 this.session = parent.session;
722 this.action = action;
723 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
725 dataset.ids.push(action.res_id);
728 this.dataset = dataset;
730 // setup storage for session-wise menu hiding
731 if (this.session.hidden_menutips) {
734 this.session.hidden_menutips = {};
737 * Initializes the ViewManagerAction: sets up the searchview (if the
738 * searchview is enabled in the manager's action flags), calls into the
739 * parent to initialize the primary view and (if the VMA has a searchview)
740 * launches an initial search after both views are done rendering.
745 search_defaults = {};
746 _.each(this.action.context, function (value, key) {
747 var match = /^search_default_(.*)$/.exec(key);
749 search_defaults[match[1]] = value;
753 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
755 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
757 var main_view_loaded = this._super();
759 var manager_ready = $.when(searchview_loaded, main_view_loaded);
761 this.$el.find('.oe_debug_view').change(this.on_debug_changed);
762 this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
763 return manager_ready;
765 on_debug_changed: function (evt) {
767 $sel = $(evt.currentTarget),
768 $option = $sel.find('option:selected'),
770 current_view = this.views[this.active_view].controller;
773 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
774 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
780 type : 'ir.actions.act_url',
781 url: '/web/static/test/test.html'
785 var ids = current_view.get_selected_ids();
786 if (ids.length === 1) {
787 this.dataset.call('perm_read', [ids]).then(function(result) {
788 var dialog = new instance.web.Dialog(this, {
789 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
791 }, QWeb.render('ViewManagerDebugViewLog', {
793 format : instance.web.format_value
798 case 'toggle_layout_outline':
799 current_view.rendering_engine.toggle_layout_debugging();
803 name: "Technical Translation",
804 res_model : 'ir.translation',
805 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
806 views: [[false, 'list'], [false, 'form']],
807 type : 'ir.actions.act_window',
813 this.dataset.call('fields_get', [false, {}]).then(function (fields) {
814 var $root = $('<dl>');
815 _(fields).each(function (attributes, name) {
816 $root.append($('<dt>').append($('<h4>').text(name)));
817 var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
818 _(attributes).each(function (def, name) {
819 if (def instanceof Object) {
820 def = JSON.stringify(def);
823 .append($('<dt>').text(name))
824 .append($('<dd style="white-space: pre-wrap;">').text(def));
827 new instance.web.Dialog(self, {
828 title: _.str.sprintf(_t("Model %s fields"),
830 width: '95%'}, $root).open();
833 case 'edit_workflow':
834 return this.do_action({
835 res_model : 'workflow',
836 domain : [['osv', '=', this.dataset.model]],
837 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
838 type : 'ir.actions.act_window',
844 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
846 case 'manage_filters':
848 res_model: 'ir.filters',
849 views: [[false, 'list'], [false, 'form']],
850 type: 'ir.actions.act_window',
852 search_default_my_filters: true,
853 search_default_model_id: this.dataset.model
857 case 'print_workflow':
858 if (current_view.get_selected_ids && current_view.get_selected_ids().length == 1) {
859 instance.web.blockUI();
861 context: { active_ids: current_view.get_selected_ids() },
862 report_name: "workflow.instance.graph",
864 model: this.dataset.model,
865 id: current_view.get_selected_ids()[0],
869 this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
874 console.log("No debug handler for ", val);
877 evt.currentTarget.selectedIndex = 0;
879 do_edit_resource: function(model, id, action) {
880 var action = _.extend({
883 type : 'ir.actions.act_window',
886 views : [[false, 'form']],
889 action_buttons : true,
891 resize_textareas : true
895 this.do_action(action);
897 switch_mode: function (view_type, no_store, options) {
900 return $.when(this._super.apply(this, arguments)).then(function () {
901 var controller = self.views[self.active_view].controller,
902 fvg = controller.fields_view,
903 view_id = (fvg && fvg.view_id) || '--';
904 self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
911 do_create_view: function(view_type) {
912 var r = this._super.apply(this, arguments);
913 var view = this.views[view_type].controller;
914 view.set({ 'title': this.action.name });
917 set_title: function(title) {
918 this.$el.find('.oe_breadcrumb_title:first').html(this.getParent().get_title());
920 do_push_state: function(state) {
921 if (this.getParent() && this.getParent().do_push_state) {
922 state["view_type"] = this.active_view;
923 this.url_states[this.active_view] = state;
924 this.getParent().do_push_state(state);
927 do_load_state: function(state, warm) {
930 if (state.view_type && state.view_type !== this.active_view) {
932 this.views[this.active_view].deferred.pipe(function() {
933 return self.switch_mode(state.view_type, true);
938 $.when(defs).then(function() {
939 self.views[self.active_view].controller.do_load_state(state, warm);
944 instance.web.Sidebar = instance.web.Widget.extend({
945 init: function(parent) {
948 var view = this.getParent();
950 { 'name' : 'print', 'label' : _t('Print'), },
951 { 'name' : 'other', 'label' : _t('More'), }
957 this.fileupload_id = _.uniqueId('oe_fileupload');
958 $(window).on(this.fileupload_id, function() {
959 var args = [].slice.call(arguments).slice(1);
960 if (args[0] && args[0].error) {
961 alert(args[0].error);
963 self.do_attachement_update(self.dataset, self.model_id);
965 instance.web.unblockUI();
972 this.$el.on('click','.oe_dropdown_menu li a', function(event) {
973 var section = $(this).data('section');
974 var index = $(this).data('index');
975 var item = self.items[section][index];
977 item.callback.apply(self, [item]);
978 } else if (item.action) {
979 self.on_item_action_clicked(item);
980 } else if (item.url) {
983 event.preventDefault();
988 self.$el.html(QWeb.render('Sidebar', {widget: self}));
990 // Hides Sidebar sections when item list is empty
991 this.$('.oe_form_dropdown_section').each(function() {
992 $(this).toggle(!!$(this).find('li').length);
996 * For each item added to the section:
999 * will be used as the item's name in the sidebar, can be html
1002 * descriptor for the action which will be executed, ``action`` and
1003 * ``callback`` should be exclusive
1006 * function to call when the item is clicked in the sidebar, called
1007 * with the item descriptor as its first argument (so information
1008 * can be stored as additional keys on the object passed to
1011 * ``classname`` (optional)
1012 * ``@class`` set on the sidebar serialization of the item
1014 * ``title`` (optional)
1015 * will be set as the item's ``@title`` (tooltip)
1017 * @param {String} section_code
1018 * @param {Array<{label, action | callback[, classname][, title]}>} items
1020 add_items: function(section_code, items) {
1023 this.items[section_code].push.apply(this.items[section_code],items);
1027 add_toolbar: function(toolbar) {
1029 _.each(['print','action','relate'], function(type) {
1030 var items = toolbar[type];
1032 for (var i = 0; i < items.length; i++) {
1034 label: items[i]['name'],
1036 classname: 'oe_sidebar_' + type
1039 self.add_items(type=='print' ? 'print' : 'other', items);
1043 on_item_action_clicked: function(item) {
1045 self.getParent().sidebar_context().then(function (context) {
1046 var ids = self.getParent().get_selected_ids();
1047 if (ids.length == 0) {
1048 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1051 var additional_context = _.extend({
1054 active_model: self.getParent().dataset.model
1056 self.rpc("/web/action/load", {
1057 action_id: item.action.id,
1058 context: additional_context
1059 }).then(function(result) {
1060 result.context = _.extend(result.context || {},
1061 additional_context);
1062 result.flags = result.flags || {};
1063 result.flags.new_window = true;
1064 self.do_action(result, function () {
1066 self.getParent().reload();
1071 do_attachement_update: function(dataset, model_id) {
1072 this.dataset = dataset;
1073 this.model_id = model_id;
1075 this.on_attachments_loaded([]);
1077 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1078 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1079 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
1082 on_attachments_loaded: function(attachments) {
1085 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
1086 _.each(attachments,function(a) {
1088 if(a.type === "binary") {
1089 a.url = prefix + a.id + '&t=' + (new Date().getTime());
1092 self.items['files'] = attachments;
1094 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1095 this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1097 on_attachment_changed: function(e) {
1098 var $e = $(e.target);
1099 if ($e.val() !== '') {
1100 this.$el.find('form.oe_form_binary_form').submit();
1101 $e.parent().find('input[type=file]').prop('disabled', true);
1102 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1103 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1104 instance.web.blockUI();
1107 on_attachment_delete: function(e) {
1110 e.stopPropagation();
1112 var $e = $(e.currentTarget);
1113 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1114 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1115 self.do_attachement_update(self.dataset, self.model_id);
1121 instance.web.View = instance.web.Widget.extend({
1122 // name displayed in view switchers
1125 * Define a view type for each view to allow automatic call to fields_view_get.
1127 view_type: undefined,
1128 init: function(parent, dataset, view_id, options) {
1129 this._super(parent);
1130 this.dataset = dataset;
1131 this.view_id = view_id;
1132 this.set_default_options(options);
1134 start: function () {
1135 return this.load_view();
1137 load_view: function() {
1139 if (this.embedded_view) {
1140 var def = $.Deferred();
1141 $.async_when().then(function() {def.resolve(self.embedded_view);});
1142 return def.pipe(function(r) {
1143 self.trigger('view_loaded', r);
1146 var context = new instance.web.CompoundContext(this.dataset.get_context());
1147 if (! this.view_type)
1148 console.warn("view_type is not defined", this);
1149 return this.rpc("/web/view/load", {
1150 "model": this.dataset.model,
1151 "view_id": this.view_id,
1152 "view_type": this.view_type,
1153 toolbar: !!this.options.$sidebar,
1155 }).pipe(function(r) {
1156 self.trigger('view_loaded', r);
1160 set_default_options: function(options) {
1161 this.options = options || {};
1162 _.defaults(this.options, {
1163 // All possible views options should be defaulted here
1167 action_views_ids: {}
1171 * Fetches and executes the action identified by ``action_data``.
1173 * @param {Object} action_data the action descriptor data
1174 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1175 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1176 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1177 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1178 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1179 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1180 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1182 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1184 var result_handler = function () {
1185 if (on_closed) { on_closed.apply(null, arguments); }
1186 if (self.getParent() && self.getParent().on_action_executed) {
1187 return self.getParent().on_action_executed.apply(null, arguments);
1190 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1192 var handler = function (r) {
1194 if (action && action.constructor == Object) {
1195 var ncontext = new instance.web.CompoundContext(context);
1198 active_id: record_id,
1199 active_ids: [record_id],
1200 active_model: dataset.model
1203 ncontext.add(action.context || {});
1204 return self.rpc('/web/session/eval_domain_and_context', {
1205 contexts: [ncontext],
1207 }).pipe(function (results) {
1208 action.context = results.context;
1209 /* niv: previously we were overriding once more with action_data.context,
1210 * I assumed this was not a correct behavior and removed it
1212 return self.do_action(action, result_handler);
1215 return result_handler();
1219 if (action_data.special) {
1220 return handler({"type":"ir.actions.act_window_close"});
1221 } else if (action_data.type=="object") {
1222 var args = [[record_id]], additional_args = [];
1223 if (action_data.args) {
1225 // Warning: quotes and double quotes problem due to json and xml clash
1226 // Maybe we should force escaping in xml or do a better parse of the args array
1227 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1228 args = args.concat(additional_args);
1230 console.error("Could not JSON.parse arguments", action_data.args);
1234 return dataset.call_button(action_data.name, args).then(handler);
1235 } else if (action_data.type=="action") {
1236 return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).then(handler);
1238 return dataset.exec_workflow(record_id, action_data.name).then(handler);
1242 * Directly set a view to use instead of calling fields_view_get. This method must
1243 * be called before start(). When an embedded view is set, underlying implementations
1244 * of instance.web.View must use the provided view instead of any other one.
1246 * @param embedded_view A view.
1248 set_embedded_view: function(embedded_view) {
1249 this.embedded_view = embedded_view;
1251 do_show: function () {
1254 do_hide: function () {
1257 do_push_state: function(state) {
1258 if (this.getParent() && this.getParent().do_push_state) {
1259 this.getParent().do_push_state(state);
1262 do_load_state: function(state, warm) {
1265 * Switches to a specific view type
1267 * @param {String} view view type to switch to
1269 do_switch_view: function(view) {
1270 this.trigger('switch_mode',view);
1273 * Cancels the switch to the current view, switches to the previous one
1275 * @param {Object} [options]
1276 * @param {Boolean} [options.created=false] resource was created
1277 * @param {String} [options.default=null] view to switch to if no previous view
1280 do_search: function(view) {
1282 on_sidebar_export: function() {
1283 new instance.web.DataExport(this, this.dataset).open();
1285 sidebar_context: function () {
1289 * Asks the view to reload itself, if the reloading is asynchronous should
1290 * return a {$.Deferred} indicating when the reloading is done.
1292 reload: function () {
1296 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1297 * An action is disabled by setting the corresponding attribute in the view's main element,
1298 * like: <form string="" create="false" edit="false" delete="false">
1300 is_action_enabled: function(action) {
1301 var attrs = this.fields_view.arch.attrs;
1302 return (action in attrs) ? JSON.parse(attrs[action]) : true;
1306 instance.web.xml_to_json = function(node) {
1307 switch (node.nodeType) {
1313 var attrs = $(node).getAttributes();
1314 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1317 attrs[key] = JSON.parse(attrs[key]);
1322 tag: node.tagName.toLowerCase(),
1324 children: _.map(node.childNodes, instance.web.xml_to_json)
1328 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1329 // For debugging purpose, this function will convert a json node back to xml
1330 indent = indent || 0;
1331 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1332 r = sindent + '<' + node.tag,
1333 cr = human_readable ? '\n' : '';
1335 if (typeof(node) === 'string') {
1336 return sindent + node;
1337 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1339 _.str.sprintf("Node [%s] is not a JSONified XML node",
1340 JSON.stringify(node)));
1342 for (var attr in node.attrs) {
1343 var vattr = node.attrs[attr];
1344 if (typeof(vattr) !== 'string') {
1346 vattr = JSON.stringify(vattr);
1348 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1349 if (human_readable) {
1350 vattr = vattr.replace(/"/g, "'");
1352 r += ' ' + attr + '="' + vattr + '"';
1354 if (node.children && node.children.length) {
1357 for (var i = 0, ii = node.children.length; i < ii; i++) {
1358 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1360 r += childs.join(cr);
1361 r += cr + sindent + '</' + node.tag + '>';
1367 instance.web.xml_to_str = function(node) {
1368 if (window.ActiveXObject) {
1371 return (new XMLSerializer()).serializeToString(node);
1374 instance.web.str_to_xml = function(s) {
1375 if (window.DOMParser) {
1376 var dp = new DOMParser();
1377 var r = dp.parseFromString(s, "text/xml");
1378 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1379 throw new Error("Could not parse string to xml");
1385 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1387 throw new Error("Could not find a DOM Parser: " + e.message);
1390 xDoc.preserveWhiteSpace = true;
1396 * Registry for all the main views
1398 instance.web.views = new instance.web.Registry();
1402 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: