1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
7 var instance = openerp;
8 openerp.web.views = {};
9 var QWeb = instance.web.qweb,
12 instance.web.ActionManager = instance.web.Widget.extend({
13 init: function(parent) {
15 this.inner_action = null;
16 this.inner_widget = null;
18 this.dialog_widget = null;
19 this.breadcrumbs = [];
20 this.on('history_back', this, function() {
21 return this.history_back();
25 this._super.apply(this, arguments);
26 this.$el.on('click', 'a.oe_breadcrumb_item', this.on_breadcrumb_clicked);
28 dialog_stop: function (reason) {
30 this.dialog.destroy(reason);
35 * Add a new item to the breadcrumb
37 * If the title of an item is an array, the multiple title mode is in use.
38 * (eg: a widget with multiple views might need to display a title for each view)
39 * In multiple title mode, the show() callback can check the index it receives
40 * in order to detect which of its titles has been clicked on by the user.
42 * @param {Object} item breadcrumb item
43 * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
44 * @param {Function} [item.show] triggered whenever the widget should be shown back
45 * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
46 * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
47 * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
48 * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
50 push_breadcrumb: function(item) {
51 var last = this.breadcrumbs.slice(-1)[0];
56 show: function(index) {
57 this.widget.$el.show();
60 this.widget.$el.hide();
63 this.widget.destroy();
65 get_title: function() {
66 return this.title || this.widget.get('title');
69 item.id = _.uniqueId('breadcrumb_');
70 this.breadcrumbs.push(item);
72 history_back: function() {
73 var last = this.breadcrumbs.slice(-1)[0];
77 var title = last.get_title();
78 if (_.isArray(title) && title.length > 1) {
79 return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
80 } else if (this.breadcrumbs.length === 1) {
81 // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
84 var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
85 title = prev.get_title();
86 return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
89 on_breadcrumb_clicked: function(ev) {
90 var $e = $(ev.target);
91 var id = $e.data('id');
93 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
94 if (this.breadcrumbs[i].id == id) {
99 var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
100 this.select_breadcrumb(index, subindex);
102 select_breadcrumb: function(index, subindex) {
103 var next_item = this.breadcrumbs[index + 1];
104 if (next_item && next_item.on_reverse_breadcrumb) {
105 next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
107 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
109 if (this.remove_breadcrumb(i) === false) {
114 var item = this.breadcrumbs[index];
116 this.inner_widget = item.widget;
117 this.inner_action = item.action;
120 clear_breadcrumbs: function() {
121 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
122 if (this.remove_breadcrumb(0) === false) {
127 remove_breadcrumb: function(index) {
128 var item = this.breadcrumbs.splice(index, 1)[0];
130 var dups = _.filter(this.breadcrumbs, function(it) {
131 return item.widget === it.widget;
134 if (this.getParent().has_uncommitted_changes()) {
135 this.inner_widget = item.widget;
136 this.inner_action = item.action;
137 this.breadcrumbs.splice(index, 0, item);
144 var last_widget = this.breadcrumbs.slice(-1)[0];
146 this.inner_widget = last_widget.widget;
147 this.inner_action = last_widget.action;
150 add_breadcrumb_url: function (url, label) {
151 // Add a pseudo breadcrumb that will redirect to an url
152 this.push_breadcrumb({
154 instance.web.redirect(url);
157 destroy: function() {},
158 get_title: function() {
163 get_title: function() {
165 for (var i = 0; i < this.breadcrumbs.length; i += 1) {
166 var item = this.breadcrumbs[i];
167 var tit = item.get_title();
168 if (item.hide_breadcrumb) {
171 if (!_.isArray(tit)) {
174 for (var j = 0; j < tit.length; j += 1) {
175 var label = _.escape(tit[j]);
176 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
177 titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
179 titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
183 return titles.join(' <span class="oe_fade">/</span> ');
185 do_push_state: function(state) {
187 if (this.getParent() && this.getParent().do_push_state) {
188 if (this.inner_action) {
189 if (this.inner_action._push_me === false) {
190 // this action has been explicitly marked as not pushable
193 state['title'] = this.inner_action.name;
194 if(this.inner_action.type == 'ir.actions.act_window') {
195 state['model'] = this.inner_action.res_model;
197 if (this.inner_action.menu_id) {
198 state['menu_id'] = this.inner_action.menu_id;
200 if (this.inner_action.id) {
201 state['action'] = this.inner_action.id;
202 } else if (this.inner_action.type == 'ir.actions.client') {
203 state['action'] = this.inner_action.tag;
205 _.each(this.inner_action.params, function(v, k) {
206 if(_.isString(v) || _.isNumber(v)) {
210 state = _.extend(params || {}, state);
212 if (this.inner_action.context) {
213 var active_id = this.inner_action.context.active_id;
215 state["active_id"] = active_id;
217 var active_ids = this.inner_action.context.active_ids;
218 if (active_ids && !(active_ids.length === 1 && active_ids[0] === active_id)) {
219 // We don't push active_ids if it's a single element array containing the active_id
220 // This makes the url shorter in most cases.
221 state["active_ids"] = this.inner_action.context.active_ids.join(',');
226 this.getParent().do_push_state(state);
230 do_load_state: function(state, warm) {
233 if (!warm && 'return_label' in state) {
234 var return_url = state.return_url || document.referrer;
236 this.add_breadcrumb_url(return_url, state.return_label);
240 if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
241 var action_client = {
242 type: "ir.actions.client",
245 _push_me: state._push_me,
250 action_loaded = this.do_action(action_client);
252 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
254 var add_context = {};
255 if (state.active_id) {
256 add_context.active_id = state.active_id;
258 if (state.active_ids) {
259 // The jQuery BBQ plugin does some parsing on values that are valid integers.
260 // It means that if there's only one item, it will do parseInt() on it,
261 // otherwise it will keep the comma seperated list as string.
262 add_context.active_ids = state.active_ids.toString().split(',').map(function(id) {
263 return parseInt(id, 10) || id;
265 } else if (state.active_id) {
266 add_context.active_ids = [state.active_id];
268 add_context.params = state;
272 action_loaded = this.do_action(state.action, { additional_context: add_context });
273 $.when(action_loaded || null).done(function() {
274 instance.webclient.menu.has_been_loaded.done(function() {
275 if (self.inner_action && self.inner_action.id) {
276 instance.webclient.menu.open_action(self.inner_action.id);
282 } else if (state.model && state.id) {
283 // TODO handle context & domain ?
288 res_model: state.model,
290 type: 'ir.actions.act_window',
291 views: [[false, 'form']]
293 action_loaded = this.do_action(action);
294 } else if (state.sa) {
295 // load session action
299 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).then(function(action) {
301 return self.do_action(action);
306 $.when(action_loaded || null).done(function() {
307 if (self.inner_widget && self.inner_widget.do_load_state) {
308 self.inner_widget.do_load_state(state, warm);
313 * Execute an OpenERP action
315 * @param {Number|String|Object} Can be either an action id, a client action or an action descriptor.
316 * @param {Object} [options]
317 * @param {Boolean} [options.clear_breadcrumbs=false] Clear the breadcrumbs history list
318 * @param {Function} [options.on_reverse_breadcrumb] Callback to be executed whenever an anterior breadcrumb item is clicked on.
319 * @param {Function} [options.hide_breadcrumb] Do not display this widget's title in the breadcrumb
320 * @param {Function} [options.on_close] Callback to be executed when the dialog is closed (only relevant for target=new actions)
321 * @param {Function} [options.action_menu_id] Manually set the menu id on the fly.
322 * @param {Object} [options.additional_context] Additional context to be merged with the action's context.
323 * @return {jQuery.Deferred} Action loaded
325 do_action: function(action, options) {
326 options = _.defaults(options || {}, {
327 clear_breadcrumbs: false,
328 on_reverse_breadcrumb: function() {},
329 hide_breadcrumb: false,
330 on_close: function() {},
331 action_menu_id: null,
332 additional_context: {},
335 if (action === false) {
336 action = { type: 'ir.actions.act_window_close' };
337 } else if (_.isString(action) && instance.web.client_actions.contains(action)) {
338 var action_client = { type: "ir.actions.client", tag: action, params: {} };
339 return this.do_action(action_client, options);
340 } else if (_.isNumber(action) || _.isString(action)) {
342 return self.rpc("/web/action/load", { action_id: action }).then(function(result) {
343 return self.do_action(result, options);
347 // Ensure context & domain are evaluated and can be manipulated/used
348 var ncontext = new instance.web.CompoundContext(options.additional_context, action.context || {});
349 action.context = instance.web.pyeval.eval('context', ncontext);
350 if (action.context.active_id || action.context.active_ids) {
351 // Here we assume that when an `active_id` or `active_ids` is used
352 // in the context, we are in a `related` action, so we disable the
353 // searchview's default custom filters.
354 action.context.search_disable_custom_filters = true;
357 action.domain = instance.web.pyeval.eval(
358 'domain', action.domain, action.context || {});
362 console.error("No type for action", action);
363 return $.Deferred().reject();
365 var type = action.type.replace(/\./g,'_');
366 var popup = action.target === 'new';
367 var inline = action.target === 'inline' || action.target === 'inlineview';
368 action.flags = _.defaults(action.flags || {}, {
369 views_switcher : !popup && !inline,
370 search_view : !popup && !inline,
371 action_buttons : !popup && !inline,
372 sidebar : !popup && !inline,
373 pager : !popup && !inline,
374 display_title : !popup,
375 search_disable_custom_filters: action.context && action.context.search_disable_custom_filters
377 action.menu_id = options.action_menu_id;
378 if (!(type in this)) {
379 console.error("Action manager can't handle action of type " + action.type, action);
380 return $.Deferred().reject();
382 return this[type](action, options);
384 null_action: function() {
386 this.clear_breadcrumbs();
390 * @param {Object} executor
391 * @param {Object} executor.action original action
392 * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
393 * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
394 * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
395 * @param {Object} options
398 ir_actions_common: function(executor, options) {
399 if (this.inner_widget && executor.action.target !== 'new') {
400 if (this.getParent().has_uncommitted_changes()) {
401 return $.Deferred().reject();
402 } else if (options.clear_breadcrumbs) {
403 this.clear_breadcrumbs();
406 var widget = executor.widget();
407 if (executor.action.target === 'new') {
408 if (this.dialog_widget && !this.dialog_widget.isDestroyed()) {
409 this.dialog_widget.destroy();
411 this.dialog_stop(executor.action);
412 this.dialog = new instance.web.Dialog(this, {
413 dialogClass: executor.klass,
415 this.dialog.on("closing", null, options.on_close);
416 this.dialog.dialog_title = executor.action.name;
417 if (widget instanceof instance.web.ViewManager) {
418 _.extend(widget.flags, {
419 $buttons: this.dialog.$buttons,
420 footer_to_buttons: true,
423 this.dialog_widget = widget;
424 this.dialog_widget.setParent(this.dialog);
425 var initialized = this.dialog_widget.appendTo(this.dialog.$el);
429 this.dialog_stop(executor.action);
430 this.inner_action = executor.action;
431 this.inner_widget = widget;
432 executor.post_process(widget);
433 return this.inner_widget.appendTo(this.$el);
436 ir_actions_act_window: function (action, options) {
439 return this.ir_actions_common({
440 widget: function () { return new instance.web.ViewManagerAction(self, action); },
442 klass: 'oe_act_window',
443 post_process: function (widget) {
444 widget.add_breadcrumb({
445 on_reverse_breadcrumb: options.on_reverse_breadcrumb,
446 hide_breadcrumb: options.hide_breadcrumb,
451 ir_actions_client: function (action, options) {
453 var ClientWidget = instance.web.client_actions.get_object(action.tag);
455 if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
457 if ((next = ClientWidget(this, action))) {
458 return this.do_action(next, options);
463 return this.ir_actions_common({
464 widget: function () { return new ClientWidget(self, action); },
466 klass: 'oe_act_client',
467 post_process: function(widget) {
468 self.push_breadcrumb({
471 on_reverse_breadcrumb: options.on_reverse_breadcrumb,
472 hide_breadcrumb: options.hide_breadcrumb,
474 if (action.tag !== 'reload') {
475 self.do_push_state({});
480 ir_actions_act_window_close: function (action, options) {
487 ir_actions_server: function (action, options) {
489 this.rpc('/web/action/run', {
490 action_id: action.id,
491 context: action.context || {}
492 }).done(function (action) {
493 self.do_action(action, options);
496 ir_actions_report_xml: function(action, options) {
498 instance.web.blockUI();
499 return instance.web.pyeval.eval_domains_and_contexts({
500 contexts: [action.context],
502 }).then(function(res) {
503 action = _.clone(action);
504 action.context = res.context;
506 // iOS devices doesn't allow iframe use the way we do it,
507 // opening a new window seems the best way to workaround
508 if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
510 action: JSON.stringify(action),
511 token: new Date().getTime()
513 var url = self.session.url('/web/report', params);
514 instance.web.unblockUI();
515 $('<a href="'+url+'" target="_blank"></a>')[0].click();
519 var c = instance.webclient.crashmanager;
520 return $.Deferred(function (d) {
521 self.session.get_file({
523 data: {action: JSON.stringify(action)},
524 complete: instance.web.unblockUI,
533 c.rpc_error.apply(c, arguments);
540 ir_actions_act_url: function (action) {
541 if (action.target === 'self') {
542 instance.web.redirect(action.url);
544 window.open(action.url, '_blank');
550 instance.web.ViewManager = instance.web.Widget.extend({
551 template: "ViewManager",
552 init: function(parent, dataset, views, flags) {
554 this.url_states = {};
555 this.model = dataset ? dataset.model : undefined;
556 this.dataset = dataset;
557 this.searchview = null;
558 this.active_view = null;
559 this.views_src = _.map(views, function(x) {
560 if (x instanceof Array) {
561 var view_type = x[1];
562 var View = instance.web.views.get_object(view_type, true);
563 var view_label = View ? View.prototype.display_name : (void 'nope');
566 view_type: view_type,
568 button_label: View ? _.str.sprintf(_t('%(view_type)s view'), {'view_type': (view_label || view_type)}) : (void 'nope'),
574 this.ActionManager = parent;
576 this.flags = flags || {};
577 this.registry = instance.web.views;
578 this.views_history = [];
579 this.view_completely_inited = $.Deferred();
582 * @returns {jQuery.Deferred} initial view loading promise
587 this.$el.find('.oe_view_manager_switch a').click(function() {
588 self.switch_mode($(this).data('view-type'));
591 _.each(this.views_src, function(view) {
592 self.views[view.view_type] = $.extend({}, view, {
593 deferred : $.Deferred(),
596 $buttons : self.$el.find('.oe_view_manager_buttons'),
597 $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
598 $pager : self.$el.find('.oe_view_manager_pager'),
599 action : self.action,
600 action_views_ids : views_ids
601 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
604 views_ids[view.view_type] = view.view_id;
606 if (this.flags.views_switcher === false) {
607 this.$el.find('.oe_view_manager_switch').hide();
609 // If no default view defined, switch to the first one in sequence
610 var default_view = this.flags.default_view || this.views_src[0].view_type;
613 return this.switch_mode(default_view, null, this.flags[default_view] && this.flags[default_view].options);
617 switch_mode: function(view_type, no_store, view_options) {
619 var view = this.views[view_type];
621 var form = this.views['form'];
622 if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
623 self.trigger('switch_mode', view_type, no_store, view_options);
624 return $.Deferred().reject();
627 this.views_history.push(view_type);
629 this.active_view = view_type;
631 if (!view.controller) {
632 view_promise = this.do_create_view(view_type);
633 } else if (this.searchview
634 && self.flags.auto_search
635 && view.controller.searchable !== false) {
636 this.searchview.ready.done(this.searchview.do_search);
639 if (this.searchview) {
640 this.searchview[(view.controller.searchable === false || this.searchview.options.hidden) ? 'hide' : 'show']();
643 this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
645 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
646 .parent().addClass('active');
647 this.$el.attr("data-view-type", view_type);
648 return $.when(view_promise).done(function () {
649 _.each(_.keys(self.views), function(view_name) {
650 var controller = self.views[view_name].controller;
652 var container = self.$el.find("> .oe_view_manager_body > .oe_view_manager_view_" + view_name);
653 if (view_name === view_type) {
655 controller.do_show(view_options || {});
658 controller.do_hide();
662 self.trigger('switch_mode', view_type, no_store, view_options);
665 do_create_view: function(view_type) {
666 // Lazy loading of views
668 var view = this.views[view_type];
669 var viewclass = this.registry.get_object(view_type);
670 var options = _.clone(view.options);
671 if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
672 options.initial_mode = 'edit';
674 var controller = new viewclass(this, this.dataset, view.view_id, options);
676 controller.on('history_back', this, function() {
677 var am = self.getParent();
678 if (am && am.trigger) {
679 return am.trigger('history_back');
683 controller.on("change:title", this, function() {
684 if (self.active_view === view_type) {
685 self.set_title(controller.get('title'));
689 if (view.embedded_view) {
690 controller.set_embedded_view(view.embedded_view);
692 controller.on('switch_mode', self, this.switch_mode);
693 controller.on('previous_view', self, this.prev_view);
695 var container = this.$el.find("> .oe_view_manager_body > .oe_view_manager_view_" + view_type);
696 var view_promise = controller.appendTo(container);
697 this.views[view_type].controller = controller;
698 this.views[view_type].deferred.resolve(view_type);
699 return $.when(view_promise).done(function() {
701 && self.flags.auto_search
702 && view.controller.searchable !== false) {
703 self.searchview.ready.done(self.searchview.do_search);
705 self.view_completely_inited.resolve();
707 self.trigger("controller_inited",view_type,controller);
711 * @returns {Number|Boolean} the view id of the given type, false if not found
713 get_view_id: function(view_type) {
714 return this.views[view_type] && this.views[view_type].view_id || false;
716 set_title: function(title) {
717 this.$el.find('.oe_view_title_text:first').text(title);
719 add_breadcrumb: function(options) {
720 options = options || {};
722 var views = [this.active_view || this.views_src[0].view_type];
723 this.on('switch_mode', self, function(mode) {
724 var last = views.slice(-1)[0];
726 if (mode !== 'form') {
732 var item = _.extend({
735 show: function(index) {
736 var view_to_select = views[index];
737 var state = self.url_states[view_to_select];
738 self.do_push_state(state || {});
739 $.when(self.switch_mode(view_to_select)).done(function() {
743 get_title: function() {
746 _.each(self.getParent().breadcrumbs, function(bc, i) {
747 if (bc.widget === self) {
751 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
752 var titles = _.map(views, function(v) {
753 var controller = self.views[v].controller;
755 id = controller.datarecord.id;
757 return controller.get('title');
759 if (next && next.action && next.action.res_id && self.dataset &&
760 self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
761 // If the current active view is a formview and the next item in the breadcrumbs
762 // is an action on same object (model / res_id), then we omit the current formview's title
768 this.getParent().push_breadcrumb(item);
771 * Returns to the view preceding the caller view in this manager's
772 * navigation history (the navigation history is appended to via
775 * @param {Object} [options]
776 * @param {Boolean} [options.created=false] resource was created
777 * @param {String} [options.default=null] view to switch to if no previous view
778 * @returns {$.Deferred} switching end signal
780 prev_view: function (options) {
781 options = options || {};
782 var current_view = this.views_history.pop();
783 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
784 if (options.created && current_view === 'form' && previous_view === 'list') {
785 // APR special case: "If creation mode from list (and only from a list),
786 // after saving, go to page view (don't come back in list)"
787 return this.switch_mode('form');
788 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
789 // APR special case: "If creation from dashboard, we have no previous view
790 return this.switch_mode('form');
792 return this.switch_mode(previous_view, true);
795 * Sets up the current viewmanager's search view.
797 * @param {Number|false} view_id the view to use or false for a default one
798 * @returns {jQuery.Deferred} search view startup deferred
800 setup_search_view: function(view_id, search_defaults) {
802 if (this.searchview) {
803 this.searchview.destroy();
806 hidden: this.flags.search_view === false,
807 disable_custom_filters: this.flags.search_disable_custom_filters,
809 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, options);
811 this.searchview.on('search_data', self, this.do_searchview_search);
812 return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
814 do_searchview_search: function(domains, contexts, groupbys) {
816 controller = this.views[this.active_view].controller,
817 action_context = this.action.context || {};
818 instance.web.pyeval.eval_domains_and_contexts({
819 domains: [this.action.domain || []].concat(domains || []),
820 contexts: [action_context].concat(contexts || []),
821 group_by_seq: groupbys || []
822 }).done(function (results) {
825 _.str.sprintf(_t("Failed to evaluate search criterions")+": \n%s",
826 JSON.stringify(results.error)));
828 self.dataset._model = new instance.web.Model(
829 self.dataset.model, results.context, results.domain);
830 var groupby = results.group_by.length
832 : action_context.group_by;
833 if (_.isString(groupby)) {
836 $.when(controller.do_search(results.domain, results.context, groupby || [])).then(function() {
837 self.view_completely_inited.resolve();
842 * Called when one of the view want to execute an action
844 on_action: function(action) {
846 on_create: function() {
848 on_remove: function() {
850 on_edit: function() {
853 * Called by children view after executing an action
855 on_action_executed: function () {
859 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
860 template:"ViewManagerAction",
862 * @constructs instance.web.ViewManagerAction
863 * @extends instance.web.ViewManager
865 * @param {instance.web.ActionManager} parent parent object/widget
866 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
868 init: function(parent, action) {
869 // dataset initialization will take the session from ``this``, so if we
870 // do not have it yet (and we don't, because we've not called our own
871 // ``_super()``) rpc requests will blow up.
872 var flags = action.flags || {};
873 if (!('auto_search' in flags)) {
874 flags.auto_search = action.auto_search !== false;
876 if (action.res_model == 'board.board' && action.view_mode === 'form') {
877 // Special case for Dashboards
879 views_switcher : false,
880 display_title : false,
884 action_buttons : false
887 this._super(parent, null, action.views, flags);
888 this.session = parent.session;
889 this.action = action;
890 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
892 dataset.ids.push(action.res_id);
895 this.dataset = dataset;
898 * Initializes the ViewManagerAction: sets up the searchview (if the
899 * searchview is enabled in the manager's action flags), calls into the
900 * parent to initialize the primary view and (if the VMA has a searchview)
901 * launches an initial search after both views are done rendering.
906 search_defaults = {};
907 _.each(this.action.context, function (value, key) {
908 var match = /^search_default_(.*)$/.exec(key);
910 search_defaults[match[1]] = value;
914 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
916 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
918 var main_view_loaded = this._super();
920 var manager_ready = $.when(searchview_loaded, main_view_loaded, this.view_completely_inited);
922 this.$el.find('.oe_debug_view').change(this.on_debug_changed);
923 this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
924 return manager_ready;
926 on_debug_changed: function (evt) {
928 $sel = $(evt.currentTarget),
929 $option = $sel.find('option:selected'),
931 current_view = this.views[this.active_view].controller;
934 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
935 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
939 name: _t("JS Tests"),
941 type : 'ir.actions.act_url',
942 url: '/web/tests?mod=*'
946 var ids = current_view.get_selected_ids();
947 if (ids.length === 1) {
948 this.dataset.call('perm_read', [ids]).done(function(result) {
949 var dialog = new instance.web.Dialog(this, {
950 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
952 }, QWeb.render('ViewManagerDebugViewLog', {
954 format : instance.web.format_value
959 case 'toggle_layout_outline':
960 current_view.rendering_engine.toggle_layout_debugging();
963 current_view.open_defaults_dialog();
967 name: _t("Technical Translation"),
968 res_model : 'ir.translation',
969 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
970 views: [[false, 'list'], [false, 'form']],
971 type : 'ir.actions.act_window',
977 this.dataset.call('fields_get', [false, {}]).done(function (fields) {
978 var $root = $('<dl>');
979 _(fields).each(function (attributes, name) {
980 $root.append($('<dt>').append($('<h4>').text(name)));
981 var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
982 _(attributes).each(function (def, name) {
983 if (def instanceof Object) {
984 def = JSON.stringify(def);
987 .append($('<dt>').text(name))
988 .append($('<dd style="white-space: pre-wrap;">').text(def));
991 new instance.web.Dialog(self, {
992 title: _.str.sprintf(_t("Model %s fields"),
994 width: '95%'}, $root).open();
997 case 'edit_workflow':
998 return this.do_action({
999 res_model : 'workflow',
1000 domain : [['osv', '=', this.dataset.model]],
1001 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
1002 type : 'ir.actions.act_window',
1007 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
1009 case 'manage_filters':
1011 res_model: 'ir.filters',
1012 views: [[false, 'list'], [false, 'form']],
1013 type: 'ir.actions.act_window',
1015 search_default_my_filters: true,
1016 search_default_model_id: this.dataset.model
1020 case 'print_workflow':
1021 if (current_view.get_selected_ids && current_view.get_selected_ids().length == 1) {
1022 instance.web.blockUI();
1024 context: { active_ids: current_view.get_selected_ids() },
1025 report_name: "workflow.instance.graph",
1027 model: this.dataset.model,
1028 id: current_view.get_selected_ids()[0],
1032 this.session.get_file({
1034 data: {action: JSON.stringify(action)},
1035 complete: instance.web.unblockUI
1041 console.log("No debug handler for ", val);
1044 evt.currentTarget.selectedIndex = 0;
1046 do_edit_resource: function(model, id, action) {
1050 type : 'ir.actions.act_window',
1053 views : [[false, 'form']],
1056 action_buttons : true,
1058 resize_textareas : true
1062 this.do_action(action);
1064 switch_mode: function (view_type, no_store, options) {
1067 return this.alive($.when(this._super.apply(this, arguments))).done(function () {
1068 var controller = self.views[self.active_view].controller;
1069 self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
1076 do_create_view: function(view_type) {
1078 return this._super.apply(this, arguments).then(function() {
1079 var view = self.views[view_type].controller;
1080 view.set({ 'title': self.action.name });
1083 get_action_manager: function() {
1085 while ((cur = cur.getParent())) {
1086 if (cur instanceof instance.web.ActionManager) {
1092 set_title: function(title) {
1093 this.$el.find('.oe_breadcrumb_title:first').html(this.get_action_manager().get_title());
1095 do_push_state: function(state) {
1096 if (this.getParent() && this.getParent().do_push_state) {
1097 state["view_type"] = this.active_view;
1098 this.url_states[this.active_view] = state;
1099 this.getParent().do_push_state(state);
1102 do_load_state: function(state, warm) {
1105 if (state.view_type && state.view_type !== this.active_view) {
1107 this.views[this.active_view].deferred.then(function() {
1108 return self.switch_mode(state.view_type, true);
1113 $.when(defs).done(function() {
1114 self.views[self.active_view].controller.do_load_state(state, warm);
1119 instance.web.Sidebar = instance.web.Widget.extend({
1120 init: function(parent) {
1122 this._super(parent);
1123 var view = this.getParent();
1125 { 'name' : 'print', 'label' : _t('Print'), },
1126 { 'name' : 'other', 'label' : _t('More'), }
1132 this.fileupload_id = _.uniqueId('oe_fileupload');
1133 $(window).on(this.fileupload_id, function() {
1134 var args = [].slice.call(arguments).slice(1);
1135 self.do_attachement_update(self.dataset, self.model_id,args);
1136 instance.web.unblockUI();
1143 this.$el.on('click','.oe_dropdown_menu li a', function(event) {
1144 var section = $(this).data('section');
1145 var index = $(this).data('index');
1146 var item = self.items[section][index];
1147 if (item.callback) {
1148 item.callback.apply(self, [item]);
1149 } else if (item.action) {
1150 self.on_item_action_clicked(item);
1151 } else if (item.url) {
1154 event.preventDefault();
1157 redraw: function() {
1159 self.$el.html(QWeb.render('Sidebar', {widget: self}));
1161 // Hides Sidebar sections when item list is empty
1162 this.$('.oe_form_dropdown_section').each(function() {
1163 $(this).toggle(!!$(this).find('li').length);
1166 self.$("[title]").tipsy({
1172 * For each item added to the section:
1175 * will be used as the item's name in the sidebar, can be html
1178 * descriptor for the action which will be executed, ``action`` and
1179 * ``callback`` should be exclusive
1182 * function to call when the item is clicked in the sidebar, called
1183 * with the item descriptor as its first argument (so information
1184 * can be stored as additional keys on the object passed to
1187 * ``classname`` (optional)
1188 * ``@class`` set on the sidebar serialization of the item
1190 * ``title`` (optional)
1191 * will be set as the item's ``@title`` (tooltip)
1193 * @param {String} section_code
1194 * @param {Array<{label, action | callback[, classname][, title]}>} items
1196 add_items: function(section_code, items) {
1199 this.items[section_code].push.apply(this.items[section_code],items);
1203 add_toolbar: function(toolbar) {
1205 _.each(['print','action','relate'], function(type) {
1206 var items = toolbar[type];
1208 for (var i = 0; i < items.length; i++) {
1210 label: items[i]['name'],
1212 classname: 'oe_sidebar_' + type
1215 self.add_items(type=='print' ? 'print' : 'other', items);
1219 on_item_action_clicked: function(item) {
1221 self.getParent().sidebar_eval_context().done(function (sidebar_eval_context) {
1222 var ids = self.getParent().get_selected_ids();
1224 if (self.getParent().get_active_domain) {
1225 domain = self.getParent().get_active_domain();
1228 domain = $.Deferred().resolve(undefined);
1230 if (ids.length === 0) {
1231 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1234 var active_ids_context = {
1237 active_model: self.getParent().dataset.model,
1240 $.when(domain).done(function (domain) {
1241 if (domain !== undefined) {
1242 active_ids_context.active_domain = domain;
1244 var c = instance.web.pyeval.eval('context',
1245 new instance.web.CompoundContext(
1246 sidebar_eval_context, active_ids_context));
1248 self.rpc("/web/action/load", {
1249 action_id: item.action.id,
1251 }).done(function(result) {
1252 result.context = new instance.web.CompoundContext(
1253 result.context || {}, active_ids_context)
1254 .set_eval_context(c);
1255 result.flags = result.flags || {};
1256 result.flags.new_window = true;
1257 self.do_action(result, {
1258 on_close: function() {
1260 self.getParent().reload();
1267 do_attachement_update: function(dataset, model_id, args) {
1269 this.dataset = dataset;
1270 this.model_id = model_id;
1271 if (args && args[0].error) {
1272 this.do_warn(_t('Uploading Error'), args[0].error);
1275 this.on_attachments_loaded([]);
1277 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1278 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1279 ds.read_slice(['name', 'url', 'type', 'create_uid', 'create_date', 'write_uid', 'write_date'], {}).done(this.on_attachments_loaded);
1282 on_attachments_loaded: function(attachments) {
1285 var prefix = this.session.url('/web/binary/saveas', {model: 'ir.attachment', field: 'datas', filename_field: 'name'});
1286 _.each(attachments,function(a) {
1288 if(a.type === "binary") {
1289 a.url = prefix + '&id=' + a.id + '&t=' + (new Date().getTime());
1292 self.items['files'] = attachments;
1294 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1295 this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1297 on_attachment_changed: function(e) {
1298 var $e = $(e.target);
1299 if ($e.val() !== '') {
1300 this.$el.find('form.oe_form_binary_form').submit();
1301 $e.parent().find('input[type=file]').prop('disabled', true);
1302 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1303 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1304 instance.web.blockUI();
1307 on_attachment_delete: function(e) {
1309 e.stopPropagation();
1311 var $e = $(e.currentTarget);
1312 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1313 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).done(function() {
1314 self.do_attachement_update(self.dataset, self.model_id);
1320 instance.web.View = instance.web.Widget.extend({
1321 // name displayed in view switchers
1324 * Define a view type for each view to allow automatic call to fields_view_get.
1326 view_type: undefined,
1327 init: function(parent, dataset, view_id, options) {
1328 this._super(parent);
1329 this.ViewManager = parent;
1330 this.dataset = dataset;
1331 this.view_id = view_id;
1332 this.set_default_options(options);
1334 start: function () {
1335 return this.load_view();
1337 load_view: function(context) {
1339 var view_loaded_def;
1340 if (this.embedded_view) {
1341 view_loaded_def = $.Deferred();
1342 $.async_when().done(function() {
1343 view_loaded_def.resolve(self.embedded_view);
1346 if (! this.view_type)
1347 console.warn("view_type is not defined", this);
1348 view_loaded_def = instance.web.fields_view_get({
1349 "model": this.dataset._model,
1350 "view_id": this.view_id,
1351 "view_type": this.view_type,
1352 "toolbar": !!this.options.$sidebar,
1353 "context": this.dataset.get_context(),
1356 return this.alive(view_loaded_def).then(function(r) {
1357 self.fields_view = r;
1358 // add css classes that reflect the (absence of) access rights
1359 self.$el.addClass('oe_view')
1360 .toggleClass('oe_cannot_create', !self.is_action_enabled('create'))
1361 .toggleClass('oe_cannot_edit', !self.is_action_enabled('edit'))
1362 .toggleClass('oe_cannot_delete', !self.is_action_enabled('delete'));
1363 return $.when(self.view_loading(r)).then(function() {
1364 self.trigger('view_loaded', r);
1368 view_loading: function(r) {
1370 set_default_options: function(options) {
1371 this.options = options || {};
1372 _.defaults(this.options, {
1373 // All possible views options should be defaulted here
1377 action_views_ids: {}
1381 * Fetches and executes the action identified by ``action_data``.
1383 * @param {Object} action_data the action descriptor data
1384 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1385 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1386 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1387 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1388 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1389 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1390 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1392 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1394 var result_handler = function () {
1395 if (on_closed) { on_closed.apply(null, arguments); }
1396 if (self.getParent() && self.getParent().on_action_executed) {
1397 return self.getParent().on_action_executed.apply(null, arguments);
1400 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1403 var handler = function (action) {
1404 if (action && action.constructor == Object) {
1405 // filter out context keys that are specific to the current action.
1406 // Wrong default_* and search_default_* values will no give the expected result
1407 // Wrong group_by values will simply fail and forbid rendering of the destination view
1408 var ncontext = new instance.web.CompoundContext(
1409 _.object(_.reject(_.pairs(dataset.get_context().eval()), function(pair) {
1410 return pair[0].match('^(?:(?:default_|search_default_).+|.+_view_ref|group_by|group_by_no_leaf|active_id|active_ids)$') !== null;
1413 ncontext.add(action_data.context || {});
1414 ncontext.add({active_model: dataset.model});
1417 active_id: record_id,
1418 active_ids: [record_id],
1421 ncontext.add(action.context || {});
1422 action.context = ncontext;
1423 return self.do_action(action, {
1424 on_close: result_handler,
1427 self.do_action({"type":"ir.actions.act_window_close"});
1428 return result_handler();
1432 if (action_data.special === 'cancel') {
1433 return handler({"type":"ir.actions.act_window_close"});
1434 } else if (action_data.type=="object") {
1435 var args = [[record_id]], additional_args = [];
1436 if (action_data.args) {
1438 // Warning: quotes and double quotes problem due to json and xml clash
1439 // Maybe we should force escaping in xml or do a better parse of the args array
1440 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1441 args = args.concat(additional_args);
1443 console.error("Could not JSON.parse arguments", action_data.args);
1446 context.add({'active_model': dataset.model, 'active_ids': [record_id], 'active_id': record_id})
1448 return dataset.call_button(action_data.name, args).then(handler).then(function () {
1449 if (instance.webclient) {
1450 instance.webclient.menu.do_reload_needaction();
1453 } else if (action_data.type=="action") {
1454 return this.rpc('/web/action/load', {
1455 action_id: action_data.name,
1456 context: _.extend({'active_model': dataset.model, 'active_ids': dataset.ids, 'active_id': record_id}, instance.web.pyeval.eval('context', context)),
1460 return dataset.exec_workflow(record_id, action_data.name).then(handler);
1464 * Directly set a view to use instead of calling fields_view_get. This method must
1465 * be called before start(). When an embedded view is set, underlying implementations
1466 * of instance.web.View must use the provided view instead of any other one.
1468 * @param embedded_view A view.
1470 set_embedded_view: function(embedded_view) {
1471 this.embedded_view = embedded_view;
1473 do_show: function () {
1476 do_hide: function () {
1479 is_active: function () {
1480 var manager = this.getParent();
1481 return !manager || !manager.active_view
1482 || manager.views[manager.active_view].controller === this;
1484 * Wraps fn to only call it if the current view is the active one. If the
1485 * current view is not active, doesn't call fn.
1487 * fn can not return anything, as a non-call to fn can't return anything
1490 * @param {Function} fn function to wrap in the active guard
1492 guard_active: function (fn) {
1494 return function () {
1495 if (self.is_active()) {
1496 fn.apply(self, arguments);
1500 do_push_state: function(state) {
1501 if (this.getParent() && this.getParent().do_push_state) {
1502 this.getParent().do_push_state(state);
1505 do_load_state: function(state, warm) {
1508 * Switches to a specific view type
1510 do_switch_view: function() {
1511 this.trigger.apply(this, ['switch_mode'].concat(_.toArray(arguments)));
1514 * Cancels the switch to the current view, switches to the previous one
1516 * @param {Object} [options]
1517 * @param {Boolean} [options.created=false] resource was created
1518 * @param {String} [options.default=null] view to switch to if no previous view
1521 do_search: function(view) {
1523 on_sidebar_export: function() {
1524 new instance.web.DataExport(this, this.dataset).open();
1526 sidebar_eval_context: function () {
1530 * Asks the view to reload itself, if the reloading is asynchronous should
1531 * return a {$.Deferred} indicating when the reloading is done.
1533 reload: function () {
1537 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1538 * An action is disabled by setting the corresponding attribute in the view's main element,
1539 * like: <form string="" create="false" edit="false" delete="false">
1541 is_action_enabled: function(action) {
1542 var attrs = this.fields_view.arch.attrs;
1543 return (action in attrs) ? JSON.parse(attrs[action]) : true;
1548 * Performs a fields_view_get and apply postprocessing.
1549 * return a {$.Deferred} resolved with the fvg
1551 * @param {Object} args
1552 * @param {String|Object} args.model instance.web.Model instance or string repr of the model
1553 * @param {Object} [args.context] context if args.model is a string
1554 * @param {Number} [args.view_id] id of the view to be loaded, default view if null
1555 * @param {String} [args.view_type] type of view to be loaded if view_id is null
1556 * @param {Boolean} [args.toolbar=false] get the toolbar definition
1558 instance.web.fields_view_get = function(args) {
1559 function postprocess(fvg) {
1560 var doc = $.parseXML(fvg.arch).documentElement;
1561 fvg.arch = instance.web.xml_to_json(doc, (doc.nodeName.toLowerCase() !== 'kanban'));
1562 if ('id' in fvg.fields) {
1563 // Special case for id's
1564 var id_field = fvg.fields['id'];
1565 id_field.original_type = id_field.type;
1566 id_field.type = 'id';
1568 _.each(fvg.fields, function(field) {
1569 _.each(field.views || {}, function(view) {
1575 args = _.defaults(args, {
1578 var model = args.model;
1579 if (typeof model === 'string') {
1580 model = new instance.web.Model(args.model, args.context);
1582 return args.model.call('fields_view_get', [args.view_id, args.view_type, args.context, args.toolbar]).then(function(fvg) {
1583 return postprocess(fvg);
1587 instance.web.xml_to_json = function(node, strip_whitespace) {
1588 switch (node.nodeType) {
1590 return instance.web.xml_to_json(node.documentElement, strip_whitespace);
1593 return (strip_whitespace && node.data.trim() === '') ? undefined : node.data;
1595 var attrs = $(node).getAttributes();
1596 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1599 attrs[key] = JSON.parse(attrs[key]);
1604 tag: node.tagName.toLowerCase(),
1606 children: _.compact(_.map(node.childNodes, function(node) {
1607 return instance.web.xml_to_json(node, strip_whitespace);
1613 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1614 // For debugging purpose, this function will convert a json node back to xml
1615 indent = indent || 0;
1616 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1617 r = sindent + '<' + node.tag,
1618 cr = human_readable ? '\n' : '';
1620 if (typeof(node) === 'string') {
1621 return sindent + node;
1622 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1624 _.str.sprintf(_t("Node [%s] is not a JSONified XML node"),
1625 JSON.stringify(node)));
1627 for (var attr in node.attrs) {
1628 var vattr = node.attrs[attr];
1629 if (typeof(vattr) !== 'string') {
1631 vattr = JSON.stringify(vattr);
1633 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1634 if (human_readable) {
1635 vattr = vattr.replace(/"/g, "'");
1637 r += ' ' + attr + '="' + vattr + '"';
1639 if (node.children && node.children.length) {
1642 for (var i = 0, ii = node.children.length; i < ii; i++) {
1643 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1645 r += childs.join(cr);
1646 r += cr + sindent + '</' + node.tag + '>';
1652 instance.web.xml_to_str = function(node) {
1654 if (window.XMLSerializer) {
1655 str = (new XMLSerializer()).serializeToString(node);
1656 } else if (window.ActiveXObject) {
1659 throw new Error(_t("Could not serialize XML"));
1661 // Browsers won't deal with self closing tags except void elements:
1662 // http://www.w3.org/TR/html-markup/syntax.html
1663 var void_elements = 'area base br col command embed hr img input keygen link meta param source track wbr'.split(' ');
1665 // The following regex is a bit naive but it's ok for the xmlserializer output
1666 str = str.replace(/<([a-z]+)([^<>]*)\s*\/\s*>/g, function(match, tag, attrs) {
1667 if (void_elements.indexOf(tag) < 0) {
1668 return "<" + tag + attrs + "></" + tag + ">";
1677 * Registry for all the main views
1679 instance.web.views = new instance.web.Registry();
1683 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: