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.id) {
178 state['action'] = this.inner_action.id;
179 } else if (this.inner_action.type == 'ir.actions.client') {
180 state['action'] = this.inner_action.tag;
182 _.each(this.inner_action.params, function(v, k) {
183 if(_.isString(v) || _.isNumber(v)) {
187 state = _.extend(params || {}, state);
191 this.getParent().do_push_state(state);
195 do_load_state: function(state, warm) {
199 if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
200 var action_client = {type: "ir.actions.client", tag: state.action, params: state};
202 action_loaded = this.do_action(action_client);
204 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
207 action_loaded = this.do_action(state.action);
208 instance.webclient.menu.has_been_loaded.then(function() {
209 instance.webclient.menu.open_action(state.action);
213 } else if (state.model && state.id) {
214 // TODO handle context & domain ?
217 res_model: state.model,
219 type: 'ir.actions.act_window',
220 views: [[false, 'form']]
222 action_loaded = this.do_action(action);
223 } else if (state.sa) {
224 // load session action
226 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
228 return self.do_action(action);
233 $.when(action_loaded || null).then(function() {
234 if (self.inner_widget && self.inner_widget.do_load_state) {
235 self.inner_widget.do_load_state(state, warm);
239 do_action: function(action, options) {
240 options = _.defaults(options || {}, {
241 clear_breadcrumbs: false,
242 on_reverse_breadcrumb: function() {},
243 on_close: function() {},
245 if (_.isString(action) && instance.web.client_actions.contains(action)) {
246 var action_client = { type: "ir.actions.client", tag: action };
247 return this.do_action(action_client, options);
248 } else if (_.isNumber(action) || _.isString(action)) {
250 return self.rpc("/web/action/load", { action_id: action }).pipe(function(result) {
251 return self.do_action(result, options);
255 console.error("No type for action", action);
256 return $.Deferred().reject();
258 var type = action.type.replace(/\./g,'_');
259 var popup = action.target === 'new';
260 var inline = action.target === 'inline' || action.target === 'inlineview';
261 action.flags = _.extend({
262 views_switcher : !popup && !inline,
263 search_view : !popup && !inline,
264 action_buttons : !popup && !inline,
265 sidebar : !popup && !inline,
266 pager : !popup && !inline,
267 display_title : !popup
268 }, action.flags || {});
269 if (!(type in this)) {
270 console.error("Action manager can't handle action of type " + action.type, action);
271 return $.Deferred().reject();
273 return this[type](action, options);
275 null_action: function() {
277 this.clear_breadcrumbs();
281 * @param {Object} executor
282 * @param {Object} executor.action original action
283 * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
284 * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
285 * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
286 * @param {Object} options
289 ir_actions_common: function(executor, options) {
290 if (this.inner_widget && executor.action.target !== 'new') {
291 if (this.getParent().has_uncommitted_changes()) {
292 return $.Deferred().reject();
293 } else if (options.clear_breadcrumbs) {
294 this.clear_breadcrumbs();
297 var widget = executor.widget();
298 if (executor.action.target === 'new') {
299 if (this.dialog_widget && ! this.dialog_widget.isDestroyed())
300 this.dialog_widget.destroy();
301 if (this.dialog === null || this.dialog.isDestroyed()) {
302 this.dialog = new instance.web.Dialog(this, {
303 dialogClass: executor.klass,
305 this.dialog.on("closing", null, options.on_close);
306 this.dialog.init_dialog();
308 this.dialog.dialog_title = executor.action.name;
309 if (widget instanceof instance.web.ViewManager) {
310 _.extend(widget.flags, {
311 $buttons: this.dialog.$buttons,
312 footer_to_buttons: true,
315 this.dialog_widget = widget;
316 this.dialog_widget.setParent(this.dialog);
317 var initialized = this.dialog_widget.appendTo(this.dialog.$el);
322 this.inner_action = executor.action;
323 this.inner_widget = widget;
324 executor.post_process(widget);
325 return this.inner_widget.appendTo(this.$el);
328 ir_actions_act_window: function (action, options) {
331 return this.ir_actions_common({
332 widget: function () { return new instance.web.ViewManagerAction(self, action); },
334 klass: 'oe_act_window',
335 post_process: function (widget) { widget.add_breadcrumb(options.on_reverse_breadcrumb); }
338 ir_actions_client: function (action, options) {
340 var ClientWidget = instance.web.client_actions.get_object(action.tag);
342 if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
344 if (next = ClientWidget(this, action.params)) {
345 return this.do_action(next, options);
350 return this.ir_actions_common({
351 widget: function () { return new ClientWidget(self, action.params); },
353 klass: 'oe_act_client',
354 post_process: function(widget) {
355 self.push_breadcrumb({
358 on_reverse_breadcrumb: options.on_reverse_breadcrumb,
360 if (action.tag !== 'reload') {
361 self.do_push_state({});
366 ir_actions_act_window_close: function (action, options) {
372 ir_actions_server: function (action, options) {
374 this.rpc('/web/action/run', {
375 action_id: action.id,
376 context: action.context || {}
377 }).then(function (action) {
378 self.do_action(action, options)
381 ir_actions_report_xml: function(action, options) {
383 instance.web.blockUI();
384 self.rpc("/web/session/eval_domain_and_context", {
385 contexts: [action.context],
387 }).then(function(res) {
388 action = _.clone(action);
389 action.context = res.context;
390 self.session.get_file({
392 data: {action: JSON.stringify(action)},
393 complete: instance.web.unblockUI,
400 error: instance.webclient.crashmanager.on_rpc_error
404 ir_actions_act_url: function (action) {
405 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
409 instance.web.ViewManager = instance.web.Widget.extend({
410 template: "ViewManager",
411 init: function(parent, dataset, views, flags) {
413 this.url_states = {};
414 this.model = dataset ? dataset.model : undefined;
415 this.dataset = dataset;
416 this.searchview = null;
417 this.active_view = null;
418 this.views_src = _.map(views, function(x) {
419 if (x instanceof Array) {
420 var View = instance.web.views.get_object(x[1], true);
424 label: View ? View.prototype.display_name : (void 'nope')
431 this.flags = flags || {};
432 this.registry = instance.web.views;
433 this.views_history = [];
436 * @returns {jQuery.Deferred} initial view loading promise
441 this.$el.find('.oe_view_manager_switch a').click(function() {
442 self.switch_mode($(this).data('view-type'));
445 _.each(this.views_src, function(view) {
446 self.views[view.view_type] = $.extend({}, view, {
447 deferred : $.Deferred(),
450 $buttons : self.$el.find('.oe_view_manager_buttons'),
451 $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
452 $pager : self.$el.find('.oe_view_manager_pager'),
453 action : self.action,
454 action_views_ids : views_ids
455 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
457 views_ids[view.view_type] = view.view_id;
459 if (this.flags.views_switcher === false) {
460 this.$el.find('.oe_view_manager_switch').hide();
462 // If no default view defined, switch to the first one in sequence
463 var default_view = this.flags.default_view || this.views_src[0].view_type;
464 return this.switch_mode(default_view);
466 switch_mode: function(view_type, no_store, view_options) {
468 var view = this.views[view_type];
470 var form = this.views['form'];
471 if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
472 self.trigger('switch_mode', view_type, no_store, view_options);
473 return $.Deferred().reject();
476 this.views_history.push(view_type);
478 this.active_view = view_type;
480 if (!view.controller) {
481 view_promise = this.do_create_view(view_type);
482 } else if (this.searchview
483 && self.flags.auto_search
484 && view.controller.searchable !== false) {
485 this.searchview.ready.then(this.searchview.do_search);
488 if (this.searchview) {
489 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
492 this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
494 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
495 .parent().addClass('active');
497 r = $.when(view_promise).then(function () {
498 _.each(_.keys(self.views), function(view_name) {
499 var controller = self.views[view_name].controller;
501 var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
502 if (view_name === view_type) {
504 controller.do_show(view_options || {});
507 controller.do_hide();
511 self.trigger('switch_mode', view_type, no_store, view_options);
515 do_create_view: function(view_type) {
516 // Lazy loading of views
518 var view = this.views[view_type];
519 var viewclass = this.registry.get_object(view_type);
520 var options = _.clone(view.options);
521 if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
522 options.initial_mode = 'edit';
524 var controller = new viewclass(this, this.dataset, view.view_id, options);
526 controller.on('history_back', this, function() {
527 var am = self.getParent();
528 if (am && am.trigger) {
529 return am.trigger('history_back');
533 controller.on("change:title", this, function() {
534 if (self.active_view === view_type) {
535 self.set_title(controller.get('title'));
539 if (view.embedded_view) {
540 controller.set_embedded_view(view.embedded_view);
542 controller.on('switch_mode', self, this.switch_mode);
543 controller.on('previous_view', self, this.prev_view);
545 var container = this.$el.find(".oe_view_manager_view_" + view_type);
546 var view_promise = controller.appendTo(container);
547 this.views[view_type].controller = controller;
548 this.views[view_type].deferred.resolve(view_type);
549 return $.when(view_promise).then(function() {
551 && self.flags.auto_search
552 && view.controller.searchable !== false) {
553 self.searchview.ready.then(self.searchview.do_search);
555 self.trigger("controller_inited",view_type,controller);
558 set_title: function(title) {
559 this.$el.find('.oe_view_title_text:first').text(title);
561 add_breadcrumb: function(on_reverse_breadcrumb) {
563 var views = [this.active_view || this.views_src[0].view_type];
564 this.on('switch_mode', self, function(mode) {
565 var last = views.slice(-1)[0];
567 if (mode !== 'form') {
573 this.getParent().push_breadcrumb({
576 show: function(index) {
577 var view_to_select = views[index];
578 var state = self.url_states[view_to_select];
579 self.do_push_state(state || {});
580 $.when(self.switch_mode(view_to_select)).then(function() {
584 get_title: function() {
587 _.each(self.getParent().breadcrumbs, function(bc, i) {
588 if (bc.widget === self) {
592 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
593 var titles = _.map(views, function(v) {
594 var controller = self.views[v].controller;
596 id = controller.datarecord.id;
598 return controller.get('title');
600 if (next && next.action && next.action.res_id && self.dataset &&
601 self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
602 // If the current active view is a formview and the next item in the breadcrumbs
603 // is an action on same object (model / res_id), then we omit the current formview's title
608 on_reverse_breadcrumb: on_reverse_breadcrumb,
612 * Returns to the view preceding the caller view in this manager's
613 * navigation history (the navigation history is appended to via
616 * @param {Object} [options]
617 * @param {Boolean} [options.created=false] resource was created
618 * @param {String} [options.default=null] view to switch to if no previous view
619 * @returns {$.Deferred} switching end signal
621 prev_view: function (options) {
622 options = options || {};
623 var current_view = this.views_history.pop();
624 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
625 if (options.created && current_view === 'form' && previous_view === 'list') {
626 // APR special case: "If creation mode from list (and only from a list),
627 // after saving, go to page view (don't come back in list)"
628 return this.switch_mode('form');
629 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
630 // APR special case: "If creation from dashboard, we have no previous view
631 return this.switch_mode('form');
633 return this.switch_mode(previous_view, true);
636 * Sets up the current viewmanager's search view.
638 * @param {Number|false} view_id the view to use or false for a default one
639 * @returns {jQuery.Deferred} search view startup deferred
641 setup_search_view: function(view_id, search_defaults) {
643 if (this.searchview) {
644 this.searchview.destroy();
646 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
648 this.searchview.on('search_data', self, this.do_searchview_search);
649 return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
651 do_searchview_search: function(domains, contexts, groupbys) {
653 controller = this.views[this.active_view].controller,
654 action_context = this.action.context || {};
655 this.rpc('/web/session/eval_domain_and_context', {
656 domains: [this.action.domain || []].concat(domains || []),
657 contexts: [action_context].concat(contexts || []),
658 group_by_seq: groupbys || []
659 }).then(function (results) {
660 self.dataset._model = new instance.web.Model(
661 self.dataset.model, results.context, results.domain);
662 var groupby = results.group_by.length
664 : action_context.group_by;
665 if (_.isString(groupby)) {
668 controller.do_search(results.domain, results.context, groupby || []);
672 * Called when one of the view want to execute an action
674 on_action: function(action) {
676 on_create: function() {
678 on_remove: function() {
680 on_edit: function() {
683 * Called by children view after executing an action
685 on_action_executed: function () {
689 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
690 template:"ViewManagerAction",
692 * @constructs instance.web.ViewManagerAction
693 * @extends instance.web.ViewManager
695 * @param {instance.web.ActionManager} parent parent object/widget
696 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
698 init: function(parent, action) {
699 // dataset initialization will take the session from ``this``, so if we
700 // do not have it yet (and we don't, because we've not called our own
701 // ``_super()``) rpc requests will blow up.
702 var flags = action.flags || {};
703 if (!('auto_search' in flags)) {
704 flags.auto_search = action.auto_search !== false;
706 if (action.res_model == 'board.board' && action.view_mode === 'form') {
707 // Special case for Dashboards
709 views_switcher : false,
710 display_title : false,
714 action_buttons : false
717 this._super(parent, null, action.views, flags);
718 this.session = parent.session;
719 this.action = action;
720 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
722 dataset.ids.push(action.res_id);
725 this.dataset = dataset;
727 // setup storage for session-wise menu hiding
728 if (this.session.hidden_menutips) {
731 this.session.hidden_menutips = {};
734 * Initializes the ViewManagerAction: sets up the searchview (if the
735 * searchview is enabled in the manager's action flags), calls into the
736 * parent to initialize the primary view and (if the VMA has a searchview)
737 * launches an initial search after both views are done rendering.
742 search_defaults = {};
743 _.each(this.action.context, function (value, key) {
744 var match = /^search_default_(.*)$/.exec(key);
746 search_defaults[match[1]] = value;
750 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
752 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
754 var main_view_loaded = this._super();
756 var manager_ready = $.when(searchview_loaded, main_view_loaded);
758 this.$el.find('.oe_debug_view').change(this.on_debug_changed);
759 this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
760 return manager_ready;
762 on_debug_changed: function (evt) {
764 $sel = $(evt.currentTarget),
765 $option = $sel.find('option:selected'),
767 current_view = this.views[this.active_view].controller;
770 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
771 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
777 type : 'ir.actions.act_url',
778 url: '/web/static/test/test.html'
782 var ids = current_view.get_selected_ids();
783 if (ids.length === 1) {
784 this.dataset.call('perm_read', [ids]).then(function(result) {
785 var dialog = new instance.web.Dialog(this, {
786 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
788 }, QWeb.render('ViewManagerDebugViewLog', {
790 format : instance.web.format_value
795 case 'toggle_layout_outline':
796 current_view.rendering_engine.toggle_layout_debugging();
800 name: "Technical Translation",
801 res_model : 'ir.translation',
802 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
803 views: [[false, 'list'], [false, 'form']],
804 type : 'ir.actions.act_window',
810 this.dataset.call('fields_get', [false, {}]).then(function (fields) {
811 var $root = $('<dl>');
812 _(fields).each(function (attributes, name) {
813 $root.append($('<dt>').append($('<h4>').text(name)));
814 var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
815 _(attributes).each(function (def, name) {
816 if (def instanceof Object) {
817 def = JSON.stringify(def);
820 .append($('<dt>').text(name))
821 .append($('<dd style="white-space: pre-wrap;">').text(def));
824 new instance.web.Dialog(self, {
825 title: _.str.sprintf(_t("Model %s fields"),
827 width: '95%'}, $root).open();
830 case 'edit_workflow':
831 return this.do_action({
832 res_model : 'workflow',
833 domain : [['osv', '=', this.dataset.model]],
834 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
835 type : 'ir.actions.act_window',
841 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
843 case 'manage_filters':
845 res_model: 'ir.filters',
846 views: [[false, 'list'], [false, 'form']],
847 type: 'ir.actions.act_window',
849 search_default_my_filters: true,
850 search_default_model_id: this.dataset.model
854 case 'print_workflow':
855 if (current_view.get_selected_ids && current_view.get_selected_ids().length == 1) {
856 instance.web.blockUI();
858 context: { active_ids: current_view.get_selected_ids() },
859 report_name: "workflow.instance.graph",
861 model: this.dataset.model,
862 id: current_view.get_selected_ids()[0],
866 this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
871 console.log("No debug handler for ", val);
874 evt.currentTarget.selectedIndex = 0;
876 do_edit_resource: function(model, id, action) {
877 var action = _.extend({
880 type : 'ir.actions.act_window',
883 views : [[false, 'form']],
886 action_buttons : true,
888 resize_textareas : true
892 this.do_action(action);
894 switch_mode: function (view_type, no_store, options) {
897 return $.when(this._super.apply(this, arguments)).then(function () {
898 var controller = self.views[self.active_view].controller;
899 self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
906 do_create_view: function(view_type) {
907 var r = this._super.apply(this, arguments);
908 var view = this.views[view_type].controller;
909 view.set({ 'title': this.action.name });
912 get_action_manager: function() {
914 while (cur = cur.getParent()) {
915 if (cur instanceof instance.web.ActionManager) {
921 set_title: function(title) {
922 this.$el.find('.oe_breadcrumb_title:first').html(this.get_action_manager().get_title());
924 do_push_state: function(state) {
925 if (this.getParent() && this.getParent().do_push_state) {
926 state["view_type"] = this.active_view;
927 this.url_states[this.active_view] = state;
928 this.getParent().do_push_state(state);
931 do_load_state: function(state, warm) {
934 if (state.view_type && state.view_type !== this.active_view) {
936 this.views[this.active_view].deferred.pipe(function() {
937 return self.switch_mode(state.view_type, true);
942 $.when(defs).then(function() {
943 self.views[self.active_view].controller.do_load_state(state, warm);
948 instance.web.Sidebar = instance.web.Widget.extend({
949 init: function(parent) {
952 var view = this.getParent();
954 { 'name' : 'print', 'label' : _t('Print'), },
955 { 'name' : 'other', 'label' : _t('More'), }
961 this.fileupload_id = _.uniqueId('oe_fileupload');
962 $(window).on(this.fileupload_id, function() {
963 var args = [].slice.call(arguments).slice(1);
964 if (args[0] && args[0].error) {
965 alert(args[0].error);
967 self.do_attachement_update(self.dataset, self.model_id);
969 instance.web.unblockUI();
976 this.$el.on('click','.oe_dropdown_menu li a', function(event) {
977 var section = $(this).data('section');
978 var index = $(this).data('index');
979 var item = self.items[section][index];
981 item.callback.apply(self, [item]);
982 } else if (item.action) {
983 self.on_item_action_clicked(item);
984 } else if (item.url) {
987 event.preventDefault();
992 self.$el.html(QWeb.render('Sidebar', {widget: self}));
994 // Hides Sidebar sections when item list is empty
995 this.$('.oe_form_dropdown_section').each(function() {
996 $(this).toggle(!!$(this).find('li').length);
1000 * For each item added to the section:
1003 * will be used as the item's name in the sidebar, can be html
1006 * descriptor for the action which will be executed, ``action`` and
1007 * ``callback`` should be exclusive
1010 * function to call when the item is clicked in the sidebar, called
1011 * with the item descriptor as its first argument (so information
1012 * can be stored as additional keys on the object passed to
1015 * ``classname`` (optional)
1016 * ``@class`` set on the sidebar serialization of the item
1018 * ``title`` (optional)
1019 * will be set as the item's ``@title`` (tooltip)
1021 * @param {String} section_code
1022 * @param {Array<{label, action | callback[, classname][, title]}>} items
1024 add_items: function(section_code, items) {
1027 this.items[section_code].push.apply(this.items[section_code],items);
1031 add_toolbar: function(toolbar) {
1033 _.each(['print','action','relate'], function(type) {
1034 var items = toolbar[type];
1036 for (var i = 0; i < items.length; i++) {
1038 label: items[i]['name'],
1040 classname: 'oe_sidebar_' + type
1043 self.add_items(type=='print' ? 'print' : 'other', items);
1047 on_item_action_clicked: function(item) {
1049 self.getParent().sidebar_context().then(function (context) {
1050 var ids = self.getParent().get_selected_ids();
1051 if (ids.length == 0) {
1052 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1055 var additional_context = _.extend({
1058 active_model: self.getParent().dataset.model
1060 self.rpc("/web/action/load", {
1061 action_id: item.action.id,
1062 context: additional_context
1063 }).then(function(result) {
1064 result.context = _.extend(result.context || {},
1065 additional_context);
1066 result.flags = result.flags || {};
1067 result.flags.new_window = true;
1068 self.do_action(result, {
1069 on_close: function() {
1071 self.getParent().reload();
1077 do_attachement_update: function(dataset, model_id) {
1078 this.dataset = dataset;
1079 this.model_id = model_id;
1081 this.on_attachments_loaded([]);
1083 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1084 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1085 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
1088 on_attachments_loaded: function(attachments) {
1091 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
1092 _.each(attachments,function(a) {
1094 if(a.type === "binary") {
1095 a.url = prefix + a.id + '&t=' + (new Date().getTime());
1098 self.items['files'] = attachments;
1100 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1101 this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1103 on_attachment_changed: function(e) {
1104 var $e = $(e.target);
1105 if ($e.val() !== '') {
1106 this.$el.find('form.oe_form_binary_form').submit();
1107 $e.parent().find('input[type=file]').prop('disabled', true);
1108 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1109 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1110 instance.web.blockUI();
1113 on_attachment_delete: function(e) {
1116 e.stopPropagation();
1118 var $e = $(e.currentTarget);
1119 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1120 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1121 self.do_attachement_update(self.dataset, self.model_id);
1127 instance.web.View = instance.web.Widget.extend({
1128 // name displayed in view switchers
1131 * Define a view type for each view to allow automatic call to fields_view_get.
1133 view_type: undefined,
1134 init: function(parent, dataset, view_id, options) {
1135 this._super(parent);
1136 this.dataset = dataset;
1137 this.view_id = view_id;
1138 this.set_default_options(options);
1140 start: function () {
1141 return this.load_view();
1143 load_view: function(context) {
1146 if (this.embedded_view) {
1147 view_loaded = $.Deferred();
1148 $.async_when().then(function() {
1149 view_loaded.resolve(self.embedded_view);
1152 if (! this.view_type)
1153 console.warn("view_type is not defined", this);
1154 view_loaded = this.rpc("/web/view/load", {
1155 "model": this.dataset.model,
1156 "view_id": this.view_id,
1157 "view_type": this.view_type,
1158 toolbar: !!this.options.$sidebar,
1159 context: this.dataset.get_context(context)
1162 return view_loaded.pipe(function(r) {
1163 self.trigger('view_loaded', r);
1164 // add css classes that reflect the (absence of) access rights
1165 self.$el.addClass('oe_view')
1166 .toggleClass('oe_cannot_create', !self.is_action_enabled('create'))
1167 .toggleClass('oe_cannot_edit', !self.is_action_enabled('edit'))
1168 .toggleClass('oe_cannot_delete', !self.is_action_enabled('delete'));
1171 set_default_options: function(options) {
1172 this.options = options || {};
1173 _.defaults(this.options, {
1174 // All possible views options should be defaulted here
1178 action_views_ids: {}
1182 * Fetches and executes the action identified by ``action_data``.
1184 * @param {Object} action_data the action descriptor data
1185 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1186 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1187 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1188 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1189 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1190 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1191 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1193 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1195 var result_handler = function () {
1196 if (on_closed) { on_closed.apply(null, arguments); }
1197 if (self.getParent() && self.getParent().on_action_executed) {
1198 return self.getParent().on_action_executed.apply(null, arguments);
1201 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1203 var handler = function (r) {
1205 if (action && action.constructor == Object) {
1206 var ncontext = new instance.web.CompoundContext(context);
1209 active_id: record_id,
1210 active_ids: [record_id],
1211 active_model: dataset.model
1214 ncontext.add(action.context || {});
1215 return self.rpc('/web/session/eval_domain_and_context', {
1216 contexts: [ncontext],
1218 }).pipe(function (results) {
1219 action.context = results.context;
1220 /* niv: previously we were overriding once more with action_data.context,
1221 * I assumed this was not a correct behavior and removed it
1223 return self.do_action(action, {
1224 on_close: result_handler,
1228 return result_handler();
1232 if (action_data.special) {
1233 return handler({"type":"ir.actions.act_window_close"});
1234 } else if (action_data.type=="object") {
1235 var args = [[record_id]], additional_args = [];
1236 if (action_data.args) {
1238 // Warning: quotes and double quotes problem due to json and xml clash
1239 // Maybe we should force escaping in xml or do a better parse of the args array
1240 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1241 args = args.concat(additional_args);
1243 console.error("Could not JSON.parse arguments", action_data.args);
1247 return dataset.call_button(action_data.name, args).then(handler);
1248 } else if (action_data.type=="action") {
1249 return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).then(handler);
1251 return dataset.exec_workflow(record_id, action_data.name).then(handler);
1255 * Directly set a view to use instead of calling fields_view_get. This method must
1256 * be called before start(). When an embedded view is set, underlying implementations
1257 * of instance.web.View must use the provided view instead of any other one.
1259 * @param embedded_view A view.
1261 set_embedded_view: function(embedded_view) {
1262 this.embedded_view = embedded_view;
1264 do_show: function () {
1267 do_hide: function () {
1270 do_push_state: function(state) {
1271 if (this.getParent() && this.getParent().do_push_state) {
1272 this.getParent().do_push_state(state);
1275 do_load_state: function(state, warm) {
1278 * Switches to a specific view type
1280 * @param {String} view view type to switch to
1282 do_switch_view: function(view) {
1283 this.trigger('switch_mode',view);
1286 * Cancels the switch to the current view, switches to the previous one
1288 * @param {Object} [options]
1289 * @param {Boolean} [options.created=false] resource was created
1290 * @param {String} [options.default=null] view to switch to if no previous view
1293 do_search: function(view) {
1295 on_sidebar_export: function() {
1296 new instance.web.DataExport(this, this.dataset).open();
1298 sidebar_context: function () {
1302 * Asks the view to reload itself, if the reloading is asynchronous should
1303 * return a {$.Deferred} indicating when the reloading is done.
1305 reload: function () {
1309 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1310 * An action is disabled by setting the corresponding attribute in the view's main element,
1311 * like: <form string="" create="false" edit="false" delete="false">
1313 is_action_enabled: function(action) {
1314 var attrs = this.fields_view.arch.attrs;
1315 return (action in attrs) ? JSON.parse(attrs[action]) : true;
1319 instance.web.xml_to_json = function(node) {
1320 switch (node.nodeType) {
1326 var attrs = $(node).getAttributes();
1327 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1330 attrs[key] = JSON.parse(attrs[key]);
1335 tag: node.tagName.toLowerCase(),
1337 children: _.map(node.childNodes, instance.web.xml_to_json)
1341 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1342 // For debugging purpose, this function will convert a json node back to xml
1343 indent = indent || 0;
1344 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1345 r = sindent + '<' + node.tag,
1346 cr = human_readable ? '\n' : '';
1348 if (typeof(node) === 'string') {
1349 return sindent + node;
1350 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1352 _.str.sprintf("Node [%s] is not a JSONified XML node",
1353 JSON.stringify(node)));
1355 for (var attr in node.attrs) {
1356 var vattr = node.attrs[attr];
1357 if (typeof(vattr) !== 'string') {
1359 vattr = JSON.stringify(vattr);
1361 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1362 if (human_readable) {
1363 vattr = vattr.replace(/"/g, "'");
1365 r += ' ' + attr + '="' + vattr + '"';
1367 if (node.children && node.children.length) {
1370 for (var i = 0, ii = node.children.length; i < ii; i++) {
1371 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1373 r += childs.join(cr);
1374 r += cr + sindent + '</' + node.tag + '>';
1380 instance.web.xml_to_str = function(node) {
1381 if (window.ActiveXObject) {
1384 return (new XMLSerializer()).serializeToString(node);
1387 instance.web.str_to_xml = function(s) {
1388 if (window.DOMParser) {
1389 var dp = new DOMParser();
1390 var r = dp.parseFromString(s, "text/xml");
1391 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1392 throw new Error("Could not parse string to xml");
1398 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1400 throw new Error("Could not find a DOM Parser: " + e.message);
1403 xDoc.preserveWhiteSpace = true;
1409 * Registry for all the main views
1411 instance.web.views = new instance.web.Registry();
1415 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: