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_viewmanager = null;
15 this.dialog_viewmanager = null;
16 this.client_widget = null;
18 dialog_stop: function () {
20 this.dialog_viewmanager.destroy();
21 this.dialog_viewmanager = null;
22 this.dialog.destroy();
26 content_stop: function () {
27 if (this.inner_viewmanager) {
28 this.inner_viewmanager.destroy();
29 this.inner_viewmanager = null;
31 if (this.client_widget) {
32 this.client_widget.destroy();
33 this.client_widget = null;
36 do_push_state: function(state) {
37 if (this.getParent() && this.getParent().do_push_state) {
38 if (this.inner_action) {
39 state['model'] = this.inner_action.res_model;
40 if (this.inner_action.id) {
41 state['action_id'] = this.inner_action.id;
44 this.getParent().do_push_state(state);
47 do_load_state: function(state, warm) {
50 if (state.action_id) {
51 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
54 action_loaded = this.do_action(state.action_id);
55 instance.webclient.menu.has_been_loaded.then(function() {
56 instance.webclient.menu.open_action(state.action_id);
59 } else if (state.model && state.id) {
60 // TODO handle context & domain ?
63 res_model: state.model,
65 type: 'ir.actions.act_window',
66 views: [[false, 'form']]
68 action_loaded = this.do_action(action);
69 } else if (state.sa) {
70 // load session action
73 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
75 return self.do_action(action);
78 } else if (state.client_action) {
80 var action = state.client_action;
81 if(_.isString(action)) {
87 this.ir_actions_client(action);
90 $.when(action_loaded || null).then(function() {
91 if (self.inner_viewmanager) {
92 self.inner_viewmanager.do_load_state(state, warm);
96 do_action: function(action, on_close) {
97 if (_.isNumber(action)) {
99 return self.rpc("/web/action/load", { action_id: action }, function(result) {
100 self.do_action(result.result, on_close);
104 console.error("No type for action", action);
107 var type = action.type.replace(/\./g,'_');
108 var popup = action.target === 'new';
109 var inline = action.target === 'inline';
110 action.flags = _.extend({
111 views_switcher : !popup && !inline,
112 search_view : !popup && !inline,
113 action_buttons : !popup && !inline,
114 sidebar : !popup && !inline,
115 pager : !popup && !inline,
116 display_title : !popup
117 }, action.flags || {});
118 if (!(type in this)) {
119 console.error("Action manager can't handle action of type " + action.type, action);
122 return this[type](action, on_close);
124 null_action: function() {
128 ir_actions_act_window: function (action, on_close) {
130 if (_(['base.module.upgrade', 'base.setup.installer'])
131 .contains(action.res_model)) {
132 var old_close = on_close;
133 on_close = function () {
134 instance.webclient.do_reload().then(old_close);
137 if (action.target === 'new') {
138 if (this.dialog == null) {
139 this.dialog = new instance.web.Dialog(this, { width: '80%' });
141 this.dialog.on_close.add(on_close);
143 this.dialog_viewmanager.destroy();
145 this.dialog.dialog_title = action.name;
146 this.dialog_viewmanager = new instance.web.ViewManagerAction(this, action);
147 this.dialog_viewmanager.appendTo(this.dialog.$element);
153 return this.getParent().do_action(action, function () {
154 instance.webclient.menu.open_menu(action.menu_id);
157 this.inner_action = action;
158 this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
159 this.inner_viewmanager.appendTo(this.$element);
160 this.inner_viewmanager.$element.addClass("oe_view_manager_global");
163 ir_actions_act_window_close: function (action, on_closed) {
164 if (!this.dialog && on_closed) {
169 ir_actions_server: function (action, on_closed) {
171 this.rpc('/web/action/run', {
172 action_id: action.id,
173 context: action.context || {}
174 }).then(function (action) {
175 self.do_action(action, on_closed)
178 ir_actions_client: function (action) {
181 var ClientWidget = instance.web.client_actions.get_object(action.tag);
182 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
184 ir_actions_report_xml: function(action, on_closed) {
187 self.rpc("/web/session/eval_domain_and_context", {
188 contexts: [action.context],
190 }).then(function(res) {
191 action = _.clone(action);
192 action.context = res.context;
193 self.session.get_file({
195 data: {action: JSON.stringify(action)},
196 complete: $.unblockUI,
198 if (!self.dialog && on_closed) {
203 error: instance.webclient.crashmanager.on_rpc_error
207 ir_actions_act_url: function (action) {
208 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
210 ir_ui_menu: function (action) {
211 this.getParent().do_action(action);
215 instance.web.ViewManager = instance.web.Widget.extend({
216 template: "ViewManager",
217 init: function(parent, dataset, views, flags) {
219 this.model = dataset ? dataset.model : undefined;
220 this.dataset = dataset;
221 this.searchview = null;
222 this.active_view = null;
223 this.views_src = _.map(views, function(x) {
224 if (x instanceof Array) {
225 var View = instance.web.views.get_object(x[1], true);
229 label: View ? View.prototype.display_name : (void 'nope')
236 this.flags = flags || {};
237 this.registry = instance.web.views;
238 this.views_history = [];
241 * @returns {jQuery.Deferred} initial view loading promise
246 this.$element.find('.oe_view_manager_switch a').click(function() {
247 self.on_mode_switch($(this).data('view-type'));
250 _.each(this.views_src, function(view) {
251 self.views[view.view_type] = $.extend({}, view, {
252 deferred : $.Deferred(),
255 $buttons : self.$element.find('.oe_view_manager_buttons'),
256 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
257 $pager : self.$element.find('.oe_view_manager_pager'),
258 action : self.action,
259 action_views_ids : views_ids
260 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
262 views_ids[view.view_type] = view.view_id;
264 if (this.flags.views_switcher === false) {
265 this.$element.find('.oe_view_manager_switch').hide();
267 // If no default view defined, switch to the first one in sequence
268 var default_view = this.flags.default_view || this.views_src[0].view_type;
269 return this.on_mode_switch(default_view);
272 * Asks the view manager to switch visualization mode.
274 * @param {String} view_type type of view to display
275 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
276 * @returns {jQuery.Deferred} new view loading promise
278 on_mode_switch: function(view_type, no_store, view_options) {
280 var view = this.views[view_type];
283 return $.Deferred().reject();
286 this.views_history.push(view_type);
288 this.active_view = view_type;
290 if (!view.controller) {
291 // Lazy loading of views
292 var controllerclass = this.registry.get_object(view_type);
293 var options = _.clone(view.options);
294 if (view_type === "form" && this.action) {
295 switch (this.action.target) {
298 options.initial_mode = 'edit';
302 var controller = new controllerclass(this, this.dataset, view.view_id, options);
303 if (view.embedded_view) {
304 controller.set_embedded_view(view.embedded_view);
306 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
307 controller.do_prev_view.add_last(this.on_prev_view);
308 var container = this.$element.find(".oe_view_manager_view_" + view_type);
309 view_promise = controller.appendTo(container);
310 this.views[view_type].controller = controller;
311 this.views[view_type].deferred.resolve(view_type);
312 $.when(view_promise).then(function() {
313 self.on_controller_inited(view_type, controller);
315 && self.flags.auto_search
316 && view.controller.searchable !== false) {
317 self.searchview.ready.then(self.searchview.do_search);
320 } else if (this.searchview
321 && self.flags.auto_search
322 && view.controller.searchable !== false) {
323 this.searchview.ready.then(this.searchview.do_search);
326 if (this.searchview) {
327 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
331 .find('.oe_view_manager_switch a').parent().removeClass('active');
333 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
334 .parent().addClass('active');
336 $.when(view_promise).then(function () {
337 _.each(_.keys(self.views), function(view_name) {
338 var controller = self.views[view_name].controller;
340 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
341 if (view_name === view_type) {
343 controller.do_show(view_options || {});
346 controller.do_hide();
351 self.$element.find('.oe_view_title_text:first').text(
352 self.display_title());
357 * Method used internally when a view asks to switch view. This method is meant
358 * to be extended by child classes to change the default behavior, which simply
359 * consist to switch to the asked view.
361 switch_view: function(view_type, no_store, options) {
362 return this.on_mode_switch(view_type, no_store, options);
365 * Returns to the view preceding the caller view in this manager's
366 * navigation history (the navigation history is appended to via
369 * @param {Object} [options]
370 * @param {Boolean} [options.created=false] resource was created
371 * @param {String} [options.default=null] view to switch to if no previous view
372 * @returns {$.Deferred} switching end signal
374 on_prev_view: function (options) {
375 options = options || {};
376 var current_view = this.views_history.pop();
377 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
378 if (options.created && current_view === 'form' && previous_view === 'list') {
379 // APR special case: "If creation mode from list (and only from a list),
380 // after saving, go to page view (don't come back in list)"
381 return this.on_mode_switch('form');
382 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
383 // APR special case: "If creation from dashboard, we have no previous view
384 return this.on_mode_switch('form');
386 return this.on_mode_switch(previous_view, true);
389 * Sets up the current viewmanager's search view.
391 * @param {Number|false} view_id the view to use or false for a default one
392 * @returns {jQuery.Deferred} search view startup deferred
394 setup_search_view: function(view_id, search_defaults) {
396 if (this.searchview) {
397 this.searchview.destroy();
399 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
401 this.searchview.on_search.add(this.do_searchview_search);
402 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
404 do_searchview_search: function(domains, contexts, groupbys) {
406 controller = this.views[this.active_view].controller,
407 action_context = this.action.context || {};
408 this.rpc('/web/session/eval_domain_and_context', {
409 domains: [this.action.domain || []].concat(domains || []),
410 contexts: [action_context].concat(contexts || []),
411 group_by_seq: groupbys || []
412 }, function (results) {
413 self.dataset._model = new instance.web.Model(
414 self.dataset.model, results.context, results.domain);
415 var groupby = results.group_by.length
417 : action_context.group_by;
418 if (_.isString(groupby)) {
421 controller.do_search(results.domain, results.context, groupby || []);
425 * Event launched when a controller has been inited.
427 * @param {String} view_type type of view
428 * @param {String} view the inited controller
430 on_controller_inited: function(view_type, view) {
433 * Called when one of the view want to execute an action
435 on_action: function(action) {
437 on_create: function() {
439 on_remove: function() {
441 on_edit: function() {
444 * Called by children view after executing an action
446 on_action_executed: function () {
448 display_title: function () {
449 var view = this.views[this.active_view];
452 return view.controller.fields_view.arch.attrs.string;
458 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
459 template:"ViewManagerAction",
461 * @constructs instance.web.ViewManagerAction
462 * @extends instance.web.ViewManager
464 * @param {instance.web.ActionManager} parent parent object/widget
465 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
467 init: function(parent, action) {
468 // dataset initialization will take the session from ``this``, so if we
469 // do not have it yet (and we don't, because we've not called our own
470 // ``_super()``) rpc requests will blow up.
471 var flags = action.flags || {};
472 if (!('auto_search' in flags)) {
473 flags.auto_search = action.auto_search !== false;
475 if (action.res_model == 'board.board' && action.view_mode === 'form') {
476 // Special case for Dashboards
478 views_switcher : false,
479 display_title : false,
483 action_buttons : false
486 this._super(parent, null, action.views, flags);
487 this.session = parent.session;
488 this.action = action;
489 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
491 dataset.ids.push(action.res_id);
494 this.dataset = dataset;
496 // setup storage for session-wise menu hiding
497 if (this.session.hidden_menutips) {
500 this.session.hidden_menutips = {}
503 * Initializes the ViewManagerAction: sets up the searchview (if the
504 * searchview is enabled in the manager's action flags), calls into the
505 * parent to initialize the primary view and (if the VMA has a searchview)
506 * launches an initial search after both views are done rendering.
511 search_defaults = {};
512 _.each(this.action.context, function (value, key) {
513 var match = /^search_default_(.*)$/.exec(key);
515 search_defaults[match[1]] = value;
519 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
521 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
523 var main_view_loaded = this._super();
525 var manager_ready = $.when(searchview_loaded, main_view_loaded);
527 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
529 if (this.action.help && !this.flags.low_profile) {
530 var Users = new instance.web.DataSet(self, 'res.users'),
531 $tips = this.$element.find('.oe_view_manager_menu_tips');
532 $tips.delegate('blockquote button', 'click', function() {
534 //noinspection FallthroughInSwitchStatementJS
535 switch ($this.attr('name')) {
537 Users.write(self.session.uid, {menu_tips:false});
539 $this.closest('blockquote').hide();
540 self.session.hidden_menutips[self.action.id] = true;
543 if (!(self.action.id in self.session.hidden_menutips)) {
544 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
546 if (!(user && user.id === self.session.uid)) {
549 $tips.find('blockquote').toggle(user.menu_tips);
554 return manager_ready;
556 on_debug_changed: function (evt) {
558 $sel = $(evt.currentTarget),
559 $option = $sel.find('option:selected'),
561 current_view = this.views[this.active_view].controller;
564 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
565 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
568 var ids = current_view.get_selected_ids();
569 if (ids.length === 1) {
570 this.dataset.call('perm_read', [ids]).then(function(result) {
571 var dialog = new instance.web.Dialog(this, {
572 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
574 }, QWeb.render('ViewManagerDebugViewLog', {
576 format : instance.web.format_value
581 case 'toggle_layout_outline':
582 current_view.rendering_engine.toggle_layout_debugging();
585 this.dataset.call_and_eval(
586 'fields_get', [false, {}], null, 1).then(function (fields) {
587 var $root = $('<dl>');
588 _(fields).each(function (attributes, name) {
589 $root.append($('<dt>').append($('<h4>').text(name)));
590 var $attrs = $('<dl>').appendTo(
591 $('<dd>').appendTo($root));
592 _(attributes).each(function (def, name) {
593 if (def instanceof Object) {
594 def = JSON.stringify(def);
597 .append($('<dt>').text(name))
598 .append($('<dd style="white-space: pre-wrap;">').text(def));
601 new instance.web.Dialog(self, {
602 title: _.str.sprintf(_t("Model %s fields"),
604 width: '95%'}, $root).open();
608 if (current_view.fields_view && current_view.fields_view.arch) {
609 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
612 this.do_warn(_t("Manage Views"),
613 _t("Could not find current view declaration"));
616 case 'edit_workflow':
617 return this.do_action({
618 res_model : 'workflow',
619 domain : [['osv', '=', this.dataset.model]],
620 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
621 type : 'ir.actions.act_window',
627 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
629 case 'manage_filters':
631 res_model: 'ir.filters',
632 views: [[false, 'list'], [false, 'form']],
633 type: 'ir.actions.act_window',
635 search_default_my_filters: true,
636 search_default_model_id: this.dataset.model
642 console.log("No debug handler for ", val);
645 evt.currentTarget.selectedIndex = 0;
647 do_edit_resource: function(model, id, action) {
648 var action = _.extend({
651 type : 'ir.actions.act_window',
654 views : [[false, 'form']],
657 action_buttons : true,
659 resize_textareas : true
663 this.do_action(action);
665 on_mode_switch: function (view_type, no_store, options) {
668 return $.when(this._super.apply(this, arguments)).then(function () {
669 var controller = self.views[self.active_view].controller,
670 fvg = controller.fields_view,
671 view_id = (fvg && fvg.view_id) || '--';
672 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
676 if (!self.action.name && fvg) {
677 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
682 do_push_state: function(state) {
683 if (this.getParent() && this.getParent().do_push_state) {
684 state["view_type"] = this.active_view;
685 this.getParent().do_push_state(state);
688 do_load_state: function(state, warm) {
691 if (state.view_type && state.view_type !== this.active_view) {
693 this.views[this.active_view].deferred.pipe(function() {
694 return self.on_mode_switch(state.view_type, true);
699 $.when(defs).then(function() {
700 self.views[self.active_view].controller.do_load_state(state, warm);
703 display_title: function () {
704 return this.action.name;
708 instance.web.Sidebar = instance.web.Widget.extend({
709 init: function(parent) {
712 var view = this.getParent();
714 { 'name' : 'print', 'label' : _t('Print'), },
715 { 'name' : 'files', 'label' : _t('Attachment'), },
716 { 'name' : 'other', 'label' : _t('More'), }
723 if (this.session.uid === 1) {
724 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
725 this.items.other.push(item);
727 this.fileupload_id = _.uniqueId('oe_fileupload');
728 $(window).on(this.fileupload_id, function() {
729 var args = [].slice.call(arguments).slice(1);
730 if (args[0] && args[0].error) {
731 alert(args[0].error);
733 self.do_attachement_update(self.dataset, self.model_id);
742 this.$element.on('click','.oe_dropdown_toggle',function(event) {
744 $(this).parent().find('ul').toggle();
747 instance.web.bus.on('click', self, function(ev) {
750 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
751 var section = $(this).data('section');
752 var index = $(this).data('index');
753 $(this).closest('ul').hide();
754 var item = self.items[section][index];
756 item.callback.apply(self, [item]);
757 } else if (item.action) {
758 self.on_item_action_clicked(item);
759 } else if (item.url) {
767 self.$element.html(QWeb.render('Sidebar', {widget: self}));
768 this.$element.find('ul').hide();
770 // Hides Sidebar sections when item list is empty
771 this.$('.oe_form_dropdown_section').each(function() {
772 $(this).toggle(!!$(this).find('li').length);
776 * For each item added to the section:
779 * will be used as the item's name in the sidebar, can be html
782 * descriptor for the action which will be executed, ``action`` and
783 * ``callback`` should be exclusive
786 * function to call when the item is clicked in the sidebar, called
787 * with the item descriptor as its first argument (so information
788 * can be stored as additional keys on the object passed to
791 * ``classname`` (optional)
792 * ``@class`` set on the sidebar serialization of the item
794 * ``title`` (optional)
795 * will be set as the item's ``@title`` (tooltip)
797 * @param {String} section_code
798 * @param {Array<{label, action | callback[, classname][, title]}>} items
800 add_items: function(section_code, items) {
803 this.items[section_code].push.apply(this.items[section_code],items);
807 add_toolbar: function(toolbar) {
809 _.each(['print','action','relate'], function(type) {
810 var items = toolbar[type];
812 for (var i = 0; i < items.length; i++) {
814 label: items[i]['name'],
816 classname: 'oe_sidebar_' + type
819 self.add_items(type=='print' ? 'print' : 'other', items);
823 on_item_action_clicked: function(item) {
825 self.getParent().sidebar_context().then(function (context) {
826 var ids = self.getParent().get_selected_ids();
827 if (ids.length == 0) {
828 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
831 var additional_context = _.extend({
834 active_model: self.getParent().dataset.model
836 self.rpc("/web/action/load", {
837 action_id: item.action.id,
838 context: additional_context
839 }, function(result) {
840 result.result.context = _.extend(result.result.context || {},
842 result.result.flags = result.result.flags || {};
843 result.result.flags.new_window = true;
844 self.do_action(result.result, function () {
846 self.getParent().reload();
851 do_attachement_update: function(dataset, model_id) {
852 this.dataset = dataset;
853 this.model_id = model_id;
855 this.on_attachments_loaded([]);
857 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
858 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
859 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
862 on_attachments_loaded: function(attachments) {
865 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
866 _.each(attachments,function(a) {
868 if(a.type === "binary") {
869 a.url = prefix + a.id + '&t=' + (new Date().getTime());
872 self.items['files'] = attachments;
874 this.$('.oe_sidebar_add_attachment .oe-binary-file').change(this.on_attachment_changed);
875 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
877 on_attachment_changed: function(e) {
878 var $e = $(e.target);
879 if ($e.val() !== '') {
880 this.$element.find('form.oe-binary-form').submit();
881 $e.parent().find('input[type=file]').prop('disabled', true);
882 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
883 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
887 on_attachment_delete: function(e) {
892 var $e = $(e.currentTarget);
893 if (confirm(_t("Do you really want to delete this attachment ?"))) {
894 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
895 self.do_attachement_update(self.dataset, self.model_id);
901 instance.web.TranslateDialog = instance.web.Dialog.extend({
902 dialog_title: {toString: function () { return _t("Translations"); }},
903 init: function(view) {
904 // TODO fme: should add the language to fields_view_get because between the fields view get
905 // and the moment the user opens the translation dialog, the user language could have been changed
906 this.view_language = view.session.user_context.lang;
907 this['on_button' + _t("Save")] = this.on_button_Save;
908 this['on_button' + _t("Close")] = this.on_button_Close;
914 this.view_type = view.fields_view.type || '';
915 this.$fields_form = null;
916 this.$view_form = null;
917 this.$sidebar_form = null;
918 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
919 this.languages = null;
920 this.languages_loaded = $.Deferred();
921 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
922 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
927 $.when(this.languages_loaded).then(function() {
928 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
929 self.$fields_form = self.$element.find('.oe_translation_form');
930 self.$fields_form.find('.oe_trad_field').change(function() {
931 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
936 on_languages_loaded: function(langs) {
937 this.languages = langs;
938 this.languages_loaded.resolve();
940 do_load_fields_values: function(callback) {
943 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
944 _.each(self.languages, function(lg) {
945 var deff = $.Deferred();
947 var callback = function(values) {
948 _.each(self.translatable_fields_keys, function(f) {
949 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
953 if (lg.code === self.view_language) {
955 _.each(self.translatable_fields_keys, function(field) {
956 values[field] = self.view.fields[field].get_value();
960 self.rpc('/web/dataset/get', {
961 model: self.view.dataset.model,
962 ids: [self.view.datarecord.id],
963 fields: self.translatable_fields_keys,
964 context: self.view.dataset.get_context({
969 $.when.apply(null, deffered).then(callback);
971 open: function(field) {
974 $.when(this.languages_loaded).then(function() {
975 if (self.view.translatable_fields && self.view.translatable_fields.length) {
976 self.do_load_fields_values(function() {
979 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
980 self.$element.scrollTo($field_input);
981 $field_input.focus();
989 on_button_Save: function() {
992 trads_mutex = new $.Mutex();
993 self.$fields_form.find('.oe_trad_field.touched').each(function() {
994 var field = $(this).attr('name').split('-');
995 if (!trads[field[0]]) {
996 trads[field[0]] = {};
998 trads[field[0]][field[1]] = $(this).val();
1000 _.each(trads, function(data, code) {
1001 if (code === self.view_language) {
1002 _.each(data, function(value, field) {
1003 self.view.fields[field].set_value(value);
1006 trads_mutex.exec(function() {
1007 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1012 on_button_Close: function() {
1017 instance.web.View = instance.web.Widget.extend({
1018 template: "EmptyComponent",
1019 // name displayed in view switchers
1022 * Define a view type for each view to allow automatic call to fields_view_get.
1024 view_type: undefined,
1025 init: function(parent, dataset, view_id, options) {
1026 this._super(parent);
1027 this.dataset = dataset;
1028 this.view_id = view_id;
1029 this.set_default_options(options);
1032 return this.load_view();
1034 load_view: function() {
1035 if (this.embedded_view) {
1036 var def = $.Deferred();
1038 $.async_when().then(function() {def.resolve(self.embedded_view);});
1039 return def.pipe(this.on_loaded);
1041 var context = new instance.web.CompoundContext(this.dataset.get_context());
1042 if (! this.view_type)
1043 console.warn("view_type is not defined", this);
1044 return this.rpc("/web/view/load", {
1045 "model": this.dataset.model,
1046 "view_id": this.view_id,
1047 "view_type": this.view_type,
1048 toolbar: !!this.options.$sidebar,
1050 }).pipe(this.on_loaded);
1054 * Called after a successful call to fields_view_get.
1055 * Must return a promise.
1057 on_loaded: function(fields_view_get) {
1059 set_default_options: function(options) {
1060 this.options = options || {};
1061 _.defaults(this.options, {
1062 // All possible views options should be defaulted here
1066 action_views_ids: {}
1069 open_translate_dialog: function(field) {
1070 if (!this.translate_dialog) {
1071 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1073 this.translate_dialog.open(field);
1076 * Fetches and executes the action identified by ``action_data``.
1078 * @param {Object} action_data the action descriptor data
1079 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1080 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1081 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1082 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1083 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1084 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1085 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1087 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1089 var result_handler = function () {
1090 if (on_closed) { on_closed.apply(null, arguments); }
1091 if (self.getParent() && self.getParent().on_action_executed) {
1092 return self.getParent().on_action_executed.apply(null, arguments);
1095 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1097 var handler = function (r) {
1098 var action = r.result;
1099 if (action && action.constructor == Object) {
1100 var ncontext = new instance.web.CompoundContext(context);
1103 active_id: record_id,
1104 active_ids: [record_id],
1105 active_model: dataset.model
1108 ncontext.add(action.context || {});
1109 return self.rpc('/web/session/eval_domain_and_context', {
1110 contexts: [ncontext],
1112 }).pipe(function (results) {
1113 action.context = results.context;
1114 /* niv: previously we were overriding once more with action_data.context,
1115 * I assumed this was not a correct behavior and removed it
1117 return self.do_action(action, result_handler);
1120 return result_handler();
1124 if (action_data.special) {
1125 return handler({result: {"type":"ir.actions.act_window_close"}});
1126 } else if (action_data.type=="object") {
1127 var args = [[record_id]], additional_args = [];
1128 if (action_data.args) {
1130 // Warning: quotes and double quotes problem due to json and xml clash
1131 // Maybe we should force escaping in xml or do a better parse of the args array
1132 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1133 args = args.concat(additional_args);
1135 console.error("Could not JSON.parse arguments", action_data.args);
1139 return dataset.call_button(action_data.name, args, handler);
1140 } else if (action_data.type=="action") {
1141 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1143 return dataset.exec_workflow(record_id, action_data.name, handler);
1147 * Directly set a view to use instead of calling fields_view_get. This method must
1148 * be called before start(). When an embedded view is set, underlying implementations
1149 * of instance.web.View must use the provided view instead of any other one.
1151 * @param embedded_view A view.
1153 set_embedded_view: function(embedded_view) {
1154 this.embedded_view = embedded_view;
1156 do_show: function () {
1157 this.$element.show();
1159 do_hide: function () {
1160 this.$element.hide();
1162 do_push_state: function(state) {
1163 if (this.getParent() && this.getParent().do_push_state) {
1164 this.getParent().do_push_state(state);
1167 do_load_state: function(state, warm) {
1170 * Switches to a specific view type
1172 * @param {String} view view type to switch to
1174 do_switch_view: function(view) {
1177 * Cancels the switch to the current view, switches to the previous one
1179 * @param {Object} [options]
1180 * @param {Boolean} [options.created=false] resource was created
1181 * @param {String} [options.default=null] view to switch to if no previous view
1183 do_prev_view: function (options) {
1185 do_search: function(view) {
1187 on_sidebar_import: function() {
1188 var import_view = new instance.web.DataImport(this, this.dataset);
1189 import_view.start();
1191 on_sidebar_export: function() {
1192 var export_view = new instance.web.DataExport(this, this.dataset);
1193 export_view.start();
1195 on_sidebar_translate: function() {
1196 return this.do_action({
1197 res_model : 'ir.translation',
1198 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1199 views: [[false, 'list'], [false, 'form']],
1200 type : 'ir.actions.act_window',
1205 sidebar_context: function () {
1209 * Asks the view to reload itself, if the reloading is asynchronous should
1210 * return a {$.Deferred} indicating when the reloading is done.
1212 reload: function () {
1217 instance.web.xml_to_json = function(node) {
1218 switch (node.nodeType) {
1224 var attrs = $(node).getAttributes();
1225 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1228 attrs[key] = JSON.parse(attrs[key]);
1233 tag: node.tagName.toLowerCase(),
1235 children: _.map(node.childNodes, instance.web.xml_to_json)
1239 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1240 // For debugging purpose, this function will convert a json node back to xml
1241 // Maybe useful for xml view editor
1242 indent = indent || 0;
1243 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1244 r = sindent + '<' + node.tag,
1245 cr = human_readable ? '\n' : '';
1247 if (typeof(node) === 'string') {
1248 return sindent + node;
1249 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1250 throw("Node a json node");
1252 for (var attr in node.attrs) {
1253 var vattr = node.attrs[attr];
1254 if (typeof(vattr) !== 'string') {
1256 vattr = JSON.stringify(vattr);
1258 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1259 if (human_readable) {
1260 vattr = vattr.replace(/"/g, "'");
1262 r += ' ' + attr + '="' + vattr + '"';
1264 if (node.children && node.children.length) {
1267 for (var i = 0, ii = node.children.length; i < ii; i++) {
1268 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1270 r += childs.join(cr);
1271 r += cr + sindent + '</' + node.tag + '>';
1277 instance.web.xml_to_str = function(node) {
1278 if (window.ActiveXObject) {
1281 return (new XMLSerializer()).serializeToString(node);
1284 instance.web.str_to_xml = function(s) {
1285 if (window.DOMParser) {
1286 var dp = new DOMParser();
1287 var r = dp.parseFromString(s, "text/xml");
1288 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1289 throw new Error("Could not parse string to xml");
1295 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1297 throw new Error("Could not find a DOM Parser: " + e.message);
1300 xDoc.preserveWhiteSpace = true;
1306 * Registry for all the main views
1308 instance.web.views = new instance.web.Registry();
1312 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: