1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
5 openerp.web.views = function(session) {
6 var QWeb = session.web.qweb,
10 * Registry for all the client actions key: tag value: widget
12 session.web.client_actions = new session.web.Registry();
15 * Registry for all the main views
17 session.web.views = new session.web.Registry();
19 session.web.ActionManager = session.web.Widget.extend({
20 identifier_prefix: "actionmanager",
21 init: function(parent) {
23 this.inner_viewmanager = null;
25 this.dialog_viewmanager = null;
26 this.client_widget = null;
29 return "<div id='"+this.element_id+"'></div>";
31 dialog_stop: function () {
33 this.dialog_viewmanager.stop();
34 this.dialog_viewmanager = null;
39 content_stop: function () {
40 if (this.inner_viewmanager) {
41 this.inner_viewmanager.stop();
42 this.inner_viewmanager = null;
44 if (this.client_widget) {
45 this.client_widget.stop();
46 this.client_widget = null;
50 do_push_state: function(state, overwrite) {
53 do_load_state: function(state) {
54 if (state.action_id) {
56 this.do_action(state.action_id);
58 else if (state.model && state.id) {
63 else if (state.client_action) {
65 this.ir_actions_client(state.client_action);
68 if (this.inner_viewmanager) {
69 this.inner_viewmanager.do_load_state(state);
73 do_action: function(action, on_close) {
74 if (_.isNumber(action)) {
76 self.rpc("/web/action/load", { action_id: action }, function(result) {
77 self.do_action(result.result, on_close);
82 console.error("No type for action", action);
85 var type = action.type.replace(/\./g,'_');
86 var popup = action.target === 'new';
87 action.flags = _.extend({
88 views_switcher : !popup,
90 action_buttons : !popup,
93 }, action.flags || {});
94 if (!(type in this)) {
95 console.error("Action manager can't handle action of type " + action.type, action);
98 return this[type](action, on_close);
100 null_action: function() {
104 ir_actions_act_window: function (action, on_close) {
105 if (_(['base.module.upgrade', 'base.setup.installer'])
106 .contains(action.res_model)) {
107 var old_close = on_close;
108 on_close = function () {
109 session.webclient.do_reload();
110 if (old_close) { old_close(); }
113 if (action.target === 'new') {
114 if (this.dialog == null) {
115 this.dialog = new session.web.Dialog(this, { title: action.name, width: '80%' });
117 this.dialog.on_close.add(on_close);
120 this.dialog_viewmanager.stop();
122 this.dialog_viewmanager = new session.web.ViewManagerAction(this, action);
123 this.dialog_viewmanager.appendTo(this.dialog.$element);
128 this.inner_viewmanager = new session.web.ViewManagerAction(this, action);
129 this.inner_viewmanager.do_push_state.add(this.do_push_state);
130 this.inner_viewmanager.appendTo(this.$element);
132 this.do_push_state({action_id: action.id}, true);
136 ir_actions_act_window_close: function (action, on_closed) {
137 if (!this.dialog && on_closed) {
142 ir_actions_server: function (action, on_closed) {
144 this.rpc('/web/action/run', {
145 action_id: action.id,
146 context: action.context || {}
147 }).then(function (action) {
148 self.do_action(action, on_closed)
151 ir_actions_client: function (action) {
153 var ClientWidget = session.web.client_actions.get_object(action.tag);
154 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this);
156 var client_action = {tag: action.tag};
157 if (action.params) _.extend(client_action, {params: action.params});
158 this.do_push_state({client_action: client_action}, true);
160 ir_actions_report_xml: function(action, on_closed) {
163 self.rpc("/web/session/eval_domain_and_context", {
164 contexts: [action.context],
166 }).then(function(res) {
167 action = _.clone(action);
168 action.context = res.context;
169 self.session.get_file({
171 data: {action: JSON.stringify(action)},
172 complete: $.unblockUI,
174 if (!self.dialog && on_closed) {
182 ir_actions_act_url: function (action) {
183 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
185 ir_ui_menu: function (action) {
186 this.widget_parent.do_action(action);
190 session.web.ViewManager = session.web.Widget.extend(/** @lends session.web.ViewManager# */{
191 identifier_prefix: "viewmanager",
192 template: "ViewManager",
194 * @constructs session.web.ViewManager
195 * @extends session.web.Widget
201 init: function(parent, dataset, views) {
203 this.model = dataset ? dataset.model : undefined;
204 this.dataset = dataset;
205 this.searchview = null;
206 this.active_view = null;
207 this.views_src = _.map(views, function(x) {return x instanceof Array? {view_id: x[0], view_type: x[1]} : x;});
209 this.flags = this.flags || {};
210 this.registry = session.web.views;
211 this.views_history = [];
214 return session.web.qweb.render(this.template, {
216 prefix: this.element_id,
217 views: this.views_src});
220 * @returns {jQuery.Deferred} initial view loading promise
225 this.$element.find('.oe_vm_switch button').click(function() {
226 self.on_mode_switch($(this).data('view-type'));
229 _.each(this.views_src, function(view) {
230 self.views[view.view_type] = $.extend({}, view, {
231 deferred : $.Deferred(),
234 sidebar_id : self.element_id + '_sidebar_' + view.view_type,
235 action : self.action,
236 action_views_ids : views_ids
237 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
239 views_ids[view.view_type] = view.view_id;
241 if (this.flags.views_switcher === false) {
242 this.$element.find('.oe_vm_switch').hide();
244 // If no default view defined, switch to the first one in sequence
245 var default_view = this.flags.default_view || this.views_src[0].view_type;
246 return this.on_mode_switch(default_view);
249 * Asks the view manager to switch visualization mode.
251 * @param {String} view_type type of view to display
252 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
253 * @returns {jQuery.Deferred} new view loading promise
255 on_mode_switch: function(view_type, no_store) {
257 view = this.views[view_type],
260 return $.Deferred().reject();
263 this.views_history.push(view_type);
265 this.active_view = view_type;
267 if (!view.controller) {
268 // Lazy loading of views
269 var controllerclass = this.registry.get_object(view_type);
270 var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
271 if (view.embedded_view) {
272 controller.set_embedded_view(view.embedded_view);
274 controller.do_switch_view.add_last(this.on_mode_switch);
275 controller.do_prev_view.add_last(this.on_prev_view);
276 var container = $("#" + this.element_id + '_view_' + view_type);
277 view_promise = controller.appendTo(container);
278 this.views[view_type].controller = controller;
279 this.views[view_type].deferred.resolve(view_type);
280 $.when(view_promise).then(function() {
281 self.on_controller_inited(view_type, controller);
282 if (self.searchview && view.controller.searchable !== false) {
283 self.searchview.ready.then(self.searchview.do_search);
286 } else if (this.searchview && view.controller.searchable !== false) {
287 this.searchview.ready.then(this.searchview.do_search);
290 if (this.searchview) {
291 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
295 .find('.oe_vm_switch button').removeAttr('disabled')
296 .filter('[data-view-type="' + view_type + '"]')
297 .attr('disabled', true);
299 for (var view_name in this.views) {
300 if (!this.views.hasOwnProperty(view_name)) { continue; }
301 if (this.views[view_name].controller) {
302 if (view_name === view_type) {
303 $.when(view_promise).then(this.views[view_name].controller.do_show);
305 this.views[view_name].controller.do_hide();
309 $.when(view_promise).then(function () {
310 self.$element.find('.oe_view_title_text:first').text(
311 self.display_title());
318 * Returns to the view preceding the caller view in this manager's
319 * navigation history (the navigation history is appended to via
322 * @param {Boolean} [created=false] returning from a creation
323 * @returns {$.Deferred} switching end signal
325 on_prev_view: function (created) {
326 var current_view = this.views_history.pop();
327 var previous_view = this.views_history[this.views_history.length - 1];
328 // APR special case: "If creation mode from list (and only from a list),
329 // after saving, go to page view (don't come back in list)"
330 if (created && current_view === 'form' && previous_view === 'list') {
331 return this.on_mode_switch('page');
333 return this.on_mode_switch(previous_view, true);
336 * Sets up the current viewmanager's search view.
338 * @param {Number|false} view_id the view to use or false for a default one
339 * @returns {jQuery.Deferred} search view startup deferred
341 setup_search_view: function(view_id, search_defaults) {
343 if (this.searchview) {
344 this.searchview.stop();
346 this.searchview = new session.web.SearchView(
348 view_id, search_defaults, this.flags.search_view === false);
350 this.searchview.on_search.add(this.do_searchview_search);
351 return this.searchview.appendTo($("#" + this.element_id + "_search"));
353 do_searchview_search: function(domains, contexts, groupbys) {
355 controller = this.views[this.active_view].controller,
356 action_context = this.action.context || {};
357 this.rpc('/web/session/eval_domain_and_context', {
358 domains: [this.action.domain || []].concat(domains || []),
359 contexts: [action_context].concat(contexts || []),
360 group_by_seq: groupbys || []
361 }, function (results) {
362 self.dataset.context = results.context;
363 self.dataset.domain = results.domain;
364 var groupby = results.group_by.length
366 : action_context.group_by;
367 controller.do_search(results.domain, results.context, groupby || []);
371 * Event launched when a controller has been inited.
373 * @param {String} view_type type of view
374 * @param {String} view the inited controller
376 on_controller_inited: function(view_type, view) {
379 * Called when one of the view want to execute an action
381 on_action: function(action) {
383 on_create: function() {
385 on_remove: function() {
387 on_edit: function() {
390 * Called by children view after executing an action
392 on_action_executed: function () {},
393 display_title: function () {
394 var view = this.views[this.active_view];
397 return view.controller.fields_view.arch.attrs.string;
403 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
404 template:"ViewManagerAction",
406 * @constructs session.web.ViewManagerAction
407 * @extends session.web.ViewManager
409 * @param {session.web.ActionManager} parent parent object/widget
410 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
412 init: function(parent, action) {
413 // dataset initialization will take the session from ``this``, so if we
414 // do not have it yet (and we don't, because we've not called our own
415 // ``_super()``) rpc requests will blow up.
416 this._super(parent, null, action.views);
417 this.session = parent.session;
418 this.action = action;
419 var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
421 dataset.ids.push(action.res_id);
424 this.dataset = dataset;
425 this.flags = this.action.flags || {};
426 if (action.res_model == 'board.board' && action.view_mode === 'form') {
427 // Special case for Dashboards
428 _.extend(this.flags, {
429 views_switcher : false,
430 display_title : false,
434 action_buttons : false
438 // setup storage for session-wise menu hiding
439 if (this.session.hidden_menutips) {
442 this.session.hidden_menutips = {}
445 * Initializes the ViewManagerAction: sets up the searchview (if the
446 * searchview is enabled in the manager's action flags), calls into the
447 * parent to initialize the primary view and (if the VMA has a searchview)
448 * launches an initial search after both views are done rendering.
453 search_defaults = {};
454 _.each(this.action.context, function (value, key) {
455 var match = /^search_default_(.*)$/.exec(key);
457 search_defaults[match[1]] = value;
461 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
463 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
465 var main_view_loaded = this._super();
467 _.each(_.keys(this.views), function(view_type) {
468 $.when(self.views[view_type].deferred).done(function(view_type) {
469 self.views[view_type].controller.do_push_state.add(self.do_push_state);
473 var manager_ready = $.when(searchview_loaded, main_view_loaded);
475 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
477 if (this.action.help && !this.flags.low_profile) {
478 var Users = new session.web.DataSet(self, 'res.users'),
479 $tips = this.$element.find('.oe_view_manager_menu_tips');
480 $tips.delegate('blockquote button', 'click', function() {
482 //noinspection FallthroughInSwitchStatementJS
483 switch ($this.attr('name')) {
485 Users.write(self.session.uid, {menu_tips:false});
487 $this.closest('blockquote').hide();
488 self.session.hidden_menutips[self.action.id] = true;
491 if (!(self.action.id in self.session.hidden_menutips)) {
492 Users.read_ids([this.session.uid], ['menu_tips'], function(users) {
494 if (!(user && user.id === self.session.uid)) {
497 $tips.find('blockquote').toggle(user.menu_tips);
502 var $res_logs = this.$element.find('.oe-view-manager-logs:first');
503 $res_logs.delegate('a.oe-more-logs', 'click', function () {
504 $res_logs.removeClass('oe-folded');
506 }).delegate('a.oe-remove-everything', 'click', function () {
507 $res_logs.removeClass('oe-has-more')
512 return manager_ready;
514 on_debug_changed: function (evt) {
515 var $sel = $(evt.currentTarget),
516 $option = $sel.find('option:selected'),
520 $('<pre>').text(session.web.json_node_to_xml(
521 this.views[this.active_view].controller.fields_view.arch, true)
522 ).dialog({ width: '95%'});
525 var model = $option.data('model'),
526 id = $option.data('id'),
527 domain = $option.data('domain'),
530 type : 'ir.actions.act_window',
535 action_buttons : true
540 action.views = [[false, 'form']];
542 action.views = [[false, 'list'], [false, 'form']];
543 action.domain = domain;
544 action.flags.views_switcher = true;
546 this.do_action(action);
550 console.log("No debug handler for ", val);
553 evt.currentTarget.selectedIndex = 0;
555 on_mode_switch: function (view_type, no_store) {
558 return $.when(this._super(view_type, no_store)).then(function () {
559 self.shortcut_check(self.views[view_type]);
561 self.$element.find('.oe-view-manager-logs:first')
562 .addClass('oe-folded').removeClass('oe-has-more')
565 var controller = self.views[self.active_view].controller,
566 fvg = controller.fields_view,
567 view_id = (fvg && fvg.view_id) || '--';
568 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
572 if (!self.action.name && fvg) {
573 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
576 var $title = self.$element.find('.oe_view_title_text'),
577 $search_prefix = $title.find('span.oe_searchable_view');
578 if (controller.searchable !== false) {
579 if (!$search_prefix.length) {
580 $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
583 $search_prefix.remove();
586 self.do_push_state({view_type: self.active_view});
590 do_push_state: function(state, overwrite) {
593 do_load_state: function(state) {
595 $.when(this.on_mode_switch(state.view_type, true)).done(function() {
596 self.views[self.active_view].controller.do_load_state(state);
600 shortcut_check : function(view) {
602 var grandparent = this.widget_parent && this.widget_parent.widget_parent;
603 // display shortcuts if on the first view for the action
604 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
605 if (!(grandparent instanceof session.web.WebClient) ||
606 !(view.view_type === this.views_src[0].view_type
607 && view.view_id === this.views_src[0].view_id)) {
608 $shortcut_toggle.hide();
611 $shortcut_toggle.removeClass('oe-shortcut-remove').show();
612 if (_(this.session.shortcuts).detect(function (shortcut) {
613 return shortcut.res_id === self.session.active_id; })) {
614 $shortcut_toggle.addClass("oe-shortcut-remove");
616 this.shortcut_add_remove();
618 shortcut_add_remove: function() {
620 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
624 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
625 $(self.session.shortcuts.binding).trigger('remove-current');
626 $shortcut_toggle.removeClass("oe-shortcut-remove");
628 $(self.session.shortcuts.binding).trigger('add', {
629 'user_id': self.session.uid,
630 'res_id': self.session.active_id,
631 'resource': 'ir.ui.menu',
632 'name': self.action.name
634 $shortcut_toggle.addClass("oe-shortcut-remove");
639 * Intercept do_action resolution from children views
641 on_action_executed: function () {
642 return new session.web.DataSet(this, 'res.log')
643 .call('get', [], this.do_display_log);
646 * @param {Array<Object>} log_records
648 do_display_log: function (log_records) {
651 $logs = this.$element.find('.oe-view-manager-logs:first')
652 .addClass('oe-folded'),
653 $logs_list = $logs.find('ul').empty();
654 $logs.toggleClass('oe-has-more', log_records.length > cutoff);
655 _(log_records.reverse()).each(function (record) {
656 $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
657 .appendTo($logs_list)
658 .delegate('a', 'click', function (e) {
660 type: 'ir.actions.act_window',
661 res_model: record.res_model,
662 res_id: record.res_id,
663 // TODO: need to have an evaluated context here somehow
664 //context: record.context,
665 views: [[false, 'form']]
671 display_title: function () {
672 return this.action.name;
676 session.web.Sidebar = session.web.Widget.extend({
677 init: function(parent, element_id) {
678 this._super(parent, element_id);
685 this.$element.html(session.web.qweb.render('Sidebar'));
686 this.$element.find(".toggle-sidebar").click(function(e) {
690 add_default_sections: function() {
692 view = this.widget_parent,
693 view_manager = view.widget_parent,
694 action = view_manager.action;
695 if (this.session.uid === 1) {
696 this.add_section(_t('Customize'), 'customize');
697 this.add_items('customize', [
699 label: _t("Manage Views"),
700 callback: view.on_sidebar_manage_views,
701 title: _t("Manage views of the current object")
703 label: _t("Edit Workflow"),
704 callback: view.on_sidebar_edit_workflow,
705 title: _t("Manage views of the current object"),
706 classname: 'oe_hide oe_sidebar_edit_workflow'
708 label: _t("Customize Object"),
709 callback: view.on_sidebar_customize_object,
710 title: _t("Manage views of the current object")
712 label: _t("Translate"),
713 callback: view.on_sidebar_translate,
714 title: _t("Technical translation")
719 this.add_section(_t('Other Options'), 'other');
720 this.add_items('other', [
723 callback: view.on_sidebar_import
726 callback: view.on_sidebar_export
728 label: _t("View Log"),
729 callback: view.on_sidebar_view_log,
730 classname: 'oe_hide oe_sidebar_view_log'
735 add_toolbar: function(toolbar) {
737 _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
738 var items = toolbar[type[0]];
740 for (var i = 0; i < items.length; i++) {
742 label: items[i]['name'],
744 classname: 'oe_sidebar_' + type[0]
747 self.add_section(type[1], type[0]);
748 self.add_items(type[0], items);
753 add_section: function(name, code) {
754 if(!code) code = _.str.underscored(name);
755 var $section = this.sections[code];
758 var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
759 $section = $(session.web.qweb.render("Sidebar.section", {
760 section_id: section_id,
762 classname: 'oe_sidebar_' + code
764 $section.appendTo(this.$element.find('div.sidebar-actions'));
765 this.sections[code] = $section;
770 add_items: function(section_code, items) {
771 // An item is a dictonary : {
772 // label: label to be displayed for the link,
773 // action: action to be launch when the link is clicked,
774 // callback: a function to be executed when the link is clicked,
775 // classname: optional dom class name for the line,
776 // title: optional title for the link
778 // Note: The item should have one action or/and a callback
782 $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
783 section_id = $section.attr('id');
786 for (var i = 0; i < items.length; i++) {
787 items[i].element_id = _.uniqueId(section_id + '_item_');
788 this.items[items[i].element_id] = items[i];
791 var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
793 $items.find('a.oe_sidebar_action_a').click(function() {
794 var item = self.items[$(this).attr('id')];
796 item.callback.apply(self, [item]);
799 self.on_item_action_clicked(item);
804 var $ul = $section.find('ul');
806 $ul = $('<ul/>').appendTo($section);
808 $items.appendTo($ul);
811 on_item_action_clicked: function(item) {
813 self.widget_parent.sidebar_context().then(function (context) {
814 var ids = self.widget_parent.get_selected_ids();
815 if (ids.length == 0) {
816 //TODO: make prettier warning?
817 $("<div />").text(_t("You must choose at least one record.")).dialog({
818 title: _t("Warning"),
823 var additional_context = _.extend({
826 active_model: self.widget_parent.dataset.model
828 self.rpc("/web/action/load", {
829 action_id: item.action.id,
830 context: additional_context
831 }, function(result) {
832 result.result.context = _.extend(result.result.context || {},
834 result.result.flags = result.result.flags || {};
835 result.result.flags.new_window = true;
836 self.do_action(result.result);
840 do_fold: function() {
841 this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
843 do_unfold: function() {
844 this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
846 do_toggle: function() {
847 this.$element.toggleClass('open-sidebar closed-sidebar');
851 session.web.TranslateDialog = session.web.Dialog.extend({
852 dialog_title: _t("Translations"),
853 init: function(view) {
854 // TODO fme: should add the language to fields_view_get because between the fields view get
855 // and the moment the user opens the translation dialog, the user language could have been changed
856 this.view_language = view.session.user_context.lang;
857 this['on_button' + _t("Save")] = this.on_button_Save;
858 this['on_button' + _t("Close")] = this.on_button_Close;
864 this.view_type = view.fields_view.type || '';
865 this.$fields_form = null;
866 this.$view_form = null;
867 this.$sidebar_form = null;
868 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
869 this.languages = null;
870 this.languages_loaded = $.Deferred();
871 (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
872 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }, this.on_languages_loaded);
877 $.when(this.languages_loaded).then(function() {
878 self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
879 self.$fields_form = self.$element.find('.oe_translation_form');
880 self.$fields_form.find('.oe_trad_field').change(function() {
881 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
886 on_languages_loaded: function(langs) {
887 this.languages = langs;
888 this.languages_loaded.resolve();
890 do_load_fields_values: function(callback) {
893 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
894 _.each(self.languages, function(lg) {
895 var deff = $.Deferred();
897 var callback = function(values) {
898 _.each(self.translatable_fields_keys, function(f) {
899 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
903 if (lg.code === self.view_language) {
905 _.each(self.translatable_fields_keys, function(field) {
906 values[field] = self.view.fields[field].get_value();
910 self.rpc('/web/dataset/get', {
911 model: self.view.dataset.model,
912 ids: [self.view.datarecord.id],
913 fields: self.translatable_fields_keys,
914 context: self.view.dataset.get_context({
919 $.when.apply(null, deffered).then(callback);
921 open: function(field) {
924 $.when(this.languages_loaded).then(function() {
925 if (self.view.translatable_fields && self.view.translatable_fields.length) {
926 self.do_load_fields_values(function() {
929 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
930 self.$element.scrollTo($field_input);
931 $field_input.focus();
939 on_button_Save: function() {
942 self.$fields_form.find('.oe_trad_field.touched').each(function() {
943 var field = $(this).attr('name').split('-');
944 if (!trads[field[0]]) {
945 trads[field[0]] = {};
947 trads[field[0]][field[1]] = $(this).val();
949 _.each(trads, function(data, code) {
950 if (code === self.view_language) {
951 _.each(data, function(value, field) {
952 self.view.fields[field].set_value(value);
955 self.view.dataset.write(self.view.datarecord.id, data, { 'lang': code });
960 on_button_Close: function() {
965 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
966 template: "EmptyComponent",
967 set_default_options: function(options) {
968 this.options = options || {};
969 _.defaults(this.options, {
970 // All possible views options should be defaulted here
977 open_translate_dialog: function(field) {
978 if (!this.translate_dialog) {
979 this.translate_dialog = new session.web.TranslateDialog(this).start();
981 this.translate_dialog.open(field);
984 * Fetches and executes the action identified by ``action_data``.
986 * @param {Object} action_data the action descriptor data
987 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
988 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
989 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
990 * @param {Object} [action_data.context=null] additional action context, to add to the current context
991 * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
992 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
993 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
995 do_execute_action: function (action_data, dataset, record_id, on_closed) {
997 var result_handler = function () {
998 if (on_closed) { on_closed.apply(null, arguments); }
999 if (self.widget_parent && self.widget_parent.on_action_executed) {
1000 return self.widget_parent.on_action_executed.apply(null, arguments);
1003 var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
1005 var handler = function (r) {
1006 var action = r.result;
1007 if (action && action.constructor == Object) {
1008 var ncontext = new session.web.CompoundContext(context);
1011 active_id: record_id,
1012 active_ids: [record_id],
1013 active_model: dataset.model
1016 ncontext.add(action.context || {});
1017 return self.rpc('/web/session/eval_domain_and_context', {
1018 contexts: [ncontext],
1020 }).pipe(function (results) {
1021 action.context = results.context;
1022 /* niv: previously we were overriding once more with action_data.context,
1023 * I assumed this was not a correct behavior and removed it
1025 return self.do_action(action, result_handler);
1028 return result_handler();
1032 if (action_data.special) {
1033 return handler({result: {"type":"ir.actions.act_window_close"}});
1034 } else if (action_data.type=="object") {
1035 var args = [[record_id]], additional_args = [];
1036 if (action_data.args) {
1038 // Warning: quotes and double quotes problem due to json and xml clash
1039 // Maybe we should force escaping in xml or do a better parse of the args array
1040 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1041 args = args.concat(additional_args);
1043 console.error("Could not JSON.parse arguments", action_data.args);
1047 return dataset.call_button(action_data.name, args, handler);
1048 } else if (action_data.type=="action") {
1049 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1051 return dataset.exec_workflow(record_id, action_data.name, handler);
1055 * Directly set a view to use instead of calling fields_view_get. This method must
1056 * be called before start(). When an embedded view is set, underlying implementations
1057 * of session.web.View must use the provided view instead of any other one.
1059 * @param embedded_view A view.
1061 set_embedded_view: function(embedded_view) {
1062 this.embedded_view = embedded_view;
1063 this.options.sidebar = false;
1066 * Switches to a specific view type
1068 * @param {String} view view type to switch to
1070 do_switch_view: function(view) { },
1072 * Cancels the switch to the current view, switches to the previous one
1074 do_prev_view: function () { },
1075 do_search: function(view) {
1078 set_common_sidebar_sections: function(sidebar) {
1079 sidebar.add_default_sections();
1081 on_sidebar_manage_views: function() {
1082 if (this.fields_view && this.fields_view.arch) {
1083 var view_editor = new session.web.ViewEditor(this, this.$element, this.dataset, this.fields_view.arch);
1084 view_editor.start();
1086 this.do_warn("Manage Views", "Could not find current view declaration");
1089 on_sidebar_edit_workflow: function() {
1090 console.log('Todo');
1092 on_sidebar_customize_object: function() {
1094 this.rpc('/web/dataset/search_read', {
1097 domain: [['model', '=', self.dataset.model]]
1098 }, function (result) {
1099 self.on_sidebar_edit_resource('ir.model', result.ids[0]);
1102 on_sidebar_import: function() {
1103 var import_view = new session.web.DataImport(this, this.dataset);
1104 import_view.start();
1106 on_sidebar_export: function() {
1107 var export_view = new session.web.DataExport(this, this.dataset);
1108 export_view.start();
1110 on_sidebar_translate: function() {
1111 return this.do_action({
1112 res_model : 'ir.translation',
1113 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1114 views: [[false, 'list'], [false, 'form']],
1115 type : 'ir.actions.act_window',
1120 on_sidebar_edit_resource: function(model, id, domain) {
1123 type : 'ir.actions.act_window',
1128 action_buttons : true
1133 action.views = [[false, 'form']];
1134 } else if (domain) {
1135 action.views = [[false, 'list'], [false, 'form']];
1136 action.domain = domain;
1137 action.flags.views_switcher = true;
1139 this.do_action(action);
1141 on_sidebar_view_log: function() {
1143 sidebar_context: function () {
1144 return $.Deferred().resolve({}).promise();
1147 do_push_state: function(state, overwrite) {
1150 do_load_state: function(state) {
1154 session.web.json_node_to_xml = function(node, human_readable, indent) {
1155 // For debugging purpose, this function will convert a json node back to xml
1156 // Maybe usefull for xml view editor
1157 indent = indent || 0;
1158 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1159 r = sindent + '<' + node.tag,
1160 cr = human_readable ? '\n' : '';
1162 if (typeof(node) === 'string') {
1163 return sindent + node;
1164 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1165 throw("Node a json node");
1167 for (var attr in node.attrs) {
1168 var vattr = node.attrs[attr];
1169 if (typeof(vattr) !== 'string') {
1171 vattr = JSON.stringify(vattr);
1173 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1174 if (human_readable) {
1175 vattr = vattr.replace(/"/g, "'");
1177 r += ' ' + attr + '="' + vattr + '"';
1179 if (node.children && node.children.length) {
1182 for (var i = 0, ii = node.children.length; i < ii; i++) {
1183 childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1185 r += childs.join(cr);
1186 r += cr + sindent + '</' + node.tag + '>';
1195 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: