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.destroy();
31 * Add a new item to the breadcrumb
33 * If the title of an item is an array, the multiple title mode is in use.
34 * (eg: a widget with multiple views might need to display a title for each view)
35 * In multiple title mode, the show() callback can check the index it receives
36 * in order to detect which of its titles has been clicked on by the user.
38 * @param {Object} item breadcrumb item
39 * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
40 * @param {Function} [item.show] triggered whenever the widget should be shown back
41 * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
42 * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
43 * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
44 * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
46 push_breadcrumb: function(item) {
47 var last = this.breadcrumbs.slice(-1)[0];
52 show: function(index) {
53 this.widget.$el.show();
56 this.widget.$el.hide();
59 this.widget.destroy();
61 get_title: function() {
62 return this.title || this.widget.get('title');
65 item.id = _.uniqueId('breadcrumb_');
66 this.breadcrumbs.push(item);
68 history_back: function() {
69 var last = this.breadcrumbs.slice(-1)[0];
73 var title = last.get_title();
74 if (_.isArray(title) && title.length > 1) {
75 return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
76 } else if (this.breadcrumbs.length === 1) {
77 // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
80 var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
81 title = prev.get_title();
82 return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
85 on_breadcrumb_clicked: function(ev) {
86 var $e = $(ev.target);
87 var id = $e.data('id');
89 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
90 if (this.breadcrumbs[i].id == id) {
95 var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
96 this.select_breadcrumb(index, subindex);
98 select_breadcrumb: function(index, subindex) {
99 var next_item = this.breadcrumbs[index + 1];
100 if (next_item && next_item.on_reverse_breadcrumb) {
101 next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
103 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
105 if (this.remove_breadcrumb(i) === false) {
110 var item = this.breadcrumbs[index];
112 this.inner_widget = item.widget;
113 this.inner_action = item.action;
116 clear_breadcrumbs: function() {
117 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
118 if (this.remove_breadcrumb(0) === false) {
123 remove_breadcrumb: function(index) {
124 var item = this.breadcrumbs.splice(index, 1)[0];
126 var dups = _.filter(this.breadcrumbs, function(it) {
127 return item.widget === it.widget;
130 if (this.getParent().has_uncommitted_changes()) {
131 this.inner_widget = item.widget;
132 this.inner_action = item.action;
133 this.breadcrumbs.splice(index, 0, item);
140 var last_widget = this.breadcrumbs.slice(-1)[0];
142 this.inner_widget = last_widget.widget;
143 this.inner_action = last_widget.action;
146 get_title: function() {
148 for (var i = 0; i < this.breadcrumbs.length; i += 1) {
149 var item = this.breadcrumbs[i];
150 var tit = item.get_title();
151 if (!_.isArray(tit)) {
154 for (var j = 0; j < tit.length; j += 1) {
155 var label = _.escape(tit[j]);
156 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
157 titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
159 titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
163 return titles.join(' <span class="oe_fade">/</span> ');
165 do_push_state: function(state) {
167 if (this.getParent() && this.getParent().do_push_state) {
168 if (this.inner_action) {
169 if (this.inner_action._push_me === false) {
170 // this action has been explicitly marked as not pushable
173 state['title'] = this.inner_action.name;
174 if(this.inner_action.type == 'ir.actions.act_window') {
175 state['model'] = this.inner_action.res_model;
177 if (this.inner_action.menu_id) {
178 state['menu_id'] = this.inner_action.menu_id;
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 = {
204 type: "ir.actions.client",
207 _push_me: state._push_me,
210 action_loaded = this.do_action(action_client);
212 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
215 action_loaded = this.do_action(state.action);
216 $.when(action_loaded || null).done(function() {
217 instance.webclient.menu.has_been_loaded.done(function() {
218 if (self.inner_action && self.inner_action.id) {
219 instance.webclient.menu.open_action(self.inner_action.id);
225 } else if (state.model && state.id) {
226 // TODO handle context & domain ?
229 res_model: state.model,
231 type: 'ir.actions.act_window',
232 views: [[false, 'form']]
234 action_loaded = this.do_action(action);
235 } else if (state.sa) {
236 // load session action
238 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).then(function(action) {
240 return self.do_action(action);
245 $.when(action_loaded || null).done(function() {
246 if (self.inner_widget && self.inner_widget.do_load_state) {
247 self.inner_widget.do_load_state(state, warm);
251 do_action: function(action, options) {
252 options = _.defaults(options || {}, {
253 clear_breadcrumbs: false,
254 on_reverse_breadcrumb: function() {},
255 on_close: function() {},
256 action_menu_id: null,
258 if (_.isString(action) && instance.web.client_actions.contains(action)) {
259 var action_client = { type: "ir.actions.client", tag: action, params: {} };
260 return this.do_action(action_client, options);
261 } else if (_.isNumber(action) || _.isString(action)) {
263 return self.rpc("/web/action/load", { action_id: action }).then(function(result) {
264 return self.do_action(result, options);
268 console.error("No type for action", action);
269 return $.Deferred().reject();
271 var type = action.type.replace(/\./g,'_');
272 var popup = action.target === 'new';
273 var inline = action.target === 'inline' || action.target === 'inlineview';
274 action.flags = _.extend({
275 views_switcher : !popup && !inline,
276 search_view : !popup && !inline,
277 action_buttons : !popup && !inline,
278 sidebar : !popup && !inline,
279 pager : !popup && !inline,
280 display_title : !popup
281 }, action.flags || {});
282 action.menu_id = options.action_menu_id;
283 if (!(type in this)) {
284 console.error("Action manager can't handle action of type " + action.type, action);
285 return $.Deferred().reject();
287 return this[type](action, options);
289 null_action: function() {
291 this.clear_breadcrumbs();
295 * @param {Object} executor
296 * @param {Object} executor.action original action
297 * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
298 * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
299 * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
300 * @param {Object} options
303 ir_actions_common: function(executor, options) {
304 if (this.inner_widget && executor.action.target !== 'new') {
305 if (this.getParent().has_uncommitted_changes()) {
306 return $.Deferred().reject();
307 } else if (options.clear_breadcrumbs) {
308 this.clear_breadcrumbs();
311 var widget = executor.widget();
312 if (executor.action.target === 'new') {
313 if (this.dialog_widget && !this.dialog_widget.isDestroyed()) {
314 this.dialog_widget.destroy();
317 this.dialog = new instance.web.Dialog(this, {
318 dialogClass: executor.klass,
320 this.dialog.on("closing", null, options.on_close);
321 this.dialog.init_dialog();
322 this.dialog.dialog_title = executor.action.name;
323 if (widget instanceof instance.web.ViewManager) {
324 _.extend(widget.flags, {
325 $buttons: this.dialog.$buttons,
326 footer_to_buttons: true,
329 this.dialog_widget = widget;
330 this.dialog_widget.setParent(this.dialog);
331 var initialized = this.dialog_widget.appendTo(this.dialog.$el);
336 this.inner_action = executor.action;
337 this.inner_widget = widget;
338 executor.post_process(widget);
339 return this.inner_widget.appendTo(this.$el);
342 ir_actions_act_window: function (action, options) {
345 return this.ir_actions_common({
346 widget: function () { return new instance.web.ViewManagerAction(self, action); },
348 klass: 'oe_act_window',
349 post_process: function (widget) { widget.add_breadcrumb(options.on_reverse_breadcrumb); }
352 ir_actions_client: function (action, options) {
354 var ClientWidget = instance.web.client_actions.get_object(action.tag);
356 if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
358 if (next = ClientWidget(this, action)) {
359 return this.do_action(next, options);
364 return this.ir_actions_common({
365 widget: function () { return new ClientWidget(self, action); },
367 klass: 'oe_act_client',
368 post_process: function(widget) {
369 self.push_breadcrumb({
372 on_reverse_breadcrumb: options.on_reverse_breadcrumb,
374 if (action.tag !== 'reload') {
375 self.do_push_state({});
380 ir_actions_act_window_close: function (action, options) {
386 ir_actions_server: function (action, options) {
388 this.rpc('/web/action/run', {
389 action_id: action.id,
390 context: action.context || {}
391 }).done(function (action) {
392 self.do_action(action, options)
395 ir_actions_report_xml: function(action, options) {
397 instance.web.blockUI();
398 self.rpc("/web/session/eval_domain_and_context", {
399 contexts: [action.context],
401 }).done(function(res) {
402 action = _.clone(action);
403 action.context = res.context;
404 var c = instance.webclient.crashmanager;
405 self.session.get_file({
407 data: {action: JSON.stringify(action)},
408 complete: instance.web.unblockUI,
415 error: c.rpc_error.bind(c)
419 ir_actions_act_url: function (action) {
420 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
424 instance.web.ViewManager = instance.web.Widget.extend({
425 template: "ViewManager",
426 init: function(parent, dataset, views, flags) {
428 this.url_states = {};
429 this.model = dataset ? dataset.model : undefined;
430 this.dataset = dataset;
431 this.searchview = null;
432 this.active_view = null;
433 this.views_src = _.map(views, function(x) {
434 if (x instanceof Array) {
435 var View = instance.web.views.get_object(x[1], true);
439 label: View ? View.prototype.display_name : (void 'nope')
446 this.flags = flags || {};
447 this.registry = instance.web.views;
448 this.views_history = [];
451 * @returns {jQuery.Deferred} initial view loading promise
456 this.$el.find('.oe_view_manager_switch a').click(function() {
457 self.switch_mode($(this).data('view-type'));
460 _.each(this.views_src, function(view) {
461 self.views[view.view_type] = $.extend({}, view, {
462 deferred : $.Deferred(),
465 $buttons : self.$el.find('.oe_view_manager_buttons'),
466 $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
467 $pager : self.$el.find('.oe_view_manager_pager'),
468 action : self.action,
469 action_views_ids : views_ids
470 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
472 views_ids[view.view_type] = view.view_id;
474 if (this.flags.views_switcher === false) {
475 this.$el.find('.oe_view_manager_switch').hide();
477 // If no default view defined, switch to the first one in sequence
478 var default_view = this.flags.default_view || this.views_src[0].view_type;
479 return this.switch_mode(default_view);
481 switch_mode: function(view_type, no_store, view_options) {
483 var view = this.views[view_type];
485 var form = this.views['form'];
486 if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
487 self.trigger('switch_mode', view_type, no_store, view_options);
488 return $.Deferred().reject();
491 this.views_history.push(view_type);
493 this.active_view = view_type;
495 if (!view.controller) {
496 view_promise = this.do_create_view(view_type);
497 } else if (this.searchview
498 && self.flags.auto_search
499 && view.controller.searchable !== false) {
500 this.searchview.ready.done(this.searchview.do_search);
503 if (this.searchview) {
504 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
507 this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
509 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
510 .parent().addClass('active');
512 return $.when(view_promise).done(function () {
513 _.each(_.keys(self.views), function(view_name) {
514 var controller = self.views[view_name].controller;
516 var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
517 if (view_name === view_type) {
519 controller.do_show(view_options || {});
522 controller.do_hide();
526 self.trigger('switch_mode', view_type, no_store, view_options);
529 do_create_view: function(view_type) {
530 // Lazy loading of views
532 var view = this.views[view_type];
533 var viewclass = this.registry.get_object(view_type);
534 var options = _.clone(view.options);
535 if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
536 options.initial_mode = 'edit';
538 var controller = new viewclass(this, this.dataset, view.view_id, options);
540 controller.on('history_back', this, function() {
541 var am = self.getParent();
542 if (am && am.trigger) {
543 return am.trigger('history_back');
547 controller.on("change:title", this, function() {
548 if (self.active_view === view_type) {
549 self.set_title(controller.get('title'));
553 if (view.embedded_view) {
554 controller.set_embedded_view(view.embedded_view);
556 controller.on('switch_mode', self, this.switch_mode);
557 controller.on('previous_view', self, this.prev_view);
559 var container = this.$el.find(".oe_view_manager_view_" + view_type);
560 var view_promise = controller.appendTo(container);
561 this.views[view_type].controller = controller;
562 this.views[view_type].deferred.resolve(view_type);
563 return $.when(view_promise).done(function() {
565 && self.flags.auto_search
566 && view.controller.searchable !== false) {
567 self.searchview.ready.done(self.searchview.do_search);
569 self.trigger("controller_inited",view_type,controller);
572 set_title: function(title) {
573 this.$el.find('.oe_view_title_text:first').text(title);
575 add_breadcrumb: function(on_reverse_breadcrumb) {
577 var views = [this.active_view || this.views_src[0].view_type];
578 this.on('switch_mode', self, function(mode) {
579 var last = views.slice(-1)[0];
581 if (mode !== 'form') {
587 this.getParent().push_breadcrumb({
590 show: function(index) {
591 var view_to_select = views[index];
592 var state = self.url_states[view_to_select];
593 self.do_push_state(state || {});
594 $.when(self.switch_mode(view_to_select)).done(function() {
598 get_title: function() {
601 _.each(self.getParent().breadcrumbs, function(bc, i) {
602 if (bc.widget === self) {
606 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
607 var titles = _.map(views, function(v) {
608 var controller = self.views[v].controller;
610 id = controller.datarecord.id;
612 return controller.get('title');
614 if (next && next.action && next.action.res_id && self.dataset &&
615 self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
616 // If the current active view is a formview and the next item in the breadcrumbs
617 // is an action on same object (model / res_id), then we omit the current formview's title
622 on_reverse_breadcrumb: on_reverse_breadcrumb,
626 * Returns to the view preceding the caller view in this manager's
627 * navigation history (the navigation history is appended to via
630 * @param {Object} [options]
631 * @param {Boolean} [options.created=false] resource was created
632 * @param {String} [options.default=null] view to switch to if no previous view
633 * @returns {$.Deferred} switching end signal
635 prev_view: function (options) {
636 options = options || {};
637 var current_view = this.views_history.pop();
638 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
639 if (options.created && current_view === 'form' && previous_view === 'list') {
640 // APR special case: "If creation mode from list (and only from a list),
641 // after saving, go to page view (don't come back in list)"
642 return this.switch_mode('form');
643 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
644 // APR special case: "If creation from dashboard, we have no previous view
645 return this.switch_mode('form');
647 return this.switch_mode(previous_view, true);
650 * Sets up the current viewmanager's search view.
652 * @param {Number|false} view_id the view to use or false for a default one
653 * @returns {jQuery.Deferred} search view startup deferred
655 setup_search_view: function(view_id, search_defaults) {
657 if (this.searchview) {
658 this.searchview.destroy();
660 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
662 this.searchview.on('search_data', self, this.do_searchview_search);
663 return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
665 do_searchview_search: function(domains, contexts, groupbys) {
667 controller = this.views[this.active_view].controller,
668 action_context = this.action.context || {};
669 this.rpc('/web/session/eval_domain_and_context', {
670 domains: [this.action.domain || []].concat(domains || []),
671 contexts: [action_context].concat(contexts || []),
672 group_by_seq: groupbys || []
673 }).done(function (results) {
674 self.dataset._model = new instance.web.Model(
675 self.dataset.model, results.context, results.domain);
676 var groupby = results.group_by.length
678 : action_context.group_by;
679 if (_.isString(groupby)) {
682 controller.do_search(results.domain, results.context, groupby || []);
686 * Called when one of the view want to execute an action
688 on_action: function(action) {
690 on_create: function() {
692 on_remove: function() {
694 on_edit: function() {
697 * Called by children view after executing an action
699 on_action_executed: function () {
703 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
704 template:"ViewManagerAction",
706 * @constructs instance.web.ViewManagerAction
707 * @extends instance.web.ViewManager
709 * @param {instance.web.ActionManager} parent parent object/widget
710 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
712 init: function(parent, action) {
713 // dataset initialization will take the session from ``this``, so if we
714 // do not have it yet (and we don't, because we've not called our own
715 // ``_super()``) rpc requests will blow up.
716 var flags = action.flags || {};
717 if (!('auto_search' in flags)) {
718 flags.auto_search = action.auto_search !== false;
720 if (action.res_model == 'board.board' && action.view_mode === 'form') {
721 // Special case for Dashboards
723 views_switcher : false,
724 display_title : false,
728 action_buttons : false
731 this._super(parent, null, action.views, flags);
732 this.session = parent.session;
733 this.action = action;
734 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
736 dataset.ids.push(action.res_id);
739 this.dataset = dataset;
741 // setup storage for session-wise menu hiding
742 if (this.session.hidden_menutips) {
745 this.session.hidden_menutips = {};
748 * Initializes the ViewManagerAction: sets up the searchview (if the
749 * searchview is enabled in the manager's action flags), calls into the
750 * parent to initialize the primary view and (if the VMA has a searchview)
751 * launches an initial search after both views are done rendering.
756 search_defaults = {};
757 _.each(this.action.context, function (value, key) {
758 var match = /^search_default_(.*)$/.exec(key);
760 search_defaults[match[1]] = value;
764 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
766 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
768 var main_view_loaded = this._super();
770 var manager_ready = $.when(searchview_loaded, main_view_loaded);
772 this.$el.find('.oe_debug_view').change(this.on_debug_changed);
773 this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
774 return manager_ready;
776 on_debug_changed: function (evt) {
778 $sel = $(evt.currentTarget),
779 $option = $sel.find('option:selected'),
781 current_view = this.views[this.active_view].controller;
784 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
785 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
791 type : 'ir.actions.act_url',
792 url: '/web/tests?mod=*'
796 var ids = current_view.get_selected_ids();
797 if (ids.length === 1) {
798 this.dataset.call('perm_read', [ids]).done(function(result) {
799 var dialog = new instance.web.Dialog(this, {
800 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
802 }, QWeb.render('ViewManagerDebugViewLog', {
804 format : instance.web.format_value
809 case 'toggle_layout_outline':
810 current_view.rendering_engine.toggle_layout_debugging();
814 name: "Technical Translation",
815 res_model : 'ir.translation',
816 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
817 views: [[false, 'list'], [false, 'form']],
818 type : 'ir.actions.act_window',
824 this.dataset.call('fields_get', [false, {}]).done(function (fields) {
825 var $root = $('<dl>');
826 _(fields).each(function (attributes, name) {
827 $root.append($('<dt>').append($('<h4>').text(name)));
828 var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
829 _(attributes).each(function (def, name) {
830 if (def instanceof Object) {
831 def = JSON.stringify(def);
834 .append($('<dt>').text(name))
835 .append($('<dd style="white-space: pre-wrap;">').text(def));
838 new instance.web.Dialog(self, {
839 title: _.str.sprintf(_t("Model %s fields"),
841 width: '95%'}, $root).open();
844 case 'edit_workflow':
845 return this.do_action({
846 res_model : 'workflow',
847 domain : [['osv', '=', this.dataset.model]],
848 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
849 type : 'ir.actions.act_window',
855 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
857 case 'manage_filters':
859 res_model: 'ir.filters',
860 views: [[false, 'list'], [false, 'form']],
861 type: 'ir.actions.act_window',
863 search_default_my_filters: true,
864 search_default_model_id: this.dataset.model
868 case 'print_workflow':
869 if (current_view.get_selected_ids && current_view.get_selected_ids().length == 1) {
870 instance.web.blockUI();
872 context: { active_ids: current_view.get_selected_ids() },
873 report_name: "workflow.instance.graph",
875 model: this.dataset.model,
876 id: current_view.get_selected_ids()[0],
880 this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
885 console.log("No debug handler for ", val);
888 evt.currentTarget.selectedIndex = 0;
890 do_edit_resource: function(model, id, action) {
891 var action = _.extend({
894 type : 'ir.actions.act_window',
897 views : [[false, 'form']],
900 action_buttons : true,
902 resize_textareas : true
906 this.do_action(action);
908 switch_mode: function (view_type, no_store, options) {
911 return $.when(this._super.apply(this, arguments)).done(function () {
912 var controller = self.views[self.active_view].controller;
913 self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
920 do_create_view: function(view_type) {
921 var r = this._super.apply(this, arguments);
922 var view = this.views[view_type].controller;
923 view.set({ 'title': this.action.name });
926 get_action_manager: function() {
928 while (cur = cur.getParent()) {
929 if (cur instanceof instance.web.ActionManager) {
935 set_title: function(title) {
936 this.$el.find('.oe_breadcrumb_title:first').html(this.get_action_manager().get_title());
938 do_push_state: function(state) {
939 if (this.getParent() && this.getParent().do_push_state) {
940 state["view_type"] = this.active_view;
941 this.url_states[this.active_view] = state;
942 this.getParent().do_push_state(state);
945 do_load_state: function(state, warm) {
948 if (state.view_type && state.view_type !== this.active_view) {
950 this.views[this.active_view].deferred.then(function() {
951 return self.switch_mode(state.view_type, true);
956 $.when(defs).done(function() {
957 self.views[self.active_view].controller.do_load_state(state, warm);
962 instance.web.Sidebar = instance.web.Widget.extend({
963 init: function(parent) {
966 var view = this.getParent();
968 { 'name' : 'print', 'label' : _t('Print'), },
969 { 'name' : 'other', 'label' : _t('More'), }
975 this.fileupload_id = _.uniqueId('oe_fileupload');
976 $(window).on(this.fileupload_id, function() {
977 var args = [].slice.call(arguments).slice(1);
978 if (args[0] && args[0].error) {
979 alert(args[0].error);
981 self.do_attachement_update(self.dataset, self.model_id);
983 instance.web.unblockUI();
990 this.$el.on('click','.oe_dropdown_menu li a', function(event) {
991 var section = $(this).data('section');
992 var index = $(this).data('index');
993 var item = self.items[section][index];
995 item.callback.apply(self, [item]);
996 } else if (item.action) {
997 self.on_item_action_clicked(item);
998 } else if (item.url) {
1001 event.preventDefault();
1004 redraw: function() {
1006 self.$el.html(QWeb.render('Sidebar', {widget: self}));
1008 // Hides Sidebar sections when item list is empty
1009 this.$('.oe_form_dropdown_section').each(function() {
1010 $(this).toggle(!!$(this).find('li').length);
1014 * For each item added to the section:
1017 * will be used as the item's name in the sidebar, can be html
1020 * descriptor for the action which will be executed, ``action`` and
1021 * ``callback`` should be exclusive
1024 * function to call when the item is clicked in the sidebar, called
1025 * with the item descriptor as its first argument (so information
1026 * can be stored as additional keys on the object passed to
1029 * ``classname`` (optional)
1030 * ``@class`` set on the sidebar serialization of the item
1032 * ``title`` (optional)
1033 * will be set as the item's ``@title`` (tooltip)
1035 * @param {String} section_code
1036 * @param {Array<{label, action | callback[, classname][, title]}>} items
1038 add_items: function(section_code, items) {
1041 this.items[section_code].push.apply(this.items[section_code],items);
1045 add_toolbar: function(toolbar) {
1047 _.each(['print','action','relate'], function(type) {
1048 var items = toolbar[type];
1050 for (var i = 0; i < items.length; i++) {
1052 label: items[i]['name'],
1054 classname: 'oe_sidebar_' + type
1057 self.add_items(type=='print' ? 'print' : 'other', items);
1061 on_item_action_clicked: function(item) {
1063 self.getParent().sidebar_context().done(function (context) {
1064 var ids = self.getParent().get_selected_ids();
1065 if (ids.length == 0) {
1066 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1069 var additional_context = _.extend({
1072 active_model: self.getParent().dataset.model
1074 self.rpc("/web/action/load", {
1075 action_id: item.action.id,
1076 context: additional_context
1077 }).done(function(result) {
1078 result.context = _.extend(result.context || {},
1079 additional_context);
1080 result.flags = result.flags || {};
1081 result.flags.new_window = true;
1082 self.do_action(result, {
1083 on_close: function() {
1085 self.getParent().reload();
1091 do_attachement_update: function(dataset, model_id) {
1092 this.dataset = dataset;
1093 this.model_id = model_id;
1095 this.on_attachments_loaded([]);
1097 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1098 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1099 ds.read_slice(['name', 'url', 'type'], {}).done(this.on_attachments_loaded);
1102 on_attachments_loaded: function(attachments) {
1105 var prefix = this.session.url('/web/binary/saveas', {model: 'ir.attachment', field: 'datas', filename_field: 'name'});
1106 _.each(attachments,function(a) {
1108 if(a.type === "binary") {
1109 a.url = prefix + '&id=' + a.id + '&t=' + (new Date().getTime());
1112 self.items['files'] = attachments;
1114 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1115 this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1117 on_attachment_changed: function(e) {
1118 var $e = $(e.target);
1119 if ($e.val() !== '') {
1120 this.$el.find('form.oe_form_binary_form').submit();
1121 $e.parent().find('input[type=file]').prop('disabled', true);
1122 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1123 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1124 instance.web.blockUI();
1127 on_attachment_delete: function(e) {
1130 e.stopPropagation();
1132 var $e = $(e.currentTarget);
1133 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1134 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).done(function() {
1135 self.do_attachement_update(self.dataset, self.model_id);
1141 instance.web.View = instance.web.Widget.extend({
1142 // name displayed in view switchers
1145 * Define a view type for each view to allow automatic call to fields_view_get.
1147 view_type: undefined,
1148 init: function(parent, dataset, view_id, options) {
1149 this._super(parent);
1150 this.dataset = dataset;
1151 this.view_id = view_id;
1152 this.set_default_options(options);
1154 start: function () {
1155 return this.load_view();
1157 load_view: function(context) {
1160 if (this.embedded_view) {
1161 view_loaded = $.Deferred();
1162 $.async_when().done(function() {
1163 view_loaded.resolve(self.embedded_view);
1166 if (! this.view_type)
1167 console.warn("view_type is not defined", this);
1168 view_loaded = this.rpc("/web/view/load", {
1169 "model": this.dataset.model,
1170 "view_id": this.view_id,
1171 "view_type": this.view_type,
1172 toolbar: !!this.options.$sidebar,
1173 context: this.dataset.get_context(context)
1176 return view_loaded.then(function(r) {
1177 self.trigger('view_loaded', r);
1178 // add css classes that reflect the (absence of) access rights
1179 self.$el.addClass('oe_view')
1180 .toggleClass('oe_cannot_create', !self.is_action_enabled('create'))
1181 .toggleClass('oe_cannot_edit', !self.is_action_enabled('edit'))
1182 .toggleClass('oe_cannot_delete', !self.is_action_enabled('delete'));
1185 set_default_options: function(options) {
1186 this.options = options || {};
1187 _.defaults(this.options, {
1188 // All possible views options should be defaulted here
1192 action_views_ids: {}
1196 * Fetches and executes the action identified by ``action_data``.
1198 * @param {Object} action_data the action descriptor data
1199 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1200 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1201 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1202 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1203 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1204 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1205 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1207 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1209 var result_handler = function () {
1210 if (on_closed) { on_closed.apply(null, arguments); }
1211 if (self.getParent() && self.getParent().on_action_executed) {
1212 return self.getParent().on_action_executed.apply(null, arguments);
1215 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1217 var handler = function (r) {
1219 if (action && action.constructor == Object) {
1220 var ncontext = new instance.web.CompoundContext(context);
1223 active_id: record_id,
1224 active_ids: [record_id],
1225 active_model: dataset.model
1228 ncontext.add(action.context || {});
1229 return self.rpc('/web/session/eval_domain_and_context', {
1230 contexts: [ncontext],
1232 }).then(function (results) {
1233 action.context = results.context;
1234 /* niv: previously we were overriding once more with action_data.context,
1235 * I assumed this was not a correct behavior and removed it
1237 return self.do_action(action, {
1238 on_close: result_handler,
1242 self.do_action({"type":"ir.actions.act_window_close"});
1243 return result_handler();
1247 if (action_data.special === 'cancel') {
1248 return handler({"type":"ir.actions.act_window_close"});
1249 } else if (action_data.type=="object") {
1250 var args = [[record_id]], additional_args = [];
1251 if (action_data.args) {
1253 // Warning: quotes and double quotes problem due to json and xml clash
1254 // Maybe we should force escaping in xml or do a better parse of the args array
1255 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1256 args = args.concat(additional_args);
1258 console.error("Could not JSON.parse arguments", action_data.args);
1262 return dataset.call_button(action_data.name, args).done(handler);
1263 } else if (action_data.type=="action") {
1264 return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).done(handler);
1266 return dataset.exec_workflow(record_id, action_data.name).done(handler);
1270 * Directly set a view to use instead of calling fields_view_get. This method must
1271 * be called before start(). When an embedded view is set, underlying implementations
1272 * of instance.web.View must use the provided view instead of any other one.
1274 * @param embedded_view A view.
1276 set_embedded_view: function(embedded_view) {
1277 this.embedded_view = embedded_view;
1279 do_show: function () {
1282 do_hide: function () {
1285 is_active: function () {
1286 var manager = this.getParent();
1287 return !manager || !manager.active_view
1288 || manager.views[manager.active_view].controller === this;
1290 * Wraps fn to only call it if the current view is the active one. If the
1291 * current view is not active, doesn't call fn.
1293 * fn can not return anything, as a non-call to fn can't return anything
1296 * @param {Function} fn function to wrap in the active guard
1298 guard_active: function (fn) {
1300 return function () {
1301 if (self.is_active()) {
1302 fn.apply(self, arguments);
1306 do_push_state: function(state) {
1307 if (this.getParent() && this.getParent().do_push_state) {
1308 this.getParent().do_push_state(state);
1311 do_load_state: function(state, warm) {
1314 * Switches to a specific view type
1316 do_switch_view: function() {
1317 this.trigger.apply(this, ['switch_mode'].concat(_.toArray(arguments)));
1320 * Cancels the switch to the current view, switches to the previous one
1322 * @param {Object} [options]
1323 * @param {Boolean} [options.created=false] resource was created
1324 * @param {String} [options.default=null] view to switch to if no previous view
1327 do_search: function(view) {
1329 on_sidebar_export: function() {
1330 new instance.web.DataExport(this, this.dataset).open();
1332 sidebar_context: function () {
1336 * Asks the view to reload itself, if the reloading is asynchronous should
1337 * return a {$.Deferred} indicating when the reloading is done.
1339 reload: function () {
1343 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1344 * An action is disabled by setting the corresponding attribute in the view's main element,
1345 * like: <form string="" create="false" edit="false" delete="false">
1347 is_action_enabled: function(action) {
1348 var attrs = this.fields_view.arch.attrs;
1349 return (action in attrs) ? JSON.parse(attrs[action]) : true;
1353 instance.web.xml_to_json = function(node) {
1354 switch (node.nodeType) {
1360 var attrs = $(node).getAttributes();
1361 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1364 attrs[key] = JSON.parse(attrs[key]);
1369 tag: node.tagName.toLowerCase(),
1371 children: _.map(node.childNodes, instance.web.xml_to_json)
1375 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1376 // For debugging purpose, this function will convert a json node back to xml
1377 indent = indent || 0;
1378 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1379 r = sindent + '<' + node.tag,
1380 cr = human_readable ? '\n' : '';
1382 if (typeof(node) === 'string') {
1383 return sindent + node;
1384 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1386 _.str.sprintf("Node [%s] is not a JSONified XML node",
1387 JSON.stringify(node)));
1389 for (var attr in node.attrs) {
1390 var vattr = node.attrs[attr];
1391 if (typeof(vattr) !== 'string') {
1393 vattr = JSON.stringify(vattr);
1395 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1396 if (human_readable) {
1397 vattr = vattr.replace(/"/g, "'");
1399 r += ' ' + attr + '="' + vattr + '"';
1401 if (node.children && node.children.length) {
1404 for (var i = 0, ii = node.children.length; i < ii; i++) {
1405 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1407 r += childs.join(cr);
1408 r += cr + sindent + '</' + node.tag + '>';
1414 instance.web.xml_to_str = function(node) {
1415 if (window.XMLSerializer) {
1416 return (new XMLSerializer()).serializeToString(node);
1417 } else if (window.ActiveXObject) {
1420 throw new Error("Could not serialize XML");
1423 instance.web.str_to_xml = function(s) {
1424 if (window.DOMParser) {
1425 var dp = new DOMParser();
1426 var r = dp.parseFromString(s, "text/xml");
1427 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1428 throw new Error("Could not parse string to xml");
1434 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1436 throw new Error("Could not find a DOM Parser: " + e.message);
1439 xDoc.preserveWhiteSpace = true;
1445 * Registry for all the main views
1447 instance.web.views = new instance.web.Registry();
1451 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: