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 this.ir_actions_client(state.client_action);
83 $.when(action_loaded || null).then(function() {
84 if (self.inner_viewmanager) {
85 self.inner_viewmanager.do_load_state(state, warm);
89 do_action: function(action, on_close) {
90 if (_.isNumber(action)) {
92 return self.rpc("/web/action/load", { action_id: action }, function(result) {
93 self.do_action(result.result, on_close);
97 console.error("No type for action", action);
100 var type = action.type.replace(/\./g,'_');
101 var popup = action.target === 'new';
102 var inline = action.target === 'inline';
103 action.flags = _.extend({
104 views_switcher : !popup && !inline,
105 search_view : !popup && !inline,
106 action_buttons : !popup && !inline,
107 sidebar : !popup && !inline,
108 pager : !popup && !inline,
109 display_title : !popup
110 }, action.flags || {});
111 if (!(type in this)) {
112 console.error("Action manager can't handle action of type " + action.type, action);
115 return this[type](action, on_close);
117 null_action: function() {
121 ir_actions_act_window: function (action, on_close) {
123 if (_(['base.module.upgrade', 'base.setup.installer'])
124 .contains(action.res_model)) {
125 var old_close = on_close;
126 on_close = function () {
127 instance.webclient.do_reload().then(old_close);
130 if (action.target === 'new') {
131 if (this.dialog == null) {
132 this.dialog = new instance.web.Dialog(this, { width: '80%' });
134 this.dialog.on_close.add(on_close);
136 this.dialog_viewmanager.destroy();
138 this.dialog.dialog_title = action.name;
139 this.dialog_viewmanager = new instance.web.ViewManagerAction(this, action);
140 this.dialog_viewmanager.appendTo(this.dialog.$element);
146 return this.getParent().do_action(action, function () {
147 instance.webclient.menu.open_menu(action.menu_id);
150 this.inner_action = action;
151 this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
152 this.inner_viewmanager.appendTo(this.$element);
155 ir_actions_act_window_close: function (action, on_closed) {
156 if (!this.dialog && on_closed) {
161 ir_actions_server: function (action, on_closed) {
163 this.rpc('/web/action/run', {
164 action_id: action.id,
165 context: action.context || {}
166 }).then(function (action) {
167 self.do_action(action, on_closed)
170 ir_actions_client: function (action) {
173 var ClientWidget = instance.web.client_actions.get_object(action.tag);
174 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
176 ir_actions_report_xml: function(action, on_closed) {
179 self.rpc("/web/session/eval_domain_and_context", {
180 contexts: [action.context],
182 }).then(function(res) {
183 action = _.clone(action);
184 action.context = res.context;
185 self.session.get_file({
187 data: {action: JSON.stringify(action)},
188 complete: $.unblockUI,
190 if (!self.dialog && on_closed) {
195 error: instance.webclient.crashmanager.on_rpc_error
199 ir_actions_act_url: function (action) {
200 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
202 ir_ui_menu: function (action) {
203 this.getParent().do_action(action);
207 instance.web.ViewManager = instance.web.Widget.extend({
208 template: "ViewManager",
209 init: function(parent, dataset, views, flags) {
211 this.model = dataset ? dataset.model : undefined;
212 this.dataset = dataset;
213 this.searchview = null;
214 this.active_view = null;
215 this.views_src = _.map(views, function(x) {
216 if (x instanceof Array) {
217 var View = instance.web.views.get_object(x[1], true);
221 label: View ? View.prototype.display_name : (void 'nope')
228 this.flags = flags || {};
229 this.registry = instance.web.views;
230 this.views_history = [];
233 * @returns {jQuery.Deferred} initial view loading promise
238 this.$element.find('.oe_view_manager_switch a').click(function() {
239 self.on_mode_switch($(this).data('view-type'));
242 _.each(this.views_src, function(view) {
243 self.views[view.view_type] = $.extend({}, view, {
244 deferred : $.Deferred(),
247 $buttons : self.$element.find('.oe_view_manager_buttons'),
248 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
249 $pager : self.$element.find('.oe_view_manager_pager'),
250 action : self.action,
251 action_views_ids : views_ids
252 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
254 views_ids[view.view_type] = view.view_id;
256 if (this.flags.views_switcher === false) {
257 this.$element.find('.oe_view_manager_switch').hide();
259 // If no default view defined, switch to the first one in sequence
260 var default_view = this.flags.default_view || this.views_src[0].view_type;
261 return this.on_mode_switch(default_view);
264 * Asks the view manager to switch visualization mode.
266 * @param {String} view_type type of view to display
267 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
268 * @returns {jQuery.Deferred} new view loading promise
270 on_mode_switch: function(view_type, no_store) {
272 var view = this.views[view_type];
275 return $.Deferred().reject();
278 this.views_history.push(view_type);
280 this.active_view = view_type;
282 if (!view.controller) {
283 // Lazy loading of views
284 var controllerclass = this.registry.get_object(view_type);
285 var options = _.clone(view.options);
286 if (view_type === "form" && this.action) {
287 switch (this.action.target) {
290 options.initial_mode = 'edit';
294 var controller = new controllerclass(this, this.dataset, view.view_id, options);
295 if (view.embedded_view) {
296 controller.set_embedded_view(view.embedded_view);
298 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
299 controller.do_prev_view.add_last(this.on_prev_view);
300 var container = this.$element.find(".oe_view_manager_view_" + view_type);
301 view_promise = controller.appendTo(container);
302 this.views[view_type].controller = controller;
303 this.views[view_type].deferred.resolve(view_type);
304 $.when(view_promise).then(function() {
305 self.on_controller_inited(view_type, controller);
307 && self.flags.auto_search
308 && view.controller.searchable !== false) {
309 self.searchview.ready.then(self.searchview.do_search);
312 } else if (this.searchview
313 && self.flags.auto_search
314 && view.controller.searchable !== false) {
315 this.searchview.ready.then(this.searchview.do_search);
318 if (this.searchview) {
319 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
323 .find('.oe_view_manager_switch a').parent().removeClass('active')
325 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
326 .parent().addClass('active');
328 $.when(view_promise).then(function () {
329 _.each(_.keys(self.views), function(view_name) {
330 var controller = self.views[view_name].controller;
332 if (view_name === view_type) {
333 controller.do_show();
335 controller.do_hide();
340 self.$element.find('.oe_view_title_text:first').text(
341 self.display_title());
346 * Method used internally when a view asks to switch view. This method is meant
347 * to be extended by child classes to change the default behavior, which simply
348 * consist to switch to the asked view.
350 switch_view: function(view_type, no_store) {
351 return this.on_mode_switch(view_type, no_store);
354 * Returns to the view preceding the caller view in this manager's
355 * navigation history (the navigation history is appended to via
358 * @param {Object} [options]
359 * @param {Boolean} [options.created=false] resource was created
360 * @param {String} [options.default=null] view to switch to if no previous view
361 * @returns {$.Deferred} switching end signal
363 on_prev_view: function (options) {
364 options = options || {};
365 var current_view = this.views_history.pop();
366 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
367 if (options.created && current_view === 'form' && previous_view === 'list') {
368 // APR special case: "If creation mode from list (and only from a list),
369 // after saving, go to page view (don't come back in list)"
370 return this.on_mode_switch('form');
371 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
372 // APR special case: "If creation from dashboard, we have no previous view
373 return this.on_mode_switch('form');
375 return this.on_mode_switch(previous_view, true);
378 * Sets up the current viewmanager's search view.
380 * @param {Number|false} view_id the view to use or false for a default one
381 * @returns {jQuery.Deferred} search view startup deferred
383 setup_search_view: function(view_id, search_defaults) {
385 if (this.searchview) {
386 this.searchview.destroy();
388 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
390 this.searchview.on_search.add(this.do_searchview_search);
391 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
393 do_searchview_search: function(domains, contexts, groupbys) {
395 controller = this.views[this.active_view].controller,
396 action_context = this.action.context || {};
397 this.rpc('/web/session/eval_domain_and_context', {
398 domains: [this.action.domain || []].concat(domains || []),
399 contexts: [action_context].concat(contexts || []),
400 group_by_seq: groupbys || []
401 }, function (results) {
402 self.dataset._model = new instance.web.Model(
403 self.dataset.model, results.context, results.domain);
404 var groupby = results.group_by.length
406 : action_context.group_by;
407 if (_.isString(groupby)) {
410 controller.do_search(results.domain, results.context, groupby || []);
414 * Event launched when a controller has been inited.
416 * @param {String} view_type type of view
417 * @param {String} view the inited controller
419 on_controller_inited: function(view_type, view) {
422 * Called when one of the view want to execute an action
424 on_action: function(action) {
426 on_create: function() {
428 on_remove: function() {
430 on_edit: function() {
433 * Called by children view after executing an action
435 on_action_executed: function () {
437 display_title: function () {
438 var view = this.views[this.active_view];
441 return view.controller.fields_view.arch.attrs.string;
447 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
448 template:"ViewManagerAction",
450 * @constructs instance.web.ViewManagerAction
451 * @extends instance.web.ViewManager
453 * @param {instance.web.ActionManager} parent parent object/widget
454 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
456 init: function(parent, action) {
457 // dataset initialization will take the session from ``this``, so if we
458 // do not have it yet (and we don't, because we've not called our own
459 // ``_super()``) rpc requests will blow up.
460 var flags = action.flags || {};
461 if (!('auto_search' in flags)) {
462 flags.auto_search = action.auto_search !== false;
464 if (action.res_model == 'board.board' && action.view_mode === 'form') {
465 // Special case for Dashboards
467 views_switcher : false,
468 display_title : false,
472 action_buttons : false
475 this._super(parent, null, action.views, flags);
476 this.session = parent.session;
477 this.action = action;
478 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
480 dataset.ids.push(action.res_id);
483 this.dataset = dataset;
485 // setup storage for session-wise menu hiding
486 if (this.session.hidden_menutips) {
489 this.session.hidden_menutips = {}
492 * Initializes the ViewManagerAction: sets up the searchview (if the
493 * searchview is enabled in the manager's action flags), calls into the
494 * parent to initialize the primary view and (if the VMA has a searchview)
495 * launches an initial search after both views are done rendering.
500 search_defaults = {};
501 _.each(this.action.context, function (value, key) {
502 var match = /^search_default_(.*)$/.exec(key);
504 search_defaults[match[1]] = value;
508 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
510 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
512 var main_view_loaded = this._super();
514 var manager_ready = $.when(searchview_loaded, main_view_loaded);
516 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
518 if (this.action.help && !this.flags.low_profile) {
519 var Users = new instance.web.DataSet(self, 'res.users'),
520 $tips = this.$element.find('.oe_view_manager_menu_tips');
521 $tips.delegate('blockquote button', 'click', function() {
523 //noinspection FallthroughInSwitchStatementJS
524 switch ($this.attr('name')) {
526 Users.write(self.session.uid, {menu_tips:false});
528 $this.closest('blockquote').hide();
529 self.session.hidden_menutips[self.action.id] = true;
532 if (!(self.action.id in self.session.hidden_menutips)) {
533 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
535 if (!(user && user.id === self.session.uid)) {
538 $tips.find('blockquote').toggle(user.menu_tips);
543 return manager_ready;
545 on_debug_changed: function (evt) {
547 $sel = $(evt.currentTarget),
548 $option = $sel.find('option:selected'),
550 current_view = this.views[this.active_view].controller;
553 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
554 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
557 var ids = current_view.get_selected_ids();
558 if (ids.length === 1) {
559 this.dataset.call('perm_read', [ids]).then(function(result) {
560 var dialog = new instance.web.Dialog(this, {
561 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
563 }, QWeb.render('ViewManagerDebugViewLog', {
565 format : instance.web.format_value
570 case 'toggle_layout_outline':
571 current_view.rendering_engine.toggle_layout_debugging();
574 this.dataset.call_and_eval(
575 'fields_get', [false, {}], null, 1).then(function (fields) {
576 var $root = $('<dl>');
577 _(fields).each(function (attributes, name) {
578 $root.append($('<dt>').append($('<h4>').text(name)));
579 var $attrs = $('<dl>').appendTo(
580 $('<dd>').appendTo($root));
581 _(attributes).each(function (def, name) {
582 if (def instanceof Object) {
583 def = JSON.stringify(def);
586 .append($('<dt>').text(name))
587 .append($('<dd style="white-space: pre-wrap;">').text(def));
590 new instance.web.Dialog(self, {
591 title: _.str.sprintf(_t("Model %s fields"),
593 width: '95%'}, $root).open();
597 if (current_view.fields_view && current_view.fields_view.arch) {
598 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
601 this.do_warn(_t("Manage Views"),
602 _t("Could not find current view declaration"));
605 case 'edit_workflow':
606 return this.do_action({
607 res_model : 'workflow',
608 domain : [['osv', '=', this.dataset.model]],
609 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
610 type : 'ir.actions.act_window',
616 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
620 console.log("No debug handler for ", val);
623 evt.currentTarget.selectedIndex = 0;
625 do_edit_resource: function(model, id, action) {
626 var action = _.extend({
629 type : 'ir.actions.act_window',
632 views : [[false, 'form']],
635 action_buttons : true,
637 resize_textareas : true
641 this.do_action(action);
643 on_mode_switch: function (view_type, no_store) {
646 return $.when(this._super(view_type, no_store)).then(function () {
647 var controller = self.views[self.active_view].controller,
648 fvg = controller.fields_view,
649 view_id = (fvg && fvg.view_id) || '--';
650 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
654 if (!self.action.name && fvg) {
655 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
660 do_push_state: function(state) {
661 if (this.getParent() && this.getParent().do_push_state) {
662 state["view_type"] = this.active_view;
663 this.getParent().do_push_state(state);
666 do_load_state: function(state, warm) {
669 if (state.view_type && state.view_type !== this.active_view) {
671 this.views[this.active_view].deferred.pipe(function() {
672 return self.on_mode_switch(state.view_type, true);
677 $.when(defs).then(function() {
678 self.views[self.active_view].controller.do_load_state(state, warm);
681 display_title: function () {
682 return this.action.name;
686 instance.web.Sidebar = instance.web.Widget.extend({
687 init: function(parent) {
689 var view = this.getParent();
691 { 'name' : 'print', 'label' : _t('Print'), },
692 { 'name' : 'files', 'label' : _t('Attachement'), },
693 { 'name' : 'other', 'label' : _t('More'), }
699 { label: _t("Import"), callback: view.on_sidebar_import },
700 { label: _t("Export"), callback: view.on_sidebar_export }
703 if (this.session.uid === 1) {
704 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
705 this.items.other.push(item);
712 this.$element.on('click','.oe_dropdown_toggle',function(event) {
713 $(this).parent().find('ul').toggle();
716 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
717 var section = $(this).data('section');
718 var index = $(this).data('index');
719 $(this).closest('ul').hide();
720 var item = self.items[section][index];
722 item.callback.apply(self, [item]);
723 } else if (item.action) {
724 self.on_item_action_clicked(item);
725 } else if (item.url) {
730 //this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
731 //this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
732 //this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
736 self.$element.html(QWeb.render('Sidebar', {widget: self}));
737 this.$element.find('ul').hide();
740 * For each item added to the section:
743 * will be used as the item's name in the sidebar, can be html
746 * descriptor for the action which will be executed, ``action`` and
747 * ``callback`` should be exclusive
750 * function to call when the item is clicked in the sidebar, called
751 * with the item descriptor as its first argument (so information
752 * can be stored as additional keys on the object passed to
755 * ``classname`` (optional)
756 * ``@class`` set on the sidebar serialization of the item
758 * ``title`` (optional)
759 * will be set as the item's ``@title`` (tooltip)
761 * @param {String} section_code
762 * @param {Array<{label, action | callback[, classname][, title]}>} items
764 add_items: function(section_code, items) {
767 this.items[section_code].push.apply(this.items[section_code],items);
771 add_toolbar: function(toolbar) {
773 _.each(['print','action','relate'], function(type) {
774 var items = toolbar[type];
776 for (var i = 0; i < items.length; i++) {
778 label: items[i]['name'],
780 classname: 'oe_sidebar_' + type
783 self.add_items(type=='print' ? 'print' : 'other', items);
787 on_item_action_clicked: function(item) {
789 self.getParent().sidebar_context().then(function (context) {
790 var ids = self.getParent().get_selected_ids();
791 if (ids.length == 0) {
792 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
795 var additional_context = _.extend({
798 active_model: self.getParent().dataset.model
800 self.rpc("/web/action/load", {
801 action_id: item.action.id,
802 context: additional_context
803 }, function(result) {
804 result.result.context = _.extend(result.result.context || {},
806 result.result.flags = result.result.flags || {};
807 result.result.flags.new_window = true;
808 self.do_action(result.result, function () {
810 self.getParent().reload();
815 do_attachement_update: function(dataset, model_id) {
817 this.on_attachments_loaded([]);
819 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
820 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
821 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
824 on_attachments_loaded: function(attachments) {
827 // TODO: preprend: _s +
828 var prefix = '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
829 _.each(attachments,function(a) {
831 if(a.type === "binary") {
832 a.url = prefix + a.id + '&t=' + (new Date().getTime());
835 attachments.push( { label: _t("Add..."), callback: self.on_attachment_add } );
836 self.items['files'] = attachments;
839 on_attachment_add: function(e) {
840 this.$element.find('.oe_sidebar_add').show();
842 on_attachment_changed: function(e) {
844 window[this.element_id + '_iframe'] = this.do_update;
845 var $e = $(e.target);
846 if ($e.val() != '') {
847 this.$element.find('form.oe-binary-form').submit();
848 $e.parent().find('input[type=file]').prop('disabled', true);
849 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
852 on_attachment_delete: function(e) {
854 var self = this, $e = $(e.currentTarget);
855 var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
856 if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
857 this.rpc('/web/dataset/unlink', {
858 model: 'ir.attachment',
859 ids: [parseInt($e.attr('data-id'))]
861 $e.parent().remove();
862 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
868 instance.web.TranslateDialog = instance.web.Dialog.extend({
869 dialog_title: {toString: function () { return _t("Translations"); }},
870 init: function(view) {
871 // TODO fme: should add the language to fields_view_get because between the fields view get
872 // and the moment the user opens the translation dialog, the user language could have been changed
873 this.view_language = view.session.user_context.lang;
874 this['on_button' + _t("Save")] = this.on_button_Save;
875 this['on_button' + _t("Close")] = this.on_button_Close;
881 this.view_type = view.fields_view.type || '';
882 this.$fields_form = null;
883 this.$view_form = null;
884 this.$sidebar_form = null;
885 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
886 this.languages = null;
887 this.languages_loaded = $.Deferred();
888 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
889 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
894 $.when(this.languages_loaded).then(function() {
895 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
896 self.$fields_form = self.$element.find('.oe_translation_form');
897 self.$fields_form.find('.oe_trad_field').change(function() {
898 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
903 on_languages_loaded: function(langs) {
904 this.languages = langs;
905 this.languages_loaded.resolve();
907 do_load_fields_values: function(callback) {
910 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
911 _.each(self.languages, function(lg) {
912 var deff = $.Deferred();
914 var callback = function(values) {
915 _.each(self.translatable_fields_keys, function(f) {
916 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
920 if (lg.code === self.view_language) {
922 _.each(self.translatable_fields_keys, function(field) {
923 values[field] = self.view.fields[field].get_value();
927 self.rpc('/web/dataset/get', {
928 model: self.view.dataset.model,
929 ids: [self.view.datarecord.id],
930 fields: self.translatable_fields_keys,
931 context: self.view.dataset.get_context({
936 $.when.apply(null, deffered).then(callback);
938 open: function(field) {
941 $.when(this.languages_loaded).then(function() {
942 if (self.view.translatable_fields && self.view.translatable_fields.length) {
943 self.do_load_fields_values(function() {
946 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
947 self.$element.scrollTo($field_input);
948 $field_input.focus();
956 on_button_Save: function() {
959 trads_mutex = new $.Mutex();
960 self.$fields_form.find('.oe_trad_field.touched').each(function() {
961 var field = $(this).attr('name').split('-');
962 if (!trads[field[0]]) {
963 trads[field[0]] = {};
965 trads[field[0]][field[1]] = $(this).val();
967 _.each(trads, function(data, code) {
968 if (code === self.view_language) {
969 _.each(data, function(value, field) {
970 self.view.fields[field].set_value(value);
973 trads_mutex.exec(function() {
974 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
979 on_button_Close: function() {
984 instance.web.View = instance.web.Widget.extend({
985 template: "EmptyComponent",
986 // name displayed in view switchers
989 * Define a view type for each view to allow automatic call to fields_view_get.
991 view_type: undefined,
992 init: function(parent, dataset, view_id, options) {
994 this.dataset = dataset;
995 this.view_id = view_id;
996 this.set_default_options(options);
999 return this.load_view();
1001 load_view: function() {
1002 if (this.embedded_view) {
1003 var def = $.Deferred();
1005 $.async_when().then(function() {def.resolve(self.embedded_view);});
1006 return def.pipe(this.on_loaded);
1008 var context = new instance.web.CompoundContext(this.dataset.get_context());
1009 if (! this.view_type)
1010 console.warn("view_type is not defined", this);
1011 return this.rpc("/web/view/load", {
1012 "model": this.dataset.model,
1013 "view_id": this.view_id,
1014 "view_type": this.view_type,
1015 toolbar: !!this.options.$sidebar,
1017 }).pipe(this.on_loaded);
1021 * Called after a successful call to fields_view_get.
1022 * Must return a promise.
1024 on_loaded: function(fields_view_get) {
1026 set_default_options: function(options) {
1027 this.options = options || {};
1028 _.defaults(this.options, {
1029 // All possible views options should be defaulted here
1033 action_views_ids: {}
1036 open_translate_dialog: function(field) {
1037 if (!this.translate_dialog) {
1038 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1040 this.translate_dialog.open(field);
1043 * Fetches and executes the action identified by ``action_data``.
1045 * @param {Object} action_data the action descriptor data
1046 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1047 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1048 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1049 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1050 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1051 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1052 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1054 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1056 var result_handler = function () {
1057 if (on_closed) { on_closed.apply(null, arguments); }
1058 if (self.getParent() && self.getParent().on_action_executed) {
1059 return self.getParent().on_action_executed.apply(null, arguments);
1062 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1064 var handler = function (r) {
1065 var action = r.result;
1066 if (action && action.constructor == Object) {
1067 var ncontext = new instance.web.CompoundContext(context);
1070 active_id: record_id,
1071 active_ids: [record_id],
1072 active_model: dataset.model
1075 ncontext.add(action.context || {});
1076 return self.rpc('/web/session/eval_domain_and_context', {
1077 contexts: [ncontext],
1079 }).pipe(function (results) {
1080 action.context = results.context;
1081 /* niv: previously we were overriding once more with action_data.context,
1082 * I assumed this was not a correct behavior and removed it
1084 return self.do_action(action, result_handler);
1087 return result_handler();
1091 if (action_data.special) {
1092 return handler({result: {"type":"ir.actions.act_window_close"}});
1093 } else if (action_data.type=="object") {
1094 var args = [[record_id]], additional_args = [];
1095 if (action_data.args) {
1097 // Warning: quotes and double quotes problem due to json and xml clash
1098 // Maybe we should force escaping in xml or do a better parse of the args array
1099 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1100 args = args.concat(additional_args);
1102 console.error("Could not JSON.parse arguments", action_data.args);
1106 return dataset.call_button(action_data.name, args, handler);
1107 } else if (action_data.type=="action") {
1108 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1110 return dataset.exec_workflow(record_id, action_data.name, handler);
1114 * Directly set a view to use instead of calling fields_view_get. This method must
1115 * be called before start(). When an embedded view is set, underlying implementations
1116 * of instance.web.View must use the provided view instead of any other one.
1118 * @param embedded_view A view.
1120 set_embedded_view: function(embedded_view) {
1121 this.embedded_view = embedded_view;
1123 do_show: function () {
1124 this.$element.show();
1126 do_hide: function () {
1127 this.$element.hide();
1129 do_push_state: function(state) {
1130 if (this.getParent() && this.getParent().do_push_state) {
1131 this.getParent().do_push_state(state);
1134 do_load_state: function(state, warm) {
1137 * Switches to a specific view type
1139 * @param {String} view view type to switch to
1141 do_switch_view: function(view) {
1144 * Cancels the switch to the current view, switches to the previous one
1146 * @param {Object} [options]
1147 * @param {Boolean} [options.created=false] resource was created
1148 * @param {String} [options.default=null] view to switch to if no previous view
1150 do_prev_view: function (options) {
1152 do_search: function(view) {
1154 on_sidebar_import: function() {
1155 var import_view = new instance.web.DataImport(this, this.dataset);
1156 import_view.start();
1158 on_sidebar_export: function() {
1159 var export_view = new instance.web.DataExport(this, this.dataset);
1160 export_view.start();
1162 on_sidebar_translate: function() {
1163 return this.do_action({
1164 res_model : 'ir.translation',
1165 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1166 views: [[false, 'list'], [false, 'form']],
1167 type : 'ir.actions.act_window',
1172 sidebar_context: function () {
1176 * Asks the view to reload itself, if the reloading is asynchronous should
1177 * return a {$.Deferred} indicating when the reloading is done.
1179 reload: function () {
1184 instance.web.xml_to_json = function(node) {
1185 switch (node.nodeType) {
1191 var attrs = $(node).getAttributes();
1192 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1195 attrs[key] = JSON.parse(attrs[key]);
1200 tag: node.tagName.toLowerCase(),
1202 children: _.map(node.childNodes, instance.web.xml_to_json)
1206 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1207 // For debugging purpose, this function will convert a json node back to xml
1208 // Maybe useful for xml view editor
1209 indent = indent || 0;
1210 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1211 r = sindent + '<' + node.tag,
1212 cr = human_readable ? '\n' : '';
1214 if (typeof(node) === 'string') {
1215 return sindent + node;
1216 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1217 throw("Node a json node");
1219 for (var attr in node.attrs) {
1220 var vattr = node.attrs[attr];
1221 if (typeof(vattr) !== 'string') {
1223 vattr = JSON.stringify(vattr);
1225 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1226 if (human_readable) {
1227 vattr = vattr.replace(/"/g, "'");
1229 r += ' ' + attr + '="' + vattr + '"';
1231 if (node.children && node.children.length) {
1234 for (var i = 0, ii = node.children.length; i < ii; i++) {
1235 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1237 r += childs.join(cr);
1238 r += cr + sindent + '</' + node.tag + '>';
1244 instance.web.xml_to_str = function(node) {
1245 if (window.ActiveXObject) {
1248 return (new XMLSerializer()).serializeToString(node);
1251 instance.web.str_to_xml = function(s) {
1252 if (window.DOMParser) {
1253 var dp = new DOMParser();
1254 var r = dp.parseFromString(s, "text/xml");
1255 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1256 throw new Error("Could not parse string to xml");
1262 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1264 throw new Error("Could not find a DOM Parser: " + e.message);
1267 xDoc.preserveWhiteSpace = true;
1273 * Registry for all the main views
1275 instance.web.views = new instance.web.Registry();
1279 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: