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['title'] = this.inner_action.name;
40 state['model'] = this.inner_action.res_model;
41 if (this.inner_action.id) {
42 state['action_id'] = this.inner_action.id;
45 this.getParent().do_push_state(state);
48 do_load_state: function(state, warm) {
51 if (state.action_id) {
52 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
55 action_loaded = this.do_action(state.action_id);
56 instance.webclient.menu.has_been_loaded.then(function() {
57 instance.webclient.menu.open_action(state.action_id);
60 } else if (state.model && state.id) {
61 // TODO handle context & domain ?
64 res_model: state.model,
66 type: 'ir.actions.act_window',
67 views: [[false, 'form']]
69 action_loaded = this.do_action(action);
70 } else if (state.sa) {
71 // load session action
74 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
76 return self.do_action(action);
79 } else if (state.client_action) {
81 var action = state.client_action;
82 if(_.isString(action)) {
88 this.ir_actions_client(action);
91 $.when(action_loaded || null).then(function() {
92 if (self.inner_viewmanager) {
93 self.inner_viewmanager.do_load_state(state, warm);
97 do_action: function(action, on_close) {
98 if (_.isNumber(action)) {
100 return self.rpc("/web/action/load", { action_id: action }, function(result) {
101 self.do_action(result.result, on_close);
105 console.error("No type for action", action);
108 var type = action.type.replace(/\./g,'_');
109 var popup = action.target === 'new';
110 var inline = action.target === 'inline';
111 action.flags = _.extend({
112 views_switcher : !popup && !inline,
113 search_view : !popup && !inline,
114 action_buttons : !popup && !inline,
115 sidebar : !popup && !inline,
116 pager : !popup && !inline,
117 display_title : !popup
118 }, action.flags || {});
119 if (!(type in this)) {
120 console.error("Action manager can't handle action of type " + action.type, action);
123 return this[type](action, on_close);
125 null_action: function() {
129 ir_actions_act_window: function (action, on_close) {
131 if (_(['base.module.upgrade', 'base.setup.installer'])
132 .contains(action.res_model)) {
133 var old_close = on_close;
134 on_close = function () {
135 instance.webclient.do_reload().then(old_close);
138 if (action.target === 'new') {
139 if (this.dialog == null) {
140 this.dialog = new instance.web.Dialog(this, { width: '80%' });
142 this.dialog.on_close.add(on_close);
144 this.dialog_viewmanager.destroy();
146 this.dialog.dialog_title = action.name;
147 this.dialog_viewmanager = new instance.web.ViewManagerAction(this, action);
148 this.dialog_viewmanager.appendTo(this.dialog.$element);
154 return this.getParent().do_action(action, function () {
155 instance.webclient.menu.open_menu(action.menu_id);
158 this.inner_action = action;
159 this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
160 this.inner_viewmanager.appendTo(this.$element);
161 this.inner_viewmanager.$element.addClass("oe_view_manager_global");
164 ir_actions_act_window_close: function (action, on_closed) {
165 if (!this.dialog && on_closed) {
170 ir_actions_server: function (action, on_closed) {
172 this.rpc('/web/action/run', {
173 action_id: action.id,
174 context: action.context || {}
175 }).then(function (action) {
176 self.do_action(action, on_closed)
179 ir_actions_client: function (action) {
182 var ClientWidget = instance.web.client_actions.get_object(action.tag);
183 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
185 ir_actions_report_xml: function(action, on_closed) {
188 self.rpc("/web/session/eval_domain_and_context", {
189 contexts: [action.context],
191 }).then(function(res) {
192 action = _.clone(action);
193 action.context = res.context;
194 self.session.get_file({
196 data: {action: JSON.stringify(action)},
197 complete: $.unblockUI,
199 if (!self.dialog && on_closed) {
204 error: instance.webclient.crashmanager.on_rpc_error
208 ir_actions_act_url: function (action) {
209 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
211 ir_ui_menu: function (action) {
212 this.getParent().do_action(action);
216 instance.web.ViewManager = instance.web.Widget.extend({
217 template: "ViewManager",
218 init: function(parent, dataset, views, flags) {
220 this.model = dataset ? dataset.model : undefined;
221 this.dataset = dataset;
222 this.searchview = null;
223 this.active_view = null;
224 this.views_src = _.map(views, function(x) {
225 if (x instanceof Array) {
226 var View = instance.web.views.get_object(x[1], true);
230 label: View ? View.prototype.display_name : (void 'nope')
237 this.flags = flags || {};
238 this.registry = instance.web.views;
239 this.views_history = [];
242 * @returns {jQuery.Deferred} initial view loading promise
247 this.$element.find('.oe_view_manager_switch a').click(function() {
248 self.on_mode_switch($(this).data('view-type'));
251 _.each(this.views_src, function(view) {
252 self.views[view.view_type] = $.extend({}, view, {
253 deferred : $.Deferred(),
256 $buttons : self.$element.find('.oe_view_manager_buttons'),
257 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
258 $pager : self.$element.find('.oe_view_manager_pager'),
259 action : self.action,
260 action_views_ids : views_ids
261 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
263 views_ids[view.view_type] = view.view_id;
265 if (this.flags.views_switcher === false) {
266 this.$element.find('.oe_view_manager_switch').hide();
268 // If no default view defined, switch to the first one in sequence
269 var default_view = this.flags.default_view || this.views_src[0].view_type;
270 return this.on_mode_switch(default_view);
273 * Asks the view manager to switch visualization mode.
275 * @param {String} view_type type of view to display
276 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
277 * @returns {jQuery.Deferred} new view loading promise
279 on_mode_switch: function(view_type, no_store, view_options) {
281 var view = this.views[view_type];
284 return $.Deferred().reject();
287 this.views_history.push(view_type);
289 this.active_view = view_type;
291 if (!view.controller) {
292 // Lazy loading of views
293 var controllerclass = this.registry.get_object(view_type);
294 var options = _.clone(view.options);
295 if (view_type === "form" && this.action) {
296 switch (this.action.target) {
299 options.initial_mode = 'edit';
303 var controller = new controllerclass(this, this.dataset, view.view_id, options);
304 if (view.embedded_view) {
305 controller.set_embedded_view(view.embedded_view);
307 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
308 controller.do_prev_view.add_last(this.on_prev_view);
309 var container = this.$element.find(".oe_view_manager_view_" + view_type);
310 view_promise = controller.appendTo(container);
311 this.views[view_type].controller = controller;
312 this.views[view_type].deferred.resolve(view_type);
313 $.when(view_promise).then(function() {
314 self.on_controller_inited(view_type, controller);
316 && self.flags.auto_search
317 && view.controller.searchable !== false) {
318 self.searchview.ready.then(self.searchview.do_search);
321 } else if (this.searchview
322 && self.flags.auto_search
323 && view.controller.searchable !== false) {
324 this.searchview.ready.then(this.searchview.do_search);
327 if (this.searchview) {
328 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
332 .find('.oe_view_manager_switch a').parent().removeClass('active');
334 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
335 .parent().addClass('active');
337 $.when(view_promise).then(function () {
338 _.each(_.keys(self.views), function(view_name) {
339 var controller = self.views[view_name].controller;
341 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
342 if (view_name === view_type) {
344 controller.do_show(view_options || {});
347 controller.do_hide();
352 self.$element.find('.oe_view_title_text:first').text(
353 self.display_title());
358 * Method used internally when a view asks to switch view. This method is meant
359 * to be extended by child classes to change the default behavior, which simply
360 * consist to switch to the asked view.
362 switch_view: function(view_type, no_store, options) {
363 return this.on_mode_switch(view_type, no_store, options);
366 * Returns to the view preceding the caller view in this manager's
367 * navigation history (the navigation history is appended to via
370 * @param {Object} [options]
371 * @param {Boolean} [options.created=false] resource was created
372 * @param {String} [options.default=null] view to switch to if no previous view
373 * @returns {$.Deferred} switching end signal
375 on_prev_view: function (options) {
376 options = options || {};
377 var current_view = this.views_history.pop();
378 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
379 if (options.created && current_view === 'form' && previous_view === 'list') {
380 // APR special case: "If creation mode from list (and only from a list),
381 // after saving, go to page view (don't come back in list)"
382 return this.on_mode_switch('form');
383 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
384 // APR special case: "If creation from dashboard, we have no previous view
385 return this.on_mode_switch('form');
387 return this.on_mode_switch(previous_view, true);
390 * Sets up the current viewmanager's search view.
392 * @param {Number|false} view_id the view to use or false for a default one
393 * @returns {jQuery.Deferred} search view startup deferred
395 setup_search_view: function(view_id, search_defaults) {
397 if (this.searchview) {
398 this.searchview.destroy();
400 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
402 this.searchview.on_search.add(this.do_searchview_search);
403 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
405 do_searchview_search: function(domains, contexts, groupbys) {
407 controller = this.views[this.active_view].controller,
408 action_context = this.action.context || {};
409 this.rpc('/web/session/eval_domain_and_context', {
410 domains: [this.action.domain || []].concat(domains || []),
411 contexts: [action_context].concat(contexts || []),
412 group_by_seq: groupbys || []
413 }, function (results) {
414 self.dataset._model = new instance.web.Model(
415 self.dataset.model, results.context, results.domain);
416 var groupby = results.group_by.length
418 : action_context.group_by;
419 if (_.isString(groupby)) {
422 controller.do_search(results.domain, results.context, groupby || []);
426 * Event launched when a controller has been inited.
428 * @param {String} view_type type of view
429 * @param {String} view the inited controller
431 on_controller_inited: function(view_type, view) {
434 * Called when one of the view want to execute an action
436 on_action: function(action) {
438 on_create: function() {
440 on_remove: function() {
442 on_edit: function() {
445 * Called by children view after executing an action
447 on_action_executed: function () {
449 display_title: function () {
450 var view = this.views[this.active_view];
453 return view.controller.fields_view.arch.attrs.string;
459 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
460 template:"ViewManagerAction",
462 * @constructs instance.web.ViewManagerAction
463 * @extends instance.web.ViewManager
465 * @param {instance.web.ActionManager} parent parent object/widget
466 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
468 init: function(parent, action) {
469 // dataset initialization will take the session from ``this``, so if we
470 // do not have it yet (and we don't, because we've not called our own
471 // ``_super()``) rpc requests will blow up.
472 var flags = action.flags || {};
473 if (!('auto_search' in flags)) {
474 flags.auto_search = action.auto_search !== false;
476 if (action.res_model == 'board.board' && action.view_mode === 'form') {
477 // Special case for Dashboards
479 views_switcher : false,
480 display_title : false,
484 action_buttons : false
487 this._super(parent, null, action.views, flags);
488 this.session = parent.session;
489 this.action = action;
490 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
492 dataset.ids.push(action.res_id);
495 this.dataset = dataset;
497 // setup storage for session-wise menu hiding
498 if (this.session.hidden_menutips) {
501 this.session.hidden_menutips = {}
504 * Initializes the ViewManagerAction: sets up the searchview (if the
505 * searchview is enabled in the manager's action flags), calls into the
506 * parent to initialize the primary view and (if the VMA has a searchview)
507 * launches an initial search after both views are done rendering.
512 search_defaults = {};
513 _.each(this.action.context, function (value, key) {
514 var match = /^search_default_(.*)$/.exec(key);
516 search_defaults[match[1]] = value;
520 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
522 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
524 var main_view_loaded = this._super();
526 var manager_ready = $.when(searchview_loaded, main_view_loaded);
528 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
530 if (this.action.help && !this.flags.low_profile) {
531 var Users = new instance.web.DataSet(self, 'res.users'),
532 $tips = this.$element.find('.oe_view_manager_menu_tips');
533 $tips.delegate('blockquote button', 'click', function() {
535 //noinspection FallthroughInSwitchStatementJS
536 switch ($this.attr('name')) {
538 Users.write(self.session.uid, {menu_tips:false});
540 $this.closest('blockquote').hide();
541 self.session.hidden_menutips[self.action.id] = true;
544 if (!(self.action.id in self.session.hidden_menutips)) {
545 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
547 if (!(user && user.id === self.session.uid)) {
550 $tips.find('blockquote').toggle(user.menu_tips);
555 return manager_ready;
557 on_debug_changed: function (evt) {
559 $sel = $(evt.currentTarget),
560 $option = $sel.find('option:selected'),
562 current_view = this.views[this.active_view].controller;
565 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
566 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
569 var ids = current_view.get_selected_ids();
570 if (ids.length === 1) {
571 this.dataset.call('perm_read', [ids]).then(function(result) {
572 var dialog = new instance.web.Dialog(this, {
573 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
575 }, QWeb.render('ViewManagerDebugViewLog', {
577 format : instance.web.format_value
582 case 'toggle_layout_outline':
583 current_view.rendering_engine.toggle_layout_debugging();
586 this.dataset.call_and_eval(
587 'fields_get', [false, {}], null, 1).then(function (fields) {
588 var $root = $('<dl>');
589 _(fields).each(function (attributes, name) {
590 $root.append($('<dt>').append($('<h4>').text(name)));
591 var $attrs = $('<dl>').appendTo(
592 $('<dd>').appendTo($root));
593 _(attributes).each(function (def, name) {
594 if (def instanceof Object) {
595 def = JSON.stringify(def);
598 .append($('<dt>').text(name))
599 .append($('<dd style="white-space: pre-wrap;">').text(def));
602 new instance.web.Dialog(self, {
603 title: _.str.sprintf(_t("Model %s fields"),
605 width: '95%'}, $root).open();
609 if (current_view.fields_view && current_view.fields_view.arch) {
610 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
613 this.do_warn(_t("Manage Views"),
614 _t("Could not find current view declaration"));
617 case 'edit_workflow':
618 return this.do_action({
619 res_model : 'workflow',
620 domain : [['osv', '=', this.dataset.model]],
621 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
622 type : 'ir.actions.act_window',
628 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
630 case 'manage_filters':
632 res_model: 'ir.filters',
633 views: [[false, 'list'], [false, 'form']],
634 type: 'ir.actions.act_window',
636 search_default_my_filters: true,
637 search_default_model_id: this.dataset.model
643 console.log("No debug handler for ", val);
646 evt.currentTarget.selectedIndex = 0;
648 do_edit_resource: function(model, id, action) {
649 var action = _.extend({
652 type : 'ir.actions.act_window',
655 views : [[false, 'form']],
658 action_buttons : true,
660 resize_textareas : true
664 this.do_action(action);
666 on_mode_switch: function (view_type, no_store, options) {
669 return $.when(this._super.apply(this, arguments)).then(function () {
670 var controller = self.views[self.active_view].controller,
671 fvg = controller.fields_view,
672 view_id = (fvg && fvg.view_id) || '--';
673 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
677 if (!self.action.name && fvg) {
678 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
683 do_push_state: function(state) {
684 if (this.getParent() && this.getParent().do_push_state) {
685 state["view_type"] = this.active_view;
686 this.getParent().do_push_state(state);
689 do_load_state: function(state, warm) {
692 if (state.view_type && state.view_type !== this.active_view) {
694 this.views[this.active_view].deferred.pipe(function() {
695 return self.on_mode_switch(state.view_type, true);
700 $.when(defs).then(function() {
701 self.views[self.active_view].controller.do_load_state(state, warm);
704 display_title: function () {
705 return this.action.name;
709 instance.web.Sidebar = instance.web.Widget.extend({
710 init: function(parent) {
713 var view = this.getParent();
715 { 'name' : 'print', 'label' : _t('Print'), },
716 { 'name' : 'files', 'label' : _t('Attachment'), },
717 { 'name' : 'other', 'label' : _t('More'), }
724 if (this.session.uid === 1) {
725 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
726 this.items.other.push(item);
728 this.fileupload_id = _.uniqueId('oe_fileupload');
729 $(window).on(this.fileupload_id, function() {
730 var args = [].slice.call(arguments).slice(1);
731 if (args[0] && args[0].error) {
732 alert(args[0].error);
734 self.do_attachement_update(self.dataset, self.model_id);
743 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
744 var section = $(this).data('section');
745 var index = $(this).data('index');
746 var item = self.items[section][index];
748 item.callback.apply(self, [item]);
749 } else if (item.action) {
750 self.on_item_action_clicked(item);
751 } else if (item.url) {
754 event.preventDefault();
759 self.$element.html(QWeb.render('Sidebar', {widget: self}));
761 // Hides Sidebar sections when item list is empty
762 this.$('.oe_form_dropdown_section').each(function() {
763 $(this).toggle(!!$(this).find('li').length);
767 * For each item added to the section:
770 * will be used as the item's name in the sidebar, can be html
773 * descriptor for the action which will be executed, ``action`` and
774 * ``callback`` should be exclusive
777 * function to call when the item is clicked in the sidebar, called
778 * with the item descriptor as its first argument (so information
779 * can be stored as additional keys on the object passed to
782 * ``classname`` (optional)
783 * ``@class`` set on the sidebar serialization of the item
785 * ``title`` (optional)
786 * will be set as the item's ``@title`` (tooltip)
788 * @param {String} section_code
789 * @param {Array<{label, action | callback[, classname][, title]}>} items
791 add_items: function(section_code, items) {
794 this.items[section_code].push.apply(this.items[section_code],items);
798 add_toolbar: function(toolbar) {
800 _.each(['print','action','relate'], function(type) {
801 var items = toolbar[type];
803 for (var i = 0; i < items.length; i++) {
805 label: items[i]['name'],
807 classname: 'oe_sidebar_' + type
810 self.add_items(type=='print' ? 'print' : 'other', items);
814 on_item_action_clicked: function(item) {
816 self.getParent().sidebar_context().then(function (context) {
817 var ids = self.getParent().get_selected_ids();
818 if (ids.length == 0) {
819 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
822 var additional_context = _.extend({
825 active_model: self.getParent().dataset.model
827 self.rpc("/web/action/load", {
828 action_id: item.action.id,
829 context: additional_context
830 }, function(result) {
831 result.result.context = _.extend(result.result.context || {},
833 result.result.flags = result.result.flags || {};
834 result.result.flags.new_window = true;
835 self.do_action(result.result, function () {
837 self.getParent().reload();
842 do_attachement_update: function(dataset, model_id) {
843 this.dataset = dataset;
844 this.model_id = model_id;
846 this.on_attachments_loaded([]);
848 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
849 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
850 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
853 on_attachments_loaded: function(attachments) {
856 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
857 _.each(attachments,function(a) {
859 if(a.type === "binary") {
860 a.url = prefix + a.id + '&t=' + (new Date().getTime());
863 self.items['files'] = attachments;
865 this.$('.oe_sidebar_add_attachment .oe-binary-file').change(this.on_attachment_changed);
866 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
868 on_attachment_changed: function(e) {
869 var $e = $(e.target);
870 if ($e.val() !== '') {
871 this.$element.find('form.oe-binary-form').submit();
872 $e.parent().find('input[type=file]').prop('disabled', true);
873 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
874 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
878 on_attachment_delete: function(e) {
883 var $e = $(e.currentTarget);
884 if (confirm(_t("Do you really want to delete this attachment ?"))) {
885 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
886 self.do_attachement_update(self.dataset, self.model_id);
892 instance.web.TranslateDialog = instance.web.Dialog.extend({
893 dialog_title: {toString: function () { return _t("Translations"); }},
894 init: function(view) {
895 // TODO fme: should add the language to fields_view_get because between the fields view get
896 // and the moment the user opens the translation dialog, the user language could have been changed
897 this.view_language = view.session.user_context.lang;
898 this['on_button_' + _t("Save")] = this.on_btn_save;
899 this['on_button_' + _t("Close")] = this.on_btn_close;
905 this.view_type = view.fields_view.type || '';
906 this.$fields_form = null;
907 this.$view_form = null;
908 this.$sidebar_form = null;
909 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
910 this.languages = null;
911 this.languages_loaded = $.Deferred();
912 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
913 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
918 $.when(this.languages_loaded).then(function() {
919 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
920 self.$fields_form = self.$element.find('.oe_translation_form');
921 self.$fields_form.find('.oe_trad_field').change(function() {
922 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
927 on_languages_loaded: function(langs) {
928 this.languages = langs;
929 this.languages_loaded.resolve();
931 do_load_fields_values: function(callback) {
934 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
935 _.each(self.languages, function(lg) {
936 var deff = $.Deferred();
938 var callback = function(values) {
939 _.each(self.translatable_fields_keys, function(f) {
940 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
944 if (lg.code === self.view_language) {
946 _.each(self.translatable_fields_keys, function(field) {
947 values[field] = self.view.fields[field].get_value();
951 self.rpc('/web/dataset/get', {
952 model: self.view.dataset.model,
953 ids: [self.view.datarecord.id],
954 fields: self.translatable_fields_keys,
955 context: self.view.dataset.get_context({
960 $.when.apply(null, deffered).then(callback);
962 open: function(field) {
965 $.when(this.languages_loaded).then(function() {
966 if (self.view.translatable_fields && self.view.translatable_fields.length) {
967 self.do_load_fields_values(function() {
970 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
971 self.$element.scrollTo($field_input);
972 $field_input.focus();
980 on_btn_save: function() {
983 trads_mutex = new $.Mutex();
984 self.$fields_form.find('.oe_trad_field.touched').each(function() {
985 var field = $(this).attr('name').split('-');
986 if (!trads[field[0]]) {
987 trads[field[0]] = {};
989 trads[field[0]][field[1]] = $(this).val();
991 _.each(trads, function(data, code) {
992 if (code === self.view_language) {
993 _.each(data, function(value, field) {
994 self.view.fields[field].set_value(value);
997 trads_mutex.exec(function() {
998 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1003 on_btn_close: function() {
1008 instance.web.View = instance.web.Widget.extend({
1009 template: "EmptyComponent",
1010 // name displayed in view switchers
1013 * Define a view type for each view to allow automatic call to fields_view_get.
1015 view_type: undefined,
1016 init: function(parent, dataset, view_id, options) {
1017 this._super(parent);
1018 this.dataset = dataset;
1019 this.view_id = view_id;
1020 this.set_default_options(options);
1023 return this.load_view();
1025 load_view: function() {
1026 if (this.embedded_view) {
1027 var def = $.Deferred();
1029 $.async_when().then(function() {def.resolve(self.embedded_view);});
1030 return def.pipe(this.on_loaded);
1032 var context = new instance.web.CompoundContext(this.dataset.get_context());
1033 if (! this.view_type)
1034 console.warn("view_type is not defined", this);
1035 return this.rpc("/web/view/load", {
1036 "model": this.dataset.model,
1037 "view_id": this.view_id,
1038 "view_type": this.view_type,
1039 toolbar: !!this.options.$sidebar,
1041 }).pipe(this.on_loaded);
1045 * Called after a successful call to fields_view_get.
1046 * Must return a promise.
1048 on_loaded: function(fields_view_get) {
1050 set_default_options: function(options) {
1051 this.options = options || {};
1052 _.defaults(this.options, {
1053 // All possible views options should be defaulted here
1057 action_views_ids: {}
1060 open_translate_dialog: function(field) {
1061 if (!this.translate_dialog) {
1062 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1064 this.translate_dialog.open(field);
1067 * Fetches and executes the action identified by ``action_data``.
1069 * @param {Object} action_data the action descriptor data
1070 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1071 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1072 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1073 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1074 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1075 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1076 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1078 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1080 var result_handler = function () {
1081 if (on_closed) { on_closed.apply(null, arguments); }
1082 if (self.getParent() && self.getParent().on_action_executed) {
1083 return self.getParent().on_action_executed.apply(null, arguments);
1086 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1088 var handler = function (r) {
1089 var action = r.result;
1090 if (action && action.constructor == Object) {
1091 var ncontext = new instance.web.CompoundContext(context);
1094 active_id: record_id,
1095 active_ids: [record_id],
1096 active_model: dataset.model
1099 ncontext.add(action.context || {});
1100 return self.rpc('/web/session/eval_domain_and_context', {
1101 contexts: [ncontext],
1103 }).pipe(function (results) {
1104 action.context = results.context;
1105 /* niv: previously we were overriding once more with action_data.context,
1106 * I assumed this was not a correct behavior and removed it
1108 return self.do_action(action, result_handler);
1111 return result_handler();
1115 if (action_data.special) {
1116 return handler({result: {"type":"ir.actions.act_window_close"}});
1117 } else if (action_data.type=="object") {
1118 var args = [[record_id]], additional_args = [];
1119 if (action_data.args) {
1121 // Warning: quotes and double quotes problem due to json and xml clash
1122 // Maybe we should force escaping in xml or do a better parse of the args array
1123 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1124 args = args.concat(additional_args);
1126 console.error("Could not JSON.parse arguments", action_data.args);
1130 return dataset.call_button(action_data.name, args, handler);
1131 } else if (action_data.type=="action") {
1132 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1134 return dataset.exec_workflow(record_id, action_data.name, handler);
1138 * Directly set a view to use instead of calling fields_view_get. This method must
1139 * be called before start(). When an embedded view is set, underlying implementations
1140 * of instance.web.View must use the provided view instead of any other one.
1142 * @param embedded_view A view.
1144 set_embedded_view: function(embedded_view) {
1145 this.embedded_view = embedded_view;
1147 do_show: function () {
1148 this.$element.show();
1150 do_hide: function () {
1151 this.$element.hide();
1153 do_push_state: function(state) {
1154 if (this.getParent() && this.getParent().do_push_state) {
1155 this.getParent().do_push_state(state);
1158 do_load_state: function(state, warm) {
1161 * Switches to a specific view type
1163 * @param {String} view view type to switch to
1165 do_switch_view: function(view) {
1168 * Cancels the switch to the current view, switches to the previous one
1170 * @param {Object} [options]
1171 * @param {Boolean} [options.created=false] resource was created
1172 * @param {String} [options.default=null] view to switch to if no previous view
1174 do_prev_view: function (options) {
1176 do_search: function(view) {
1178 on_sidebar_import: function() {
1179 var import_view = new instance.web.DataImport(this, this.dataset);
1180 import_view.start();
1182 on_sidebar_export: function() {
1183 var export_view = new instance.web.DataExport(this, this.dataset);
1184 export_view.start();
1186 on_sidebar_translate: function() {
1187 return this.do_action({
1188 res_model : 'ir.translation',
1189 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1190 views: [[false, 'list'], [false, 'form']],
1191 type : 'ir.actions.act_window',
1196 sidebar_context: function () {
1200 * Asks the view to reload itself, if the reloading is asynchronous should
1201 * return a {$.Deferred} indicating when the reloading is done.
1203 reload: function () {
1208 instance.web.xml_to_json = function(node) {
1209 switch (node.nodeType) {
1215 var attrs = $(node).getAttributes();
1216 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1219 attrs[key] = JSON.parse(attrs[key]);
1224 tag: node.tagName.toLowerCase(),
1226 children: _.map(node.childNodes, instance.web.xml_to_json)
1230 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1231 // For debugging purpose, this function will convert a json node back to xml
1232 // Maybe useful for xml view editor
1233 indent = indent || 0;
1234 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1235 r = sindent + '<' + node.tag,
1236 cr = human_readable ? '\n' : '';
1238 if (typeof(node) === 'string') {
1239 return sindent + node;
1240 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1241 throw("Node a json node");
1243 for (var attr in node.attrs) {
1244 var vattr = node.attrs[attr];
1245 if (typeof(vattr) !== 'string') {
1247 vattr = JSON.stringify(vattr);
1249 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1250 if (human_readable) {
1251 vattr = vattr.replace(/"/g, "'");
1253 r += ' ' + attr + '="' + vattr + '"';
1255 if (node.children && node.children.length) {
1258 for (var i = 0, ii = node.children.length; i < ii; i++) {
1259 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1261 r += childs.join(cr);
1262 r += cr + sindent + '</' + node.tag + '>';
1268 instance.web.xml_to_str = function(node) {
1269 if (window.ActiveXObject) {
1272 return (new XMLSerializer()).serializeToString(node);
1275 instance.web.str_to_xml = function(s) {
1276 if (window.DOMParser) {
1277 var dp = new DOMParser();
1278 var r = dp.parseFromString(s, "text/xml");
1279 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1280 throw new Error("Could not parse string to xml");
1286 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1288 throw new Error("Could not find a DOM Parser: " + e.message);
1291 xDoc.preserveWhiteSpace = true;
1297 * Registry for all the main views
1299 instance.web.views = new instance.web.Registry();
1303 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: