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 = [];
19 this._super.apply(this, arguments);
20 this.$element.on('click', '.oe_breadcrumb_item', this.on_breadcrumb_clicked);
22 dialog_stop: function () {
24 this.dialog_widget.destroy();
25 this.dialog_widget = null;
26 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.$element.show();
56 this.widget.$element.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 on_breadcrumb_clicked: function(ev) {
69 var $e = $(ev.target);
70 var id = $e.data('id');
72 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
73 var it = this.breadcrumbs[i];
78 this.remove_breadcrumb(i);
80 var index = $e.parent().find('.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
82 this.inner_widget = item.widget;
84 clear_breadcrumbs: function() {
85 while (this.breadcrumbs.length) {
86 this.remove_breadcrumb(0);
89 remove_breadcrumb: function(index) {
90 var item = this.breadcrumbs.splice(index, 1)[0];
92 var dups = _.filter(this.breadcrumbs, function(it) {
93 return item.widget === it.widget;
100 get_title: function() {
102 for (var i = 0; i < this.breadcrumbs.length; i += 1) {
103 var item = this.breadcrumbs[i];
104 var tit = item.get_title();
105 if (!_.isArray(tit)) {
108 for (var j = 0; j < tit.length; j += 1) {
109 var label = _.escape(tit[j]);
110 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
113 titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
117 return titles.join(' <span class="oe_fade">/</span> ');
119 do_push_state: function(state) {
120 if (this.getParent() && this.getParent().do_push_state) {
121 if (this.inner_action) {
122 state['title'] = this.inner_action.name;
123 state['model'] = this.inner_action.res_model;
124 if (this.inner_action.id) {
125 state['action_id'] = this.inner_action.id;
128 this.getParent().do_push_state(state);
131 do_load_state: function(state, warm) {
134 if (state.action_id) {
135 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action_id;
138 action_loaded = this.do_action(state.action_id);
139 instance.webclient.menu.has_been_loaded.then(function() {
140 instance.webclient.menu.open_action(state.action_id);
143 } else if (state.model && state.id) {
144 // TODO handle context & domain ?
147 res_model: state.model,
149 type: 'ir.actions.act_window',
150 views: [[false, 'form']]
152 action_loaded = this.do_action(action);
153 } else if (state.sa) {
154 // load session action
157 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
159 return self.do_action(action);
162 } else if (state.client_action) {
164 var action = state.client_action;
165 if(_.isString(action)) {
171 this.ir_actions_client(action);
174 $.when(action_loaded || null).then(function() {
175 if (self.inner_widget && self.inner_widget.do_load_state) {
176 self.inner_widget.do_load_state(state, warm);
180 do_action: function(action, on_close) {
181 if (_.isNumber(action) || _.isString(action)) {
183 return self.rpc("/web/action/load", { action_id: action }, function(result) {
184 self.do_action(result.result, on_close);
188 console.error("No type for action", action);
191 var type = action.type.replace(/\./g,'_');
192 var popup = action.target === 'new';
193 var inline = action.target === 'inline';
194 action.flags = _.extend({
195 views_switcher : !popup && !inline,
196 search_view : !popup && !inline,
197 action_buttons : !popup && !inline,
198 sidebar : !popup && !inline,
199 pager : !popup && !inline,
200 display_title : !popup
201 }, action.flags || {});
202 if (!(type in this)) {
203 console.error("Action manager can't handle action of type " + action.type, action);
206 return this[type](action, on_close);
208 null_action: function() {
210 this.clear_breadcrumbs();
212 ir_actions_act_window: function (action, on_close) {
214 if (_(['base.module.upgrade', 'base.setup.installer'])
215 .contains(action.res_model)) {
216 var old_close = on_close;
217 on_close = function () {
218 instance.webclient.do_reload().then(old_close);
221 if (action.target === 'new') {
222 if (this.dialog === null) {
223 // These buttons will be overwrited by <footer> if any
224 this.dialog = new instance.web.Dialog(this, {
225 buttons: { "Close": function() { $(this).dialog("close"); }},
226 dialogClass: 'oe_act_window'
229 this.dialog.on_close.add(on_close);
231 this.dialog_widget.destroy();
233 this.dialog.dialog_title = action.name;
234 this.dialog_widget = new instance.web.ViewManagerAction(this, action);
235 this.dialog_widget.appendTo(this.dialog.$element);
240 return this.getParent().do_action(action, function () {
241 instance.webclient.menu.open_menu(action.menu_id);
244 this.inner_action = action;
245 var inner_widget = this.inner_widget = new instance.web.ViewManagerAction(this, action);
246 inner_widget.add_breadcrumb();
247 this.inner_widget.appendTo(this.$element);
250 ir_actions_act_window_close: function (action, on_closed) {
251 if (!this.dialog && on_closed) {
256 ir_actions_server: function (action, on_closed) {
258 this.rpc('/web/action/run', {
259 action_id: action.id,
260 context: action.context || {}
261 }).then(function (action) {
262 self.do_action(action, on_closed)
265 ir_actions_client: function (action) {
267 var ClientWidget = instance.web.client_actions.get_object(action.tag);
268 this.inner_widget = new ClientWidget(this, action.params);
269 this.push_breadcrumb({
270 widget: this.inner_widget,
273 this.inner_widget.appendTo(this.$element);
275 ir_actions_report_xml: function(action, on_closed) {
278 self.rpc("/web/session/eval_domain_and_context", {
279 contexts: [action.context],
281 }).then(function(res) {
282 action = _.clone(action);
283 action.context = res.context;
284 self.session.get_file({
286 data: {action: JSON.stringify(action)},
287 complete: $.unblockUI,
289 if (!self.dialog && on_closed) {
294 error: instance.webclient.crashmanager.on_rpc_error
298 ir_actions_act_url: function (action) {
299 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
301 ir_ui_menu: function (action) {
302 this.getParent().do_action(action);
306 instance.web.ViewManager = instance.web.Widget.extend({
307 template: "ViewManager",
308 init: function(parent, dataset, views, flags) {
310 this.model = dataset ? dataset.model : undefined;
311 this.dataset = dataset;
312 this.searchview = null;
313 this.active_view = null;
314 this.views_src = _.map(views, function(x) {
315 if (x instanceof Array) {
316 var View = instance.web.views.get_object(x[1], true);
320 label: View ? View.prototype.display_name : (void 'nope')
327 this.flags = flags || {};
328 this.registry = instance.web.views;
329 this.views_history = [];
332 * @returns {jQuery.Deferred} initial view loading promise
337 this.$element.find('.oe_view_manager_switch a').click(function() {
338 self.on_mode_switch($(this).data('view-type'));
341 _.each(this.views_src, function(view) {
342 self.views[view.view_type] = $.extend({}, view, {
343 deferred : $.Deferred(),
346 $buttons : self.$element.find('.oe_view_manager_buttons'),
347 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
348 $pager : self.$element.find('.oe_view_manager_pager'),
349 action : self.action,
350 action_views_ids : views_ids
351 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
353 views_ids[view.view_type] = view.view_id;
355 if (this.flags.views_switcher === false) {
356 this.$element.find('.oe_view_manager_switch').hide();
358 // If no default view defined, switch to the first one in sequence
359 var default_view = this.flags.default_view || this.views_src[0].view_type;
360 return this.on_mode_switch(default_view);
363 * Asks the view manager to switch visualization mode.
365 * @param {String} view_type type of view to display
366 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
367 * @returns {jQuery.Deferred} new view loading promise
369 on_mode_switch: function(view_type, no_store, view_options) {
371 var view = this.views[view_type];
374 return $.Deferred().reject();
377 this.views_history.push(view_type);
379 this.active_view = view_type;
381 if (!view.controller) {
382 view_promise = this.do_create_view(view_type);
383 } else if (this.searchview
384 && self.flags.auto_search
385 && view.controller.searchable !== false) {
386 this.searchview.ready.then(this.searchview.do_search);
389 if (this.searchview) {
390 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
394 .find('.oe_view_manager_switch a').parent().removeClass('active');
396 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
397 .parent().addClass('active');
399 $.when(view_promise).then(function () {
400 _.each(_.keys(self.views), function(view_name) {
401 var controller = self.views[view_name].controller;
403 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
404 if (view_name === view_type) {
406 controller.do_show(view_options || {});
409 controller.do_hide();
411 // put the <footer> in the dialog's buttonpane
412 if (self.$element.parent('.ui-dialog-content') && self.$element.find('footer')) {
413 self.$element.parent('.ui-dialog-content').parent().find('div.ui-dialog-buttonset').hide()
414 self.$element.find('footer').appendTo(
415 self.$element.parent('.ui-dialog-content').parent().find('div.ui-dialog-buttonpane')
423 do_create_view: function(view_type) {
424 // Lazy loading of views
426 var view = this.views[view_type];
427 var controllerclass = this.registry.get_object(view_type);
428 var options = _.clone(view.options);
429 if (view_type === "form" && this.action) {
430 switch (this.action.target) {
433 options.initial_mode = 'edit';
437 var controller = new controllerclass(this, this.dataset, view.view_id, options);
439 controller.on("change:title", this, function() {
440 if (self.active_view === view_type) {
441 self.set_title(controller.get('title'));
445 if (view.embedded_view) {
446 controller.set_embedded_view(view.embedded_view);
448 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
450 controller.do_prev_view.add_last(this.on_prev_view);
451 var container = this.$element.find(".oe_view_manager_view_" + view_type);
452 var view_promise = controller.appendTo(container);
453 this.views[view_type].controller = controller;
454 this.views[view_type].deferred.resolve(view_type);
455 return $.when(view_promise).then(function() {
456 self.on_controller_inited(view_type, controller);
458 && self.flags.auto_search
459 && view.controller.searchable !== false) {
460 self.searchview.ready.then(self.searchview.do_search);
464 set_title: function(title) {
465 this.$element.find('.oe_view_title_text:first').text(title);
467 add_breadcrumb: function() {
469 var views = [this.active_view || this.views_src[0].view_type];
470 this.on_mode_switch.add(function(mode) {
471 var last = views.slice(-1)[0];
473 if (mode !== 'form') {
479 this.getParent().push_breadcrumb({
481 show: function(index, $e) {
482 var view_to_select = views[index];
483 self.$element.show();
484 if (self.active_view !== view_to_select) {
485 self.on_mode_switch(view_to_select);
488 get_title: function() {
489 return _.map(views, function(v) {
490 return self.views[v].controller.get('title');
496 * Method used internally when a view asks to switch view. This method is meant
497 * to be extended by child classes to change the default behavior, which simply
498 * consist to switch to the asked view.
500 switch_view: function(view_type, no_store, options) {
501 return this.on_mode_switch(view_type, no_store, options);
504 * Returns to the view preceding the caller view in this manager's
505 * navigation history (the navigation history is appended to via
508 * @param {Object} [options]
509 * @param {Boolean} [options.created=false] resource was created
510 * @param {String} [options.default=null] view to switch to if no previous view
511 * @returns {$.Deferred} switching end signal
513 on_prev_view: function (options) {
514 options = options || {};
515 var current_view = this.views_history.pop();
516 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
517 if (options.created && current_view === 'form' && previous_view === 'list') {
518 // APR special case: "If creation mode from list (and only from a list),
519 // after saving, go to page view (don't come back in list)"
520 return this.on_mode_switch('form');
521 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
522 // APR special case: "If creation from dashboard, we have no previous view
523 return this.on_mode_switch('form');
525 return this.on_mode_switch(previous_view, true);
528 * Sets up the current viewmanager's search view.
530 * @param {Number|false} view_id the view to use or false for a default one
531 * @returns {jQuery.Deferred} search view startup deferred
533 setup_search_view: function(view_id, search_defaults) {
535 if (this.searchview) {
536 this.searchview.destroy();
538 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
540 this.searchview.on_search.add(this.do_searchview_search);
541 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
543 do_searchview_search: function(domains, contexts, groupbys) {
545 controller = this.views[this.active_view].controller,
546 action_context = this.action.context || {};
547 this.rpc('/web/session/eval_domain_and_context', {
548 domains: [this.action.domain || []].concat(domains || []),
549 contexts: [action_context].concat(contexts || []),
550 group_by_seq: groupbys || []
551 }, function (results) {
552 self.dataset._model = new instance.web.Model(
553 self.dataset.model, results.context, results.domain);
554 var groupby = results.group_by.length
556 : action_context.group_by;
557 if (_.isString(groupby)) {
560 controller.do_search(results.domain, results.context, groupby || []);
564 * Event launched when a controller has been inited.
566 * @param {String} view_type type of view
567 * @param {String} view the inited controller
569 on_controller_inited: function(view_type, view) {
572 * Called when one of the view want to execute an action
574 on_action: function(action) {
576 on_create: function() {
578 on_remove: function() {
580 on_edit: function() {
583 * Called by children view after executing an action
585 on_action_executed: function () {
589 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
590 template:"ViewManagerAction",
592 * @constructs instance.web.ViewManagerAction
593 * @extends instance.web.ViewManager
595 * @param {instance.web.ActionManager} parent parent object/widget
596 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
598 init: function(parent, action) {
599 // dataset initialization will take the session from ``this``, so if we
600 // do not have it yet (and we don't, because we've not called our own
601 // ``_super()``) rpc requests will blow up.
602 var flags = action.flags || {};
603 if (!('auto_search' in flags)) {
604 flags.auto_search = action.auto_search !== false;
606 if (action.res_model == 'board.board' && action.view_mode === 'form') {
607 // Special case for Dashboards
609 views_switcher : false,
610 display_title : false,
614 action_buttons : false
617 this._super(parent, null, action.views, flags);
618 this.session = parent.session;
619 this.action = action;
620 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
622 dataset.ids.push(action.res_id);
625 this.dataset = dataset;
627 // setup storage for session-wise menu hiding
628 if (this.session.hidden_menutips) {
631 this.session.hidden_menutips = {};
634 * Initializes the ViewManagerAction: sets up the searchview (if the
635 * searchview is enabled in the manager's action flags), calls into the
636 * parent to initialize the primary view and (if the VMA has a searchview)
637 * launches an initial search after both views are done rendering.
642 search_defaults = {};
643 _.each(this.action.context, function (value, key) {
644 var match = /^search_default_(.*)$/.exec(key);
646 search_defaults[match[1]] = value;
650 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
652 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
654 var main_view_loaded = this._super();
656 var manager_ready = $.when(searchview_loaded, main_view_loaded);
658 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
659 this.$element.addClass("oe_view_manager_" + (this.action.target || 'current'));
661 if (this.action.help && !this.flags.low_profile) {
662 var Users = new instance.web.DataSet(self, 'res.users'),
663 $tips = this.$element.find('.oe_view_manager_menu_tips');
664 $tips.delegate('blockquote button', 'click', function() {
666 //noinspection FallthroughInSwitchStatementJS
667 switch ($this.attr('name')) {
669 Users.write(self.session.uid, {menu_tips:false});
671 $this.closest('blockquote').hide();
672 self.session.hidden_menutips[self.action.id] = true;
675 if (!(self.action.id in self.session.hidden_menutips)) {
676 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
678 if (!(user && user.id === self.session.uid)) {
681 $tips.find('blockquote').toggle(user.menu_tips);
686 return manager_ready;
688 on_debug_changed: function (evt) {
690 $sel = $(evt.currentTarget),
691 $option = $sel.find('option:selected'),
693 current_view = this.views[this.active_view].controller;
696 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
697 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
700 var ids = current_view.get_selected_ids();
701 if (ids.length === 1) {
702 this.dataset.call('perm_read', [ids]).then(function(result) {
703 var dialog = new instance.web.Dialog(this, {
704 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
706 }, QWeb.render('ViewManagerDebugViewLog', {
708 format : instance.web.format_value
713 case 'toggle_layout_outline':
714 current_view.rendering_engine.toggle_layout_debugging();
717 this.dataset.call_and_eval(
718 'fields_get', [false, {}], null, 1).then(function (fields) {
719 var $root = $('<dl>');
720 _(fields).each(function (attributes, name) {
721 $root.append($('<dt>').append($('<h4>').text(name)));
722 var $attrs = $('<dl>').appendTo(
723 $('<dd>').appendTo($root));
724 _(attributes).each(function (def, name) {
725 if (def instanceof Object) {
726 def = JSON.stringify(def);
729 .append($('<dt>').text(name))
730 .append($('<dd style="white-space: pre-wrap;">').text(def));
733 new instance.web.Dialog(self, {
734 title: _.str.sprintf(_t("Model %s fields"),
736 width: '95%'}, $root).open();
740 if (current_view.fields_view && current_view.fields_view.arch) {
741 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
744 this.do_warn(_t("Manage Views"),
745 _t("Could not find current view declaration"));
748 case 'edit_workflow':
749 return this.do_action({
750 res_model : 'workflow',
751 domain : [['osv', '=', this.dataset.model]],
752 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
753 type : 'ir.actions.act_window',
759 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
761 case 'manage_filters':
763 res_model: 'ir.filters',
764 views: [[false, 'list'], [false, 'form']],
765 type: 'ir.actions.act_window',
767 search_default_my_filters: true,
768 search_default_model_id: this.dataset.model
774 console.log("No debug handler for ", val);
777 evt.currentTarget.selectedIndex = 0;
779 do_edit_resource: function(model, id, action) {
780 var action = _.extend({
783 type : 'ir.actions.act_window',
786 views : [[false, 'form']],
789 action_buttons : true,
791 resize_textareas : true
795 this.do_action(action);
797 on_mode_switch: function (view_type, no_store, options) {
800 return $.when(this._super.apply(this, arguments)).then(function () {
801 var controller = self.views[self.active_view].controller,
802 fvg = controller.fields_view,
803 view_id = (fvg && fvg.view_id) || '--';
804 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
811 do_create_view: function(view_type) {
812 var r = this._super.apply(this, arguments);
813 var view = this.views[view_type].controller;
814 view.set({ 'title': this.action.name });
817 set_title: function(title) {
818 this.$element.find('.oe_breadcrumb_title:first').html(this.getParent().get_title());
820 do_push_state: function(state) {
821 if (this.getParent() && this.getParent().do_push_state) {
822 state["view_type"] = this.active_view;
823 this.getParent().do_push_state(state);
826 do_load_state: function(state, warm) {
829 if (state.view_type && state.view_type !== this.active_view) {
831 this.views[this.active_view].deferred.pipe(function() {
832 return self.on_mode_switch(state.view_type, true);
837 $.when(defs).then(function() {
838 self.views[self.active_view].controller.do_load_state(state, warm);
843 instance.web.Sidebar = instance.web.Widget.extend({
844 init: function(parent) {
847 var view = this.getParent();
849 { 'name' : 'print', 'label' : _t('Print'), },
850 { 'name' : 'files', 'label' : _t('Attachment'), },
851 { 'name' : 'other', 'label' : _t('More'), }
858 if (this.session.uid === 1) {
859 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
860 this.items.other.push(item);
862 this.fileupload_id = _.uniqueId('oe_fileupload');
863 $(window).on(this.fileupload_id, function() {
864 var args = [].slice.call(arguments).slice(1);
865 if (args[0] && args[0].error) {
866 alert(args[0].error);
868 self.do_attachement_update(self.dataset, self.model_id);
877 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
878 var section = $(this).data('section');
879 var index = $(this).data('index');
880 var item = self.items[section][index];
882 item.callback.apply(self, [item]);
883 } else if (item.action) {
884 self.on_item_action_clicked(item);
885 } else if (item.url) {
888 event.preventDefault();
893 self.$element.html(QWeb.render('Sidebar', {widget: self}));
895 // Hides Sidebar sections when item list is empty
896 this.$('.oe_form_dropdown_section').each(function() {
897 $(this).toggle(!!$(this).find('li').length);
901 * For each item added to the section:
904 * will be used as the item's name in the sidebar, can be html
907 * descriptor for the action which will be executed, ``action`` and
908 * ``callback`` should be exclusive
911 * function to call when the item is clicked in the sidebar, called
912 * with the item descriptor as its first argument (so information
913 * can be stored as additional keys on the object passed to
916 * ``classname`` (optional)
917 * ``@class`` set on the sidebar serialization of the item
919 * ``title`` (optional)
920 * will be set as the item's ``@title`` (tooltip)
922 * @param {String} section_code
923 * @param {Array<{label, action | callback[, classname][, title]}>} items
925 add_items: function(section_code, items) {
928 this.items[section_code].push.apply(this.items[section_code],items);
932 add_toolbar: function(toolbar) {
934 _.each(['print','action','relate'], function(type) {
935 var items = toolbar[type];
937 for (var i = 0; i < items.length; i++) {
939 label: items[i]['name'],
941 classname: 'oe_sidebar_' + type
944 self.add_items(type=='print' ? 'print' : 'other', items);
948 on_item_action_clicked: function(item) {
950 self.getParent().sidebar_context().then(function (context) {
951 var ids = self.getParent().get_selected_ids();
952 if (ids.length == 0) {
953 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
956 var additional_context = _.extend({
959 active_model: self.getParent().dataset.model
961 self.rpc("/web/action/load", {
962 action_id: item.action.id,
963 context: additional_context
964 }, function(result) {
965 result.result.context = _.extend(result.result.context || {},
967 result.result.flags = result.result.flags || {};
968 result.result.flags.new_window = true;
969 self.do_action(result.result, function () {
971 self.getParent().reload();
976 do_attachement_update: function(dataset, model_id) {
977 this.dataset = dataset;
978 this.model_id = model_id;
980 this.on_attachments_loaded([]);
982 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
983 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
984 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
987 on_attachments_loaded: function(attachments) {
990 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
991 _.each(attachments,function(a) {
993 if(a.type === "binary") {
994 a.url = prefix + a.id + '&t=' + (new Date().getTime());
997 self.items['files'] = attachments;
999 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1000 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1002 on_attachment_changed: function(e) {
1003 var $e = $(e.target);
1004 if ($e.val() !== '') {
1005 this.$element.find('form.oe_form_binary_form').submit();
1006 $e.parent().find('input[type=file]').prop('disabled', true);
1007 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1008 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1012 on_attachment_delete: function(e) {
1015 e.stopPropagation();
1017 var $e = $(e.currentTarget);
1018 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1019 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1020 self.do_attachement_update(self.dataset, self.model_id);
1026 instance.web.TranslateDialog = instance.web.Dialog.extend({
1027 dialog_title: {toString: function () { return _t("Translations"); }},
1028 init: function(view) {
1029 // TODO fme: should add the language to fields_view_get because between the fields view get
1030 // and the moment the user opens the translation dialog, the user language could have been changed
1031 this.view_language = view.session.user_context.lang;
1032 this['on_button_' + _t("Save")] = this.on_btn_save;
1033 this['on_button_' + _t("Close")] = this.on_btn_close;
1039 this.view_type = view.fields_view.type || '';
1040 this.$fields_form = null;
1041 this.$view_form = null;
1042 this.$sidebar_form = null;
1043 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
1044 this.languages = null;
1045 this.languages_loaded = $.Deferred();
1046 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
1047 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
1052 $.when(this.languages_loaded).then(function() {
1053 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
1054 self.$fields_form = self.$element.find('.oe_translation_form');
1055 self.$fields_form.find('.oe_trad_field').change(function() {
1056 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
1061 on_languages_loaded: function(langs) {
1062 this.languages = langs;
1063 this.languages_loaded.resolve();
1065 do_load_fields_values: function(callback) {
1068 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1069 _.each(self.languages, function(lg) {
1070 var deff = $.Deferred();
1071 deffered.push(deff);
1072 var callback = function(values) {
1073 _.each(self.translatable_fields_keys, function(f) {
1074 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1078 if (lg.code === self.view_language) {
1080 _.each(self.translatable_fields_keys, function(field) {
1081 values[field] = self.view.fields[field].get_value();
1085 self.rpc('/web/dataset/get', {
1086 model: self.view.dataset.model,
1087 ids: [self.view.datarecord.id],
1088 fields: self.translatable_fields_keys,
1089 context: self.view.dataset.get_context({
1094 $.when.apply(null, deffered).then(callback);
1096 open: function(field) {
1099 $.when(this.languages_loaded).then(function() {
1100 if (self.view.translatable_fields && self.view.translatable_fields.length) {
1101 self.do_load_fields_values(function() {
1104 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1105 self.$element.scrollTo($field_input);
1106 $field_input.focus();
1114 on_btn_save: function() {
1117 trads_mutex = new $.Mutex();
1118 self.$fields_form.find('.oe_trad_field.touched').each(function() {
1119 var field = $(this).attr('name').split('-');
1120 if (!trads[field[0]]) {
1121 trads[field[0]] = {};
1123 trads[field[0]][field[1]] = $(this).val();
1125 _.each(trads, function(data, code) {
1126 if (code === self.view_language) {
1127 _.each(data, function(value, field) {
1128 self.view.fields[field].set_value(value);
1131 trads_mutex.exec(function() {
1132 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1137 on_btn_close: function() {
1142 instance.web.View = instance.web.Widget.extend({
1143 template: "EmptyComponent",
1144 // name displayed in view switchers
1147 * Define a view type for each view to allow automatic call to fields_view_get.
1149 view_type: undefined,
1150 init: function(parent, dataset, view_id, options) {
1151 this._super(parent);
1152 this.dataset = dataset;
1153 this.view_id = view_id;
1154 this.set_default_options(options);
1157 return this.load_view();
1159 load_view: function() {
1160 if (this.embedded_view) {
1161 var def = $.Deferred();
1163 $.async_when().then(function() {def.resolve(self.embedded_view);});
1164 return def.pipe(this.on_loaded);
1166 var context = new instance.web.CompoundContext(this.dataset.get_context());
1167 if (! this.view_type)
1168 console.warn("view_type is not defined", this);
1169 return this.rpc("/web/view/load", {
1170 "model": this.dataset.model,
1171 "view_id": this.view_id,
1172 "view_type": this.view_type,
1173 toolbar: !!this.options.$sidebar,
1175 }).pipe(this.on_loaded);
1179 * Called after a successful call to fields_view_get.
1180 * Must return a promise.
1182 on_loaded: function(fields_view_get) {
1184 set_default_options: function(options) {
1185 this.options = options || {};
1186 _.defaults(this.options, {
1187 // All possible views options should be defaulted here
1191 action_views_ids: {}
1194 open_translate_dialog: function(field) {
1195 if (!this.translate_dialog) {
1196 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1198 this.translate_dialog.open(field);
1201 * Fetches and executes the action identified by ``action_data``.
1203 * @param {Object} action_data the action descriptor data
1204 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1205 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1206 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1207 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1208 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1209 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1210 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1212 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1214 var result_handler = function () {
1215 if (on_closed) { on_closed.apply(null, arguments); }
1216 if (self.getParent() && self.getParent().on_action_executed) {
1217 return self.getParent().on_action_executed.apply(null, arguments);
1220 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1222 var handler = function (r) {
1223 var action = r.result;
1224 if (action && action.constructor == Object) {
1225 var ncontext = new instance.web.CompoundContext(context);
1228 active_id: record_id,
1229 active_ids: [record_id],
1230 active_model: dataset.model
1233 ncontext.add(action.context || {});
1234 return self.rpc('/web/session/eval_domain_and_context', {
1235 contexts: [ncontext],
1237 }).pipe(function (results) {
1238 action.context = results.context;
1239 /* niv: previously we were overriding once more with action_data.context,
1240 * I assumed this was not a correct behavior and removed it
1242 return self.do_action(action, result_handler);
1245 return result_handler();
1249 if (action_data.special) {
1250 return handler({result: {"type":"ir.actions.act_window_close"}});
1251 } else if (action_data.type=="object") {
1252 var args = [[record_id]], additional_args = [];
1253 if (action_data.args) {
1255 // Warning: quotes and double quotes problem due to json and xml clash
1256 // Maybe we should force escaping in xml or do a better parse of the args array
1257 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1258 args = args.concat(additional_args);
1260 console.error("Could not JSON.parse arguments", action_data.args);
1264 return dataset.call_button(action_data.name, args, handler);
1265 } else if (action_data.type=="action") {
1266 return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}, handler);
1268 return dataset.exec_workflow(record_id, action_data.name, handler);
1272 * Directly set a view to use instead of calling fields_view_get. This method must
1273 * be called before start(). When an embedded view is set, underlying implementations
1274 * of instance.web.View must use the provided view instead of any other one.
1276 * @param embedded_view A view.
1278 set_embedded_view: function(embedded_view) {
1279 this.embedded_view = embedded_view;
1281 do_show: function () {
1282 this.$element.show();
1284 do_hide: function () {
1285 this.$element.hide();
1287 do_push_state: function(state) {
1288 if (this.getParent() && this.getParent().do_push_state) {
1289 this.getParent().do_push_state(state);
1292 do_load_state: function(state, warm) {
1295 * Switches to a specific view type
1297 * @param {String} view view type to switch to
1299 do_switch_view: function(view) {
1302 * Cancels the switch to the current view, switches to the previous one
1304 * @param {Object} [options]
1305 * @param {Boolean} [options.created=false] resource was created
1306 * @param {String} [options.default=null] view to switch to if no previous view
1308 do_prev_view: function (options) {
1310 do_search: function(view) {
1312 on_sidebar_import: function() {
1313 var import_view = new instance.web.DataImport(this, this.dataset);
1314 import_view.start();
1316 on_sidebar_export: function() {
1317 var export_view = new instance.web.DataExport(this, this.dataset);
1318 export_view.start();
1320 on_sidebar_translate: function() {
1321 return this.do_action({
1322 res_model : 'ir.translation',
1323 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1324 views: [[false, 'list'], [false, 'form']],
1325 type : 'ir.actions.act_window',
1330 sidebar_context: function () {
1334 * Asks the view to reload itself, if the reloading is asynchronous should
1335 * return a {$.Deferred} indicating when the reloading is done.
1337 reload: function () {
1342 instance.web.xml_to_json = function(node) {
1343 switch (node.nodeType) {
1349 var attrs = $(node).getAttributes();
1350 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1353 attrs[key] = JSON.parse(attrs[key]);
1358 tag: node.tagName.toLowerCase(),
1360 children: _.map(node.childNodes, instance.web.xml_to_json)
1364 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1365 // For debugging purpose, this function will convert a json node back to xml
1366 // Maybe useful for xml view editor
1367 indent = indent || 0;
1368 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1369 r = sindent + '<' + node.tag,
1370 cr = human_readable ? '\n' : '';
1372 if (typeof(node) === 'string') {
1373 return sindent + node;
1374 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1375 throw("Node a json node");
1377 for (var attr in node.attrs) {
1378 var vattr = node.attrs[attr];
1379 if (typeof(vattr) !== 'string') {
1381 vattr = JSON.stringify(vattr);
1383 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1384 if (human_readable) {
1385 vattr = vattr.replace(/"/g, "'");
1387 r += ' ' + attr + '="' + vattr + '"';
1389 if (node.children && node.children.length) {
1392 for (var i = 0, ii = node.children.length; i < ii; i++) {
1393 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1395 r += childs.join(cr);
1396 r += cr + sindent + '</' + node.tag + '>';
1402 instance.web.xml_to_str = function(node) {
1403 if (window.ActiveXObject) {
1406 return (new XMLSerializer()).serializeToString(node);
1409 instance.web.str_to_xml = function(s) {
1410 if (window.DOMParser) {
1411 var dp = new DOMParser();
1412 var r = dp.parseFromString(s, "text/xml");
1413 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1414 throw new Error("Could not parse string to xml");
1420 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1422 throw new Error("Could not find a DOM Parser: " + e.message);
1425 xDoc.preserveWhiteSpace = true;
1431 * Registry for all the main views
1433 instance.web.views = new instance.web.Registry();
1437 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: