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) {
106 if (_(['base.module.upgrade', 'base.setup.installer'])
107 .contains(action.res_model)) {
108 var old_close = on_close;
109 on_close = function () {
110 session.webclient.do_reload();
111 if (old_close) { old_close(); }
114 if (action.target === 'new') {
115 if (this.dialog == null) {
116 this.dialog = new session.web.Dialog(this, { title: action.name, width: '80%' });
118 this.dialog.on_close.add(on_close);
121 this.dialog_viewmanager.stop();
123 this.dialog_viewmanager = new session.web.ViewManagerAction(this, action);
124 this.dialog_viewmanager.appendTo(this.dialog.$element);
129 this.inner_action = action;
130 this.inner_viewmanager = new session.web.ViewManagerAction(this, action);
131 this.inner_viewmanager.do_push_state.add(function(state,overwrite) {
132 state['action_id'] = action.id;
133 self.do_push_state(state,true);
135 this.inner_viewmanager.appendTo(this.$element);
138 ir_actions_act_window_close: function (action, on_closed) {
139 if (!this.dialog && on_closed) {
144 ir_actions_server: function (action, on_closed) {
146 this.rpc('/web/action/run', {
147 action_id: action.id,
148 context: action.context || {}
149 }).then(function (action) {
150 self.do_action(action, on_closed)
153 ir_actions_client: function (action) {
156 var ClientWidget = session.web.client_actions.get_object(action.tag);
157 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this);
159 var client_action = {tag: action.tag};
160 if (action.params) _.extend(client_action, {params: action.params});
161 this.do_push_state({client_action: client_action}, true);
163 ir_actions_report_xml: function(action, on_closed) {
166 self.rpc("/web/session/eval_domain_and_context", {
167 contexts: [action.context],
169 }).then(function(res) {
170 action = _.clone(action);
171 action.context = res.context;
172 self.session.get_file({
174 data: {action: JSON.stringify(action)},
175 complete: $.unblockUI,
177 if (!self.dialog && on_closed) {
185 ir_actions_act_url: function (action) {
186 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
188 ir_ui_menu: function (action) {
189 this.widget_parent.do_action(action);
193 session.web.ViewManager = session.web.Widget.extend(/** @lends session.web.ViewManager# */{
194 identifier_prefix: "viewmanager",
195 template: "ViewManager",
197 * @constructs session.web.ViewManager
198 * @extends session.web.Widget
204 init: function(parent, dataset, views, flags) {
206 this.model = dataset ? dataset.model : undefined;
207 this.dataset = dataset;
208 this.searchview = null;
209 this.active_view = null;
210 this.views_src = _.map(views, function(x) {return x instanceof Array? {view_id: x[0], view_type: x[1]} : x;});
212 this.flags = flags || {};
213 this.registry = session.web.views;
214 this.views_history = [];
217 return session.web.qweb.render(this.template, {
219 prefix: this.element_id,
220 views: this.views_src});
223 * @returns {jQuery.Deferred} initial view loading promise
228 this.$element.find('.oe_vm_switch button').click(function() {
229 self.on_mode_switch($(this).data('view-type'));
232 _.each(this.views_src, function(view) {
233 self.views[view.view_type] = $.extend({}, view, {
234 deferred : $.Deferred(),
237 sidebar_id : self.element_id + '_sidebar_' + view.view_type,
238 action : self.action,
239 action_views_ids : views_ids
240 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
242 views_ids[view.view_type] = view.view_id;
244 if (this.flags.views_switcher === false) {
245 this.$element.find('.oe_vm_switch').hide();
247 // If no default view defined, switch to the first one in sequence
248 var default_view = this.flags.default_view || this.views_src[0].view_type;
249 return this.on_mode_switch(default_view);
252 * Asks the view manager to switch visualization mode.
254 * @param {String} view_type type of view to display
255 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
256 * @returns {jQuery.Deferred} new view loading promise
258 on_mode_switch: function(view_type, no_store) {
260 view = this.views[view_type],
263 return $.Deferred().reject();
266 this.views_history.push(view_type);
268 this.active_view = view_type;
270 if (!view.controller) {
271 // Lazy loading of views
272 var controllerclass = this.registry.get_object(view_type);
273 var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
274 if (view.embedded_view) {
275 controller.set_embedded_view(view.embedded_view);
277 controller.do_switch_view.add_last(this.on_mode_switch);
278 controller.do_prev_view.add_last(this.on_prev_view);
279 var container = $("#" + this.element_id + '_view_' + view_type);
280 view_promise = controller.appendTo(container);
281 this.views[view_type].controller = controller;
282 this.views[view_type].deferred.resolve(view_type);
283 $.when(view_promise).then(function() {
284 self.on_controller_inited(view_type, controller);
285 if (self.searchview && view.controller.searchable !== false) {
286 self.searchview.ready.then(self.searchview.do_search);
289 } else if (this.searchview && view.controller.searchable !== false) {
290 this.searchview.ready.then(this.searchview.do_search);
293 if (this.searchview) {
294 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
298 .find('.oe_vm_switch button').removeAttr('disabled')
299 .filter('[data-view-type="' + view_type + '"]')
300 .attr('disabled', true);
302 for (var view_name in this.views) {
303 if (!this.views.hasOwnProperty(view_name)) { continue; }
304 if (this.views[view_name].controller) {
305 if (view_name === view_type) {
306 $.when(view_promise).then(this.views[view_name].controller.do_show);
308 this.views[view_name].controller.do_hide();
312 $.when(view_promise).then(function () {
313 self.$element.find('.oe_view_title_text:first').text(
314 self.display_title());
321 * Returns to the view preceding the caller view in this manager's
322 * navigation history (the navigation history is appended to via
325 * @param {Boolean} [created=false] returning from a creation
326 * @returns {$.Deferred} switching end signal
328 on_prev_view: function (created) {
329 var current_view = this.views_history.pop();
330 var previous_view = this.views_history[this.views_history.length - 1];
331 // APR special case: "If creation mode from list (and only from a list),
332 // after saving, go to page view (don't come back in list)"
333 if (created && current_view === 'form' && previous_view === 'list') {
334 return this.on_mode_switch('page');
336 return this.on_mode_switch(previous_view, true);
339 * Sets up the current viewmanager's search view.
341 * @param {Number|false} view_id the view to use or false for a default one
342 * @returns {jQuery.Deferred} search view startup deferred
344 setup_search_view: function(view_id, search_defaults) {
346 if (this.searchview) {
347 this.searchview.stop();
349 this.searchview = new session.web.SearchView(
351 view_id, search_defaults, this.flags.search_view === false);
353 this.searchview.on_search.add(this.do_searchview_search);
354 return this.searchview.appendTo($("#" + this.element_id + "_search"));
356 do_searchview_search: function(domains, contexts, groupbys) {
358 controller = this.views[this.active_view].controller,
359 action_context = this.action.context || {};
360 this.rpc('/web/session/eval_domain_and_context', {
361 domains: [this.action.domain || []].concat(domains || []),
362 contexts: [action_context].concat(contexts || []),
363 group_by_seq: groupbys || []
364 }, function (results) {
365 self.dataset.context = results.context;
366 self.dataset.domain = results.domain;
367 var groupby = results.group_by.length
369 : action_context.group_by;
370 controller.do_search(results.domain, results.context, groupby || []);
374 * Event launched when a controller has been inited.
376 * @param {String} view_type type of view
377 * @param {String} view the inited controller
379 on_controller_inited: function(view_type, view) {
382 * Called when one of the view want to execute an action
384 on_action: function(action) {
386 on_create: function() {
388 on_remove: function() {
390 on_edit: function() {
393 * Called by children view after executing an action
395 on_action_executed: function () {},
396 display_title: function () {
397 var view = this.views[this.active_view];
400 return view.controller.fields_view.arch.attrs.string;
406 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
407 template:"ViewManagerAction",
409 * @constructs session.web.ViewManagerAction
410 * @extends session.web.ViewManager
412 * @param {session.web.ActionManager} parent parent object/widget
413 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
415 init: function(parent, action) {
416 // dataset initialization will take the session from ``this``, so if we
417 // do not have it yet (and we don't, because we've not called our own
418 // ``_super()``) rpc requests will blow up.
419 var flags = action.flags || {};
420 if (action.res_model == 'board.board' && action.view_mode === 'form') {
421 // Special case for Dashboards
423 views_switcher : false,
424 display_title : false,
428 action_buttons : false
431 this._super(parent, null, action.views, flags);
432 this.session = parent.session;
433 this.action = action;
434 var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
436 dataset.ids.push(action.res_id);
439 this.dataset = dataset;
441 // setup storage for session-wise menu hiding
442 if (this.session.hidden_menutips) {
445 this.session.hidden_menutips = {}
448 * Initializes the ViewManagerAction: sets up the searchview (if the
449 * searchview is enabled in the manager's action flags), calls into the
450 * parent to initialize the primary view and (if the VMA has a searchview)
451 * launches an initial search after both views are done rendering.
456 search_defaults = {};
457 _.each(this.action.context, function (value, key) {
458 var match = /^search_default_(.*)$/.exec(key);
460 search_defaults[match[1]] = value;
464 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
466 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
468 var main_view_loaded = this._super();
470 _.each(_.keys(this.views), function(view_type) {
471 $.when(self.views[view_type].deferred).done(function(view_type) {
472 self.views[view_type].controller.do_push_state.add(self.do_push_state);
476 var manager_ready = $.when(searchview_loaded, main_view_loaded);
478 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
480 if (this.action.help && !this.flags.low_profile) {
481 var Users = new session.web.DataSet(self, 'res.users'),
482 $tips = this.$element.find('.oe_view_manager_menu_tips');
483 $tips.delegate('blockquote button', 'click', function() {
485 //noinspection FallthroughInSwitchStatementJS
486 switch ($this.attr('name')) {
488 Users.write(self.session.uid, {menu_tips:false});
490 $this.closest('blockquote').hide();
491 self.session.hidden_menutips[self.action.id] = true;
494 if (!(self.action.id in self.session.hidden_menutips)) {
495 Users.read_ids([this.session.uid], ['menu_tips'], function(users) {
497 if (!(user && user.id === self.session.uid)) {
500 $tips.find('blockquote').toggle(user.menu_tips);
505 var $res_logs = this.$element.find('.oe-view-manager-logs:first');
506 $res_logs.delegate('a.oe-more-logs', 'click', function () {
507 $res_logs.removeClass('oe-folded');
509 }).delegate('a.oe-remove-everything', 'click', function () {
510 $res_logs.removeClass('oe-has-more')
515 return manager_ready;
517 on_debug_changed: function (evt) {
518 var $sel = $(evt.currentTarget),
519 $option = $sel.find('option:selected'),
523 $('<pre>').text(session.web.json_node_to_xml(
524 this.views[this.active_view].controller.fields_view.arch, true)
525 ).dialog({ width: '95%'});
528 var model = $option.data('model'),
529 id = $option.data('id'),
530 domain = $option.data('domain'),
533 type : 'ir.actions.act_window',
538 action_buttons : true
543 action.views = [[false, 'form']];
545 action.views = [[false, 'list'], [false, 'form']];
546 action.domain = domain;
547 action.flags.views_switcher = true;
549 this.do_action(action);
553 console.log("No debug handler for ", val);
556 evt.currentTarget.selectedIndex = 0;
558 on_mode_switch: function (view_type, no_store) {
561 return $.when(this._super(view_type, no_store)).then(function () {
562 self.shortcut_check(self.views[view_type]);
564 self.$element.find('.oe-view-manager-logs:first')
565 .addClass('oe-folded').removeClass('oe-has-more')
568 var controller = self.views[self.active_view].controller,
569 fvg = controller.fields_view,
570 view_id = (fvg && fvg.view_id) || '--';
571 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
575 if (!self.action.name && fvg) {
576 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
579 var $title = self.$element.find('.oe_view_title_text'),
580 $search_prefix = $title.find('span.oe_searchable_view');
581 if (controller.searchable !== false) {
582 if (!$search_prefix.length) {
583 $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
586 $search_prefix.remove();
589 self.do_push_state({view_type: self.active_view});
593 do_push_state: function(state, overwrite) {
596 do_load_state: function(state) {
598 $.when(this.on_mode_switch(state.view_type, true)).done(function() {
599 self.views[self.active_view].controller.do_load_state(state);
603 shortcut_check : function(view) {
605 var grandparent = this.widget_parent && this.widget_parent.widget_parent;
606 // display shortcuts if on the first view for the action
607 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
608 if (!(grandparent instanceof session.web.WebClient) ||
609 !(view.view_type === this.views_src[0].view_type
610 && view.view_id === this.views_src[0].view_id)) {
611 $shortcut_toggle.hide();
614 $shortcut_toggle.removeClass('oe-shortcut-remove').show();
615 if (_(this.session.shortcuts).detect(function (shortcut) {
616 return shortcut.res_id === self.session.active_id; })) {
617 $shortcut_toggle.addClass("oe-shortcut-remove");
619 this.shortcut_add_remove();
621 shortcut_add_remove: function() {
623 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
627 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
628 $(self.session.shortcuts.binding).trigger('remove-current');
629 $shortcut_toggle.removeClass("oe-shortcut-remove");
631 $(self.session.shortcuts.binding).trigger('add', {
632 'user_id': self.session.uid,
633 'res_id': self.session.active_id,
634 'resource': 'ir.ui.menu',
635 'name': self.action.name
637 $shortcut_toggle.addClass("oe-shortcut-remove");
642 * Intercept do_action resolution from children views
644 on_action_executed: function () {
645 return new session.web.DataSet(this, 'res.log')
646 .call('get', [], this.do_display_log);
649 * @param {Array<Object>} log_records
651 do_display_log: function (log_records) {
654 $logs = this.$element.find('.oe-view-manager-logs:first')
655 .addClass('oe-folded'),
656 $logs_list = $logs.find('ul').empty();
657 $logs.toggleClass('oe-has-more', log_records.length > cutoff);
658 _(log_records.reverse()).each(function (record) {
659 $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
660 .appendTo($logs_list)
661 .delegate('a', 'click', function (e) {
663 type: 'ir.actions.act_window',
664 res_model: record.res_model,
665 res_id: record.res_id,
666 // TODO: need to have an evaluated context here somehow
667 //context: record.context,
668 views: [[false, 'form']]
674 display_title: function () {
675 return this.action.name;
679 session.web.Sidebar = session.web.Widget.extend({
680 init: function(parent, element_id) {
681 this._super(parent, element_id);
688 this.$element.html(session.web.qweb.render('Sidebar'));
689 this.$element.find(".toggle-sidebar").click(function(e) {
693 add_default_sections: function() {
695 view = this.widget_parent,
696 view_manager = view.widget_parent,
697 action = view_manager.action;
698 if (this.session.uid === 1) {
699 this.add_section(_t('Customize'), 'customize');
700 this.add_items('customize', [
702 label: _t("Manage Views"),
703 callback: view.on_sidebar_manage_views,
704 title: _t("Manage views of the current object")
706 label: _t("Edit Workflow"),
707 callback: view.on_sidebar_edit_workflow,
708 title: _t("Manage views of the current object"),
709 classname: 'oe_hide oe_sidebar_edit_workflow'
711 label: _t("Customize Object"),
712 callback: view.on_sidebar_customize_object,
713 title: _t("Manage views of the current object")
715 label: _t("Translate"),
716 callback: view.on_sidebar_translate,
717 title: _t("Technical translation")
722 this.add_section(_t('Other Options'), 'other');
723 this.add_items('other', [
726 callback: view.on_sidebar_import
729 callback: view.on_sidebar_export
731 label: _t("View Log"),
732 callback: view.on_sidebar_view_log,
733 classname: 'oe_hide oe_sidebar_view_log'
738 add_toolbar: function(toolbar) {
740 _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
741 var items = toolbar[type[0]];
743 for (var i = 0; i < items.length; i++) {
745 label: items[i]['name'],
747 classname: 'oe_sidebar_' + type[0]
750 self.add_section(type[1], type[0]);
751 self.add_items(type[0], items);
756 add_section: function(name, code) {
757 if(!code) code = _.str.underscored(name);
758 var $section = this.sections[code];
761 var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
762 $section = $(session.web.qweb.render("Sidebar.section", {
763 section_id: section_id,
765 classname: 'oe_sidebar_' + code
767 $section.appendTo(this.$element.find('div.sidebar-actions'));
768 this.sections[code] = $section;
773 add_items: function(section_code, items) {
774 // An item is a dictonary : {
775 // label: label to be displayed for the link,
776 // action: action to be launch when the link is clicked,
777 // callback: a function to be executed when the link is clicked,
778 // classname: optional dom class name for the line,
779 // title: optional title for the link
781 // Note: The item should have one action or/and a callback
785 $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
786 section_id = $section.attr('id');
789 for (var i = 0; i < items.length; i++) {
790 items[i].element_id = _.uniqueId(section_id + '_item_');
791 this.items[items[i].element_id] = items[i];
794 var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
796 $items.find('a.oe_sidebar_action_a').click(function() {
797 var item = self.items[$(this).attr('id')];
799 item.callback.apply(self, [item]);
802 self.on_item_action_clicked(item);
807 var $ul = $section.find('ul');
809 $ul = $('<ul/>').appendTo($section);
811 $items.appendTo($ul);
814 on_item_action_clicked: function(item) {
816 self.widget_parent.sidebar_context().then(function (context) {
817 var ids = self.widget_parent.get_selected_ids();
818 if (ids.length == 0) {
819 //TODO: make prettier warning?
820 $("<div />").text(_t("You must choose at least one record.")).dialog({
821 title: _t("Warning"),
826 var additional_context = _.extend({
829 active_model: self.widget_parent.dataset.model
831 self.rpc("/web/action/load", {
832 action_id: item.action.id,
833 context: additional_context
834 }, function(result) {
835 result.result.context = _.extend(result.result.context || {},
837 result.result.flags = result.result.flags || {};
838 result.result.flags.new_window = true;
839 self.do_action(result.result);
843 do_fold: function() {
844 this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
846 do_unfold: function() {
847 this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
849 do_toggle: function() {
850 this.$element.toggleClass('open-sidebar closed-sidebar');
854 session.web.TranslateDialog = session.web.Dialog.extend({
855 dialog_title: _t("Translations"),
856 init: function(view) {
857 // TODO fme: should add the language to fields_view_get because between the fields view get
858 // and the moment the user opens the translation dialog, the user language could have been changed
859 this.view_language = view.session.user_context.lang;
860 this['on_button' + _t("Save")] = this.on_button_Save;
861 this['on_button' + _t("Close")] = this.on_button_Close;
867 this.view_type = view.fields_view.type || '';
868 this.$fields_form = null;
869 this.$view_form = null;
870 this.$sidebar_form = null;
871 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
872 this.languages = null;
873 this.languages_loaded = $.Deferred();
874 (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
875 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }, this.on_languages_loaded);
880 $.when(this.languages_loaded).then(function() {
881 self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
882 self.$fields_form = self.$element.find('.oe_translation_form');
883 self.$fields_form.find('.oe_trad_field').change(function() {
884 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
889 on_languages_loaded: function(langs) {
890 this.languages = langs;
891 this.languages_loaded.resolve();
893 do_load_fields_values: function(callback) {
896 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
897 _.each(self.languages, function(lg) {
898 var deff = $.Deferred();
900 var callback = function(values) {
901 _.each(self.translatable_fields_keys, function(f) {
902 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
906 if (lg.code === self.view_language) {
908 _.each(self.translatable_fields_keys, function(field) {
909 values[field] = self.view.fields[field].get_value();
913 self.rpc('/web/dataset/get', {
914 model: self.view.dataset.model,
915 ids: [self.view.datarecord.id],
916 fields: self.translatable_fields_keys,
917 context: self.view.dataset.get_context({
922 $.when.apply(null, deffered).then(callback);
924 open: function(field) {
927 $.when(this.languages_loaded).then(function() {
928 if (self.view.translatable_fields && self.view.translatable_fields.length) {
929 self.do_load_fields_values(function() {
932 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
933 self.$element.scrollTo($field_input);
934 $field_input.focus();
942 on_button_Save: function() {
945 self.$fields_form.find('.oe_trad_field.touched').each(function() {
946 var field = $(this).attr('name').split('-');
947 if (!trads[field[0]]) {
948 trads[field[0]] = {};
950 trads[field[0]][field[1]] = $(this).val();
952 _.each(trads, function(data, code) {
953 if (code === self.view_language) {
954 _.each(data, function(value, field) {
955 self.view.fields[field].set_value(value);
958 self.view.dataset.write(self.view.datarecord.id, data, { 'lang': code });
963 on_button_Close: function() {
968 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
969 template: "EmptyComponent",
970 set_default_options: function(options) {
971 this.options = options || {};
972 _.defaults(this.options, {
973 // All possible views options should be defaulted here
980 open_translate_dialog: function(field) {
981 if (!this.translate_dialog) {
982 this.translate_dialog = new session.web.TranslateDialog(this).start();
984 this.translate_dialog.open(field);
987 * Fetches and executes the action identified by ``action_data``.
989 * @param {Object} action_data the action descriptor data
990 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
991 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
992 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
993 * @param {Object} [action_data.context=null] additional action context, to add to the current context
994 * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
995 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
996 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
998 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1000 var result_handler = function () {
1001 if (on_closed) { on_closed.apply(null, arguments); }
1002 if (self.widget_parent && self.widget_parent.on_action_executed) {
1003 return self.widget_parent.on_action_executed.apply(null, arguments);
1006 var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
1008 var handler = function (r) {
1009 var action = r.result;
1010 if (action && action.constructor == Object) {
1011 var ncontext = new session.web.CompoundContext(context);
1014 active_id: record_id,
1015 active_ids: [record_id],
1016 active_model: dataset.model
1019 ncontext.add(action.context || {});
1020 return self.rpc('/web/session/eval_domain_and_context', {
1021 contexts: [ncontext],
1023 }).pipe(function (results) {
1024 action.context = results.context;
1025 /* niv: previously we were overriding once more with action_data.context,
1026 * I assumed this was not a correct behavior and removed it
1028 return self.do_action(action, result_handler);
1031 return result_handler();
1035 if (action_data.special) {
1036 return handler({result: {"type":"ir.actions.act_window_close"}});
1037 } else if (action_data.type=="object") {
1038 var args = [[record_id]], additional_args = [];
1039 if (action_data.args) {
1041 // Warning: quotes and double quotes problem due to json and xml clash
1042 // Maybe we should force escaping in xml or do a better parse of the args array
1043 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1044 args = args.concat(additional_args);
1046 console.error("Could not JSON.parse arguments", action_data.args);
1050 return dataset.call_button(action_data.name, args, handler);
1051 } else if (action_data.type=="action") {
1052 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1054 return dataset.exec_workflow(record_id, action_data.name, handler);
1058 * Directly set a view to use instead of calling fields_view_get. This method must
1059 * be called before start(). When an embedded view is set, underlying implementations
1060 * of session.web.View must use the provided view instead of any other one.
1062 * @param embedded_view A view.
1064 set_embedded_view: function(embedded_view) {
1065 this.embedded_view = embedded_view;
1066 this.options.sidebar = false;
1068 do_show: function () {
1069 this.$element.show();
1071 do_hide: function () {
1072 this.$element.hide();
1075 * Switches to a specific view type
1077 * @param {String} view view type to switch to
1079 do_switch_view: function(view) {
1082 * Cancels the switch to the current view, switches to the previous one
1084 do_prev_view: function () {
1086 do_search: function(view) {
1088 set_common_sidebar_sections: function(sidebar) {
1089 sidebar.add_default_sections();
1091 on_sidebar_manage_views: function() {
1092 if (this.fields_view && this.fields_view.arch) {
1093 var view_editor = new session.web.ViewEditor(this, this.$element, this.dataset, this.fields_view.arch);
1094 view_editor.start();
1096 this.do_warn("Manage Views", "Could not find current view declaration");
1099 on_sidebar_edit_workflow: function() {
1100 console.log('Todo');
1102 on_sidebar_customize_object: function() {
1104 this.rpc('/web/dataset/search_read', {
1107 domain: [['model', '=', self.dataset.model]]
1108 }, function (result) {
1109 self.on_sidebar_edit_resource('ir.model', result.ids[0]);
1112 on_sidebar_import: function() {
1113 var import_view = new session.web.DataImport(this, this.dataset);
1114 import_view.start();
1116 on_sidebar_export: function() {
1117 var export_view = new session.web.DataExport(this, this.dataset);
1118 export_view.start();
1120 on_sidebar_translate: function() {
1121 return this.do_action({
1122 res_model : 'ir.translation',
1123 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1124 views: [[false, 'list'], [false, 'form']],
1125 type : 'ir.actions.act_window',
1130 on_sidebar_edit_resource: function(model, id, domain) {
1133 type : 'ir.actions.act_window',
1138 action_buttons : true
1143 action.views = [[false, 'form']];
1144 } else if (domain) {
1145 action.views = [[false, 'list'], [false, 'form']];
1146 action.domain = domain;
1147 action.flags.views_switcher = true;
1149 this.do_action(action);
1151 on_sidebar_view_log: function() {
1153 sidebar_context: function () {
1154 return $.Deferred().resolve({}).promise();
1156 do_push_state: function(state, overwrite) {
1158 do_load_state: function(state) {
1162 session.web.json_node_to_xml = function(node, human_readable, indent) {
1163 // For debugging purpose, this function will convert a json node back to xml
1164 // Maybe usefull for xml view editor
1165 indent = indent || 0;
1166 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1167 r = sindent + '<' + node.tag,
1168 cr = human_readable ? '\n' : '';
1170 if (typeof(node) === 'string') {
1171 return sindent + node;
1172 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1173 throw("Node a json node");
1175 for (var attr in node.attrs) {
1176 var vattr = node.attrs[attr];
1177 if (typeof(vattr) !== 'string') {
1179 vattr = JSON.stringify(vattr);
1181 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1182 if (human_readable) {
1183 vattr = vattr.replace(/"/g, "'");
1185 r += ' ' + attr + '="' + vattr + '"';
1187 if (node.children && node.children.length) {
1190 for (var i = 0, ii = node.children.length; i < ii; i++) {
1191 childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1193 r += childs.join(cr);
1194 r += cr + sindent + '</' + node.tag + '>';
1203 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: