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;
19 this._super.apply(this, arguments);
20 this.breadcrumb = new instance.web.BreadCrumb(this);
22 dialog_stop: function () {
24 this.dialog_viewmanager.destroy();
25 this.dialog_viewmanager = null;
26 this.dialog.destroy();
30 content_stop: function () {
31 // TODO: problem with bread crumb here. Check if those references are needed
32 if (this.inner_viewmanager) {
33 this.inner_viewmanager.destroy();
34 this.inner_viewmanager = null;
36 if (this.client_widget) {
37 this.client_widget.destroy();
38 this.client_widget = null;
41 do_push_state: function(state) {
42 if (this.getParent() && this.getParent().do_push_state) {
43 if (this.inner_action) {
44 state['title'] = this.inner_action.name;
45 state['model'] = this.inner_action.res_model;
46 if (this.inner_action.id) {
47 state['action_id'] = this.inner_action.id;
50 this.getParent().do_push_state(state);
53 do_load_state: function(state, warm) {
56 if (state.action_id) {
57 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
60 action_loaded = this.do_action(state.action_id);
61 instance.webclient.menu.has_been_loaded.then(function() {
62 instance.webclient.menu.open_action(state.action_id);
65 } else if (state.model && state.id) {
66 // TODO handle context & domain ?
69 res_model: state.model,
71 type: 'ir.actions.act_window',
72 views: [[false, 'form']]
74 action_loaded = this.do_action(action);
75 } else if (state.sa) {
76 // load session action
79 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
81 return self.do_action(action);
84 } else if (state.client_action) {
86 var action = state.client_action;
87 if(_.isString(action)) {
93 this.ir_actions_client(action);
96 $.when(action_loaded || null).then(function() {
97 if (self.inner_viewmanager) {
98 self.inner_viewmanager.do_load_state(state, warm);
102 do_action: function(action, on_close) {
103 if (_.isNumber(action)) {
105 return self.rpc("/web/action/load", { action_id: action }, function(result) {
106 self.do_action(result.result, on_close);
110 console.error("No type for action", action);
113 var type = action.type.replace(/\./g,'_');
114 var popup = action.target === 'new';
115 var inline = action.target === 'inline';
116 action.flags = _.extend({
117 views_switcher : !popup && !inline,
118 search_view : !popup && !inline,
119 action_buttons : !popup && !inline,
120 sidebar : !popup && !inline,
121 pager : !popup && !inline,
122 display_title : !popup
123 }, action.flags || {});
124 if (!(type in this)) {
125 console.error("Action manager can't handle action of type " + action.type, action);
128 return this[type](action, on_close);
130 null_action: function() {
134 ir_actions_act_window: function (action, on_close) {
136 if (_(['base.module.upgrade', 'base.setup.installer'])
137 .contains(action.res_model)) {
138 var old_close = on_close;
139 on_close = function () {
140 instance.webclient.do_reload().then(old_close);
143 if (action.target === 'new') {
144 if (this.dialog === null) {
145 this.dialog = new instance.web.Dialog(this, { width: '80%' });
147 this.dialog.on_close.add(on_close);
149 this.dialog_viewmanager.destroy();
151 this.dialog.dialog_title = action.name;
152 this.dialog_viewmanager = new instance.web.ViewManagerAction(this.dialog, action);
153 this.dialog_viewmanager.appendTo(this.dialog.$element);
154 this.dialog_viewmanager.$element.addClass("oe_view_manager_" + action.target);
158 //this.content_stop();
159 this.breadcrumb.hide_items();
161 return this.getParent().do_action(action, function () {
162 instance.webclient.menu.open_menu(action.menu_id);
165 this.inner_action = action;
166 var inner_viewmanager = this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
167 this.inner_viewmanager.appendTo(this.$element);
168 this.inner_viewmanager.$element.addClass("oe_view_manager_" + action.target);
169 this.breadcrumb.push_actionmanager(inner_viewmanager);
172 ir_actions_act_window_close: function (action, on_closed) {
173 if (!this.dialog && on_closed) {
178 ir_actions_server: function (action, on_closed) {
180 this.rpc('/web/action/run', {
181 action_id: action.id,
182 context: action.context || {}
183 }).then(function (action) {
184 self.do_action(action, on_closed)
187 ir_actions_client: function (action) {
188 //this.content_stop();
190 this.breadcrumb.hide_items();
191 var ClientWidget = instance.web.client_actions.get_object(action.tag);
192 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
193 this.breadcrumb.push({
194 widget: this.client_widget,
198 ir_actions_report_xml: function(action, on_closed) {
201 self.rpc("/web/session/eval_domain_and_context", {
202 contexts: [action.context],
204 }).then(function(res) {
205 action = _.clone(action);
206 action.context = res.context;
207 self.session.get_file({
209 data: {action: JSON.stringify(action)},
210 complete: $.unblockUI,
212 if (!self.dialog && on_closed) {
217 error: instance.webclient.crashmanager.on_rpc_error
221 ir_actions_act_url: function (action) {
222 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
224 ir_ui_menu: function (action) {
225 this.getParent().do_action(action);
229 instance.web.BreadCrumb = instance.web.CallbackEnabled.extend({
230 init: function(parent) {
232 this.action_manager = parent;
234 this.action_manager.$element.on('click', '.oe_breadcrumb_item', this.on_item_clicked);
236 push: function(item) {
238 item.show = function() {
239 item.widget.$element.show();
243 item.hide = function() {
244 item.widget.$element.hide();
248 item.destroy = function() {
249 item.widget.destroy();
252 if (!item.get_title) {
253 item.get_title = function() {
254 return item.title || item.widget.get('title');
257 this.items.push(item);
259 push_actionmanager: function(am) {
261 var bookmarked_view = am.active_view;
266 am.on_mode_switch(current_view);
269 am.on_mode_switch.add_first(function(mode) {
270 if (mode === 'form' && !am.views[mode].controller) {
275 inner_viewmanager.on_mode_switch('form');
278 get_title: function() {
279 var form = inner_viewmanager.views['form'].controller;
281 return form.get('title');
289 this.remove_item(this.items.length - 1);
290 this.select_item(this.items.length - 1);
292 get_title: function() {
293 return QWeb.render('BreadCrumb', { widget: this });
295 hide_items: function() {
296 _.each(this.items, function(i) {
300 on_item_clicked: function(ev) {
301 var $e = $(ev.target);
302 var index = $e.data('index');
303 this.select_item(index);
305 select_item: function(index) {
306 for (var i = index + 1; i < this.items.length; i += 1) {
309 var item = this.items[index];
313 console.warn("Breadcrumb: Can't select item at index", index);
316 remove_item: function(index) {
317 var item = this.items.splice(index, 1)[0];
321 console.warn("Breadcrumb: Can't remove item at index", index);
325 while (this.items.length) {
331 instance.web.ViewManager = instance.web.Widget.extend({
332 template: "ViewManager",
333 init: function(parent, dataset, views, flags) {
335 this.model = dataset ? dataset.model : undefined;
336 this.dataset = dataset;
337 this.searchview = null;
338 this.active_view = null;
339 this.views_src = _.map(views, function(x) {
340 if (x instanceof Array) {
341 var View = instance.web.views.get_object(x[1], true);
345 label: View ? View.prototype.display_name : (void 'nope')
352 this.flags = flags || {};
353 this.registry = instance.web.views;
354 this.views_history = [];
357 * @returns {jQuery.Deferred} initial view loading promise
362 this.$element.find('.oe_view_manager_switch a').click(function() {
363 self.on_mode_switch($(this).data('view-type'));
366 _.each(this.views_src, function(view) {
367 self.views[view.view_type] = $.extend({}, view, {
368 deferred : $.Deferred(),
371 $buttons : self.$element.find('.oe_view_manager_buttons'),
372 $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
373 $pager : self.$element.find('.oe_view_manager_pager'),
374 action : self.action,
375 action_views_ids : views_ids
376 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
378 views_ids[view.view_type] = view.view_id;
380 if (this.flags.views_switcher === false) {
381 this.$element.find('.oe_view_manager_switch').hide();
383 this.on('change:title', this, function() {
384 var breadcrumb = self.getParent().breadcrumb;
386 self.$element.find('.oe_view_title_text:first').html(breadcrumb.get_title());
388 self.$element.find('.oe_view_title_text:first').text(self.get('title'));
391 // If no default view defined, switch to the first one in sequence
392 var default_view = this.flags.default_view || this.views_src[0].view_type;
393 return this.on_mode_switch(default_view);
396 * Asks the view manager to switch visualization mode.
398 * @param {String} view_type type of view to display
399 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
400 * @returns {jQuery.Deferred} new view loading promise
402 on_mode_switch: function(view_type, no_store, view_options) {
404 var view = this.views[view_type];
407 return $.Deferred().reject();
410 this.views_history.push(view_type);
412 this.active_view = view_type;
414 if (!view.controller) {
415 // Lazy loading of views
416 var controllerclass = this.registry.get_object(view_type);
417 var options = _.clone(view.options);
418 if (view_type === "form" && this.action) {
419 switch (this.action.target) {
422 options.initial_mode = 'edit';
426 var controller = new controllerclass(this, this.dataset, view.view_id, options);
427 controller.on("change:title", this, function() {
428 if (self.active_view === view_type) {
429 self.set({ 'title' : controller.get('title') });
432 if (view.embedded_view) {
433 controller.set_embedded_view(view.embedded_view);
435 controller.do_switch_view.add_last(_.bind(this.switch_view, this));
437 controller.do_prev_view.add_last(this.on_prev_view);
438 var container = this.$element.find(".oe_view_manager_view_" + view_type);
439 view_promise = controller.appendTo(container);
440 this.views[view_type].controller = controller;
441 this.views[view_type].deferred.resolve(view_type);
442 $.when(view_promise).then(function() {
443 self.on_controller_inited(view_type, controller);
445 && self.flags.auto_search
446 && view.controller.searchable !== false) {
447 self.searchview.ready.then(self.searchview.do_search);
450 } else if (this.searchview
451 && self.flags.auto_search
452 && view.controller.searchable !== false) {
453 this.searchview.ready.then(this.searchview.do_search);
456 if (this.searchview) {
457 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
461 .find('.oe_view_manager_switch a').parent().removeClass('active');
463 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
464 .parent().addClass('active');
466 $.when(view_promise).then(function () {
467 _.each(_.keys(self.views), function(view_name) {
468 var controller = self.views[view_name].controller;
470 var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
471 if (view_name === view_type) {
473 controller.do_show(view_options || {});
476 controller.do_hide();
484 * Method used internally when a view asks to switch view. This method is meant
485 * to be extended by child classes to change the default behavior, which simply
486 * consist to switch to the asked view.
488 switch_view: function(view_type, no_store, options) {
489 return this.on_mode_switch(view_type, no_store, options);
492 * Returns to the view preceding the caller view in this manager's
493 * navigation history (the navigation history is appended to via
496 * @param {Object} [options]
497 * @param {Boolean} [options.created=false] resource was created
498 * @param {String} [options.default=null] view to switch to if no previous view
499 * @returns {$.Deferred} switching end signal
501 on_prev_view: function (options) {
502 options = options || {};
503 var current_view = this.views_history.pop();
504 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
505 if (options.created && current_view === 'form' && previous_view === 'list') {
506 // APR special case: "If creation mode from list (and only from a list),
507 // after saving, go to page view (don't come back in list)"
508 return this.on_mode_switch('form');
509 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
510 // APR special case: "If creation from dashboard, we have no previous view
511 return this.on_mode_switch('form');
513 return this.on_mode_switch(previous_view, true);
516 * Sets up the current viewmanager's search view.
518 * @param {Number|false} view_id the view to use or false for a default one
519 * @returns {jQuery.Deferred} search view startup deferred
521 setup_search_view: function(view_id, search_defaults) {
523 if (this.searchview) {
524 this.searchview.destroy();
526 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
528 this.searchview.on_search.add(this.do_searchview_search);
529 return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
531 do_searchview_search: function(domains, contexts, groupbys) {
533 controller = this.views[this.active_view].controller,
534 action_context = this.action.context || {};
535 this.rpc('/web/session/eval_domain_and_context', {
536 domains: [this.action.domain || []].concat(domains || []),
537 contexts: [action_context].concat(contexts || []),
538 group_by_seq: groupbys || []
539 }, function (results) {
540 self.dataset._model = new instance.web.Model(
541 self.dataset.model, results.context, results.domain);
542 var groupby = results.group_by.length
544 : action_context.group_by;
545 if (_.isString(groupby)) {
548 controller.do_search(results.domain, results.context, groupby || []);
552 * Event launched when a controller has been inited.
554 * @param {String} view_type type of view
555 * @param {String} view the inited controller
557 on_controller_inited: function(view_type, view) {
560 * Called when one of the view want to execute an action
562 on_action: function(action) {
564 on_create: function() {
566 on_remove: function() {
568 on_edit: function() {
571 * Called by children view after executing an action
573 on_action_executed: function () {
577 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
578 template:"ViewManagerAction",
580 * @constructs instance.web.ViewManagerAction
581 * @extends instance.web.ViewManager
583 * @param {instance.web.ActionManager} parent parent object/widget
584 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
586 init: function(parent, action) {
587 // dataset initialization will take the session from ``this``, so if we
588 // do not have it yet (and we don't, because we've not called our own
589 // ``_super()``) rpc requests will blow up.
590 var flags = action.flags || {};
591 if (!('auto_search' in flags)) {
592 flags.auto_search = action.auto_search !== false;
594 if (action.res_model == 'board.board' && action.view_mode === 'form') {
595 // Special case for Dashboards
597 views_switcher : false,
598 display_title : false,
602 action_buttons : false
605 this._super(parent, null, action.views, flags);
606 this.session = parent.session;
607 this.action = action;
608 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
610 dataset.ids.push(action.res_id);
613 this.dataset = dataset;
615 // setup storage for session-wise menu hiding
616 if (this.session.hidden_menutips) {
619 this.session.hidden_menutips = {};
622 * Initializes the ViewManagerAction: sets up the searchview (if the
623 * searchview is enabled in the manager's action flags), calls into the
624 * parent to initialize the primary view and (if the VMA has a searchview)
625 * launches an initial search after both views are done rendering.
630 search_defaults = {};
631 _.each(this.action.context, function (value, key) {
632 var match = /^search_default_(.*)$/.exec(key);
634 search_defaults[match[1]] = value;
638 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
640 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
642 var main_view_loaded = this._super();
644 var manager_ready = $.when(searchview_loaded, main_view_loaded);
646 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
648 if (this.action.help && !this.flags.low_profile) {
649 var Users = new instance.web.DataSet(self, 'res.users'),
650 $tips = this.$element.find('.oe_view_manager_menu_tips');
651 $tips.delegate('blockquote button', 'click', function() {
653 //noinspection FallthroughInSwitchStatementJS
654 switch ($this.attr('name')) {
656 Users.write(self.session.uid, {menu_tips:false});
658 $this.closest('blockquote').hide();
659 self.session.hidden_menutips[self.action.id] = true;
662 if (!(self.action.id in self.session.hidden_menutips)) {
663 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
665 if (!(user && user.id === self.session.uid)) {
668 $tips.find('blockquote').toggle(user.menu_tips);
673 return manager_ready;
675 on_debug_changed: function (evt) {
677 $sel = $(evt.currentTarget),
678 $option = $sel.find('option:selected'),
680 current_view = this.views[this.active_view].controller;
683 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
684 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
687 var ids = current_view.get_selected_ids();
688 if (ids.length === 1) {
689 this.dataset.call('perm_read', [ids]).then(function(result) {
690 var dialog = new instance.web.Dialog(this, {
691 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
693 }, QWeb.render('ViewManagerDebugViewLog', {
695 format : instance.web.format_value
700 case 'toggle_layout_outline':
701 current_view.rendering_engine.toggle_layout_debugging();
704 this.dataset.call_and_eval(
705 'fields_get', [false, {}], null, 1).then(function (fields) {
706 var $root = $('<dl>');
707 _(fields).each(function (attributes, name) {
708 $root.append($('<dt>').append($('<h4>').text(name)));
709 var $attrs = $('<dl>').appendTo(
710 $('<dd>').appendTo($root));
711 _(attributes).each(function (def, name) {
712 if (def instanceof Object) {
713 def = JSON.stringify(def);
716 .append($('<dt>').text(name))
717 .append($('<dd style="white-space: pre-wrap;">').text(def));
720 new instance.web.Dialog(self, {
721 title: _.str.sprintf(_t("Model %s fields"),
723 width: '95%'}, $root).open();
727 if (current_view.fields_view && current_view.fields_view.arch) {
728 var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
731 this.do_warn(_t("Manage Views"),
732 _t("Could not find current view declaration"));
735 case 'edit_workflow':
736 return this.do_action({
737 res_model : 'workflow',
738 domain : [['osv', '=', this.dataset.model]],
739 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
740 type : 'ir.actions.act_window',
746 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
748 case 'manage_filters':
750 res_model: 'ir.filters',
751 views: [[false, 'list'], [false, 'form']],
752 type: 'ir.actions.act_window',
754 search_default_my_filters: true,
755 search_default_model_id: this.dataset.model
761 console.log("No debug handler for ", val);
764 evt.currentTarget.selectedIndex = 0;
766 do_edit_resource: function(model, id, action) {
767 var action = _.extend({
770 type : 'ir.actions.act_window',
773 views : [[false, 'form']],
776 action_buttons : true,
778 resize_textareas : true
782 this.do_action(action);
784 on_mode_switch: function (view_type, no_store, options) {
787 return $.when(this._super.apply(this, arguments)).then(function () {
788 var controller = self.views[self.active_view].controller,
789 fvg = controller.fields_view,
790 view_id = (fvg && fvg.view_id) || '--';
791 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
795 if (!self.action.name && fvg) {
796 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
801 do_push_state: function(state) {
802 if (this.getParent() && this.getParent().do_push_state) {
803 state["view_type"] = this.active_view;
804 this.getParent().do_push_state(state);
807 do_load_state: function(state, warm) {
810 if (state.view_type && state.view_type !== this.active_view) {
812 this.views[this.active_view].deferred.pipe(function() {
813 return self.on_mode_switch(state.view_type, true);
818 $.when(defs).then(function() {
819 self.views[self.active_view].controller.do_load_state(state, warm);
822 set_title: function (title) {
823 this.getParent().breadcrumb.update();
827 instance.web.Sidebar = instance.web.Widget.extend({
828 init: function(parent) {
831 var view = this.getParent();
833 { 'name' : 'print', 'label' : _t('Print'), },
834 { 'name' : 'files', 'label' : _t('Attachment'), },
835 { 'name' : 'other', 'label' : _t('More'), }
842 if (this.session.uid === 1) {
843 var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
844 this.items.other.push(item);
846 this.fileupload_id = _.uniqueId('oe_fileupload');
847 $(window).on(this.fileupload_id, function() {
848 var args = [].slice.call(arguments).slice(1);
849 if (args[0] && args[0].error) {
850 alert(args[0].error);
852 self.do_attachement_update(self.dataset, self.model_id);
861 this.$element.on('click','.oe_dropdown_menu li a', function(event) {
862 var section = $(this).data('section');
863 var index = $(this).data('index');
864 var item = self.items[section][index];
866 item.callback.apply(self, [item]);
867 } else if (item.action) {
868 self.on_item_action_clicked(item);
869 } else if (item.url) {
872 event.preventDefault();
877 self.$element.html(QWeb.render('Sidebar', {widget: self}));
879 // Hides Sidebar sections when item list is empty
880 this.$('.oe_form_dropdown_section').each(function() {
881 $(this).toggle(!!$(this).find('li').length);
885 * For each item added to the section:
888 * will be used as the item's name in the sidebar, can be html
891 * descriptor for the action which will be executed, ``action`` and
892 * ``callback`` should be exclusive
895 * function to call when the item is clicked in the sidebar, called
896 * with the item descriptor as its first argument (so information
897 * can be stored as additional keys on the object passed to
900 * ``classname`` (optional)
901 * ``@class`` set on the sidebar serialization of the item
903 * ``title`` (optional)
904 * will be set as the item's ``@title`` (tooltip)
906 * @param {String} section_code
907 * @param {Array<{label, action | callback[, classname][, title]}>} items
909 add_items: function(section_code, items) {
912 this.items[section_code].push.apply(this.items[section_code],items);
916 add_toolbar: function(toolbar) {
918 _.each(['print','action','relate'], function(type) {
919 var items = toolbar[type];
921 for (var i = 0; i < items.length; i++) {
923 label: items[i]['name'],
925 classname: 'oe_sidebar_' + type
928 self.add_items(type=='print' ? 'print' : 'other', items);
932 on_item_action_clicked: function(item) {
934 self.getParent().sidebar_context().then(function (context) {
935 var ids = self.getParent().get_selected_ids();
936 if (ids.length == 0) {
937 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
940 var additional_context = _.extend({
943 active_model: self.getParent().dataset.model
945 self.rpc("/web/action/load", {
946 action_id: item.action.id,
947 context: additional_context
948 }, function(result) {
949 result.result.context = _.extend(result.result.context || {},
951 result.result.flags = result.result.flags || {};
952 result.result.flags.new_window = true;
953 self.do_action(result.result, function () {
955 self.getParent().reload();
960 do_attachement_update: function(dataset, model_id) {
961 this.dataset = dataset;
962 this.model_id = model_id;
964 this.on_attachments_loaded([]);
966 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
967 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
968 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
971 on_attachments_loaded: function(attachments) {
974 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
975 _.each(attachments,function(a) {
977 if(a.type === "binary") {
978 a.url = prefix + a.id + '&t=' + (new Date().getTime());
981 self.items['files'] = attachments;
983 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
984 this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
986 on_attachment_changed: function(e) {
987 var $e = $(e.target);
988 if ($e.val() !== '') {
989 this.$element.find('form.oe_form_binary_form').submit();
990 $e.parent().find('input[type=file]').prop('disabled', true);
991 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
992 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
996 on_attachment_delete: function(e) {
1001 var $e = $(e.currentTarget);
1002 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1003 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1004 self.do_attachement_update(self.dataset, self.model_id);
1010 instance.web.TranslateDialog = instance.web.Dialog.extend({
1011 dialog_title: {toString: function () { return _t("Translations"); }},
1012 init: function(view) {
1013 // TODO fme: should add the language to fields_view_get because between the fields view get
1014 // and the moment the user opens the translation dialog, the user language could have been changed
1015 this.view_language = view.session.user_context.lang;
1016 this['on_button_' + _t("Save")] = this.on_btn_save;
1017 this['on_button_' + _t("Close")] = this.on_btn_close;
1023 this.view_type = view.fields_view.type || '';
1024 this.$fields_form = null;
1025 this.$view_form = null;
1026 this.$sidebar_form = null;
1027 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
1028 this.languages = null;
1029 this.languages_loaded = $.Deferred();
1030 (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
1031 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
1036 $.when(this.languages_loaded).then(function() {
1037 self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
1038 self.$fields_form = self.$element.find('.oe_translation_form');
1039 self.$fields_form.find('.oe_trad_field').change(function() {
1040 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
1045 on_languages_loaded: function(langs) {
1046 this.languages = langs;
1047 this.languages_loaded.resolve();
1049 do_load_fields_values: function(callback) {
1052 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1053 _.each(self.languages, function(lg) {
1054 var deff = $.Deferred();
1055 deffered.push(deff);
1056 var callback = function(values) {
1057 _.each(self.translatable_fields_keys, function(f) {
1058 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1062 if (lg.code === self.view_language) {
1064 _.each(self.translatable_fields_keys, function(field) {
1065 values[field] = self.view.fields[field].get_value();
1069 self.rpc('/web/dataset/get', {
1070 model: self.view.dataset.model,
1071 ids: [self.view.datarecord.id],
1072 fields: self.translatable_fields_keys,
1073 context: self.view.dataset.get_context({
1078 $.when.apply(null, deffered).then(callback);
1080 open: function(field) {
1083 $.when(this.languages_loaded).then(function() {
1084 if (self.view.translatable_fields && self.view.translatable_fields.length) {
1085 self.do_load_fields_values(function() {
1088 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1089 self.$element.scrollTo($field_input);
1090 $field_input.focus();
1098 on_btn_save: function() {
1101 trads_mutex = new $.Mutex();
1102 self.$fields_form.find('.oe_trad_field.touched').each(function() {
1103 var field = $(this).attr('name').split('-');
1104 if (!trads[field[0]]) {
1105 trads[field[0]] = {};
1107 trads[field[0]][field[1]] = $(this).val();
1109 _.each(trads, function(data, code) {
1110 if (code === self.view_language) {
1111 _.each(data, function(value, field) {
1112 self.view.fields[field].set_value(value);
1115 trads_mutex.exec(function() {
1116 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1121 on_btn_close: function() {
1126 instance.web.View = instance.web.Widget.extend({
1127 template: "EmptyComponent",
1128 // name displayed in view switchers
1131 * Define a view type for each view to allow automatic call to fields_view_get.
1133 view_type: undefined,
1134 init: function(parent, dataset, view_id, options) {
1135 this._super(parent);
1136 this.dataset = dataset;
1137 this.view_id = view_id;
1138 this.set_default_options(options);
1141 return this.load_view();
1143 load_view: function() {
1144 if (this.embedded_view) {
1145 var def = $.Deferred();
1147 $.async_when().then(function() {def.resolve(self.embedded_view);});
1148 return def.pipe(this.on_loaded);
1150 var context = new instance.web.CompoundContext(this.dataset.get_context());
1151 if (! this.view_type)
1152 console.warn("view_type is not defined", this);
1153 return this.rpc("/web/view/load", {
1154 "model": this.dataset.model,
1155 "view_id": this.view_id,
1156 "view_type": this.view_type,
1157 toolbar: !!this.options.$sidebar,
1159 }).pipe(this.on_loaded);
1163 * Called after a successful call to fields_view_get.
1164 * Must return a promise.
1166 on_loaded: function(fields_view_get) {
1168 set_default_options: function(options) {
1169 this.options = options || {};
1170 _.defaults(this.options, {
1171 // All possible views options should be defaulted here
1175 action_views_ids: {}
1178 open_translate_dialog: function(field) {
1179 if (!this.translate_dialog) {
1180 this.translate_dialog = new instance.web.TranslateDialog(this).start();
1182 this.translate_dialog.open(field);
1185 * Fetches and executes the action identified by ``action_data``.
1187 * @param {Object} action_data the action descriptor data
1188 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1189 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1190 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1191 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1192 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1193 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1194 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1196 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1198 var result_handler = function () {
1199 if (on_closed) { on_closed.apply(null, arguments); }
1200 if (self.getParent() && self.getParent().on_action_executed) {
1201 return self.getParent().on_action_executed.apply(null, arguments);
1204 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1206 var handler = function (r) {
1207 var action = r.result;
1208 if (action && action.constructor == Object) {
1209 var ncontext = new instance.web.CompoundContext(context);
1212 active_id: record_id,
1213 active_ids: [record_id],
1214 active_model: dataset.model
1217 ncontext.add(action.context || {});
1218 return self.rpc('/web/session/eval_domain_and_context', {
1219 contexts: [ncontext],
1221 }).pipe(function (results) {
1222 action.context = results.context;
1223 /* niv: previously we were overriding once more with action_data.context,
1224 * I assumed this was not a correct behavior and removed it
1226 return self.do_action(action, result_handler);
1229 return result_handler();
1233 if (action_data.special) {
1234 return handler({result: {"type":"ir.actions.act_window_close"}});
1235 } else if (action_data.type=="object") {
1236 var args = [[record_id]], additional_args = [];
1237 if (action_data.args) {
1239 // Warning: quotes and double quotes problem due to json and xml clash
1240 // Maybe we should force escaping in xml or do a better parse of the args array
1241 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1242 args = args.concat(additional_args);
1244 console.error("Could not JSON.parse arguments", action_data.args);
1248 return dataset.call_button(action_data.name, args, handler);
1249 } else if (action_data.type=="action") {
1250 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1252 return dataset.exec_workflow(record_id, action_data.name, handler);
1256 * Directly set a view to use instead of calling fields_view_get. This method must
1257 * be called before start(). When an embedded view is set, underlying implementations
1258 * of instance.web.View must use the provided view instead of any other one.
1260 * @param embedded_view A view.
1262 set_embedded_view: function(embedded_view) {
1263 this.embedded_view = embedded_view;
1265 do_show: function () {
1266 this.$element.show();
1268 do_hide: function () {
1269 this.$element.hide();
1271 do_push_state: function(state) {
1272 if (this.getParent() && this.getParent().do_push_state) {
1273 this.getParent().do_push_state(state);
1276 do_load_state: function(state, warm) {
1279 * Switches to a specific view type
1281 * @param {String} view view type to switch to
1283 do_switch_view: function(view) {
1286 * Cancels the switch to the current view, switches to the previous one
1288 * @param {Object} [options]
1289 * @param {Boolean} [options.created=false] resource was created
1290 * @param {String} [options.default=null] view to switch to if no previous view
1292 do_prev_view: function (options) {
1294 do_search: function(view) {
1296 on_sidebar_import: function() {
1297 var import_view = new instance.web.DataImport(this, this.dataset);
1298 import_view.start();
1300 on_sidebar_export: function() {
1301 var export_view = new instance.web.DataExport(this, this.dataset);
1302 export_view.start();
1304 on_sidebar_translate: function() {
1305 return this.do_action({
1306 res_model : 'ir.translation',
1307 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1308 views: [[false, 'list'], [false, 'form']],
1309 type : 'ir.actions.act_window',
1314 sidebar_context: function () {
1318 * Asks the view to reload itself, if the reloading is asynchronous should
1319 * return a {$.Deferred} indicating when the reloading is done.
1321 reload: function () {
1326 instance.web.xml_to_json = function(node) {
1327 switch (node.nodeType) {
1333 var attrs = $(node).getAttributes();
1334 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1337 attrs[key] = JSON.parse(attrs[key]);
1342 tag: node.tagName.toLowerCase(),
1344 children: _.map(node.childNodes, instance.web.xml_to_json)
1348 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1349 // For debugging purpose, this function will convert a json node back to xml
1350 // Maybe useful for xml view editor
1351 indent = indent || 0;
1352 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1353 r = sindent + '<' + node.tag,
1354 cr = human_readable ? '\n' : '';
1356 if (typeof(node) === 'string') {
1357 return sindent + node;
1358 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1359 throw("Node a json node");
1361 for (var attr in node.attrs) {
1362 var vattr = node.attrs[attr];
1363 if (typeof(vattr) !== 'string') {
1365 vattr = JSON.stringify(vattr);
1367 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1368 if (human_readable) {
1369 vattr = vattr.replace(/"/g, "'");
1371 r += ' ' + attr + '="' + vattr + '"';
1373 if (node.children && node.children.length) {
1376 for (var i = 0, ii = node.children.length; i < ii; i++) {
1377 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1379 r += childs.join(cr);
1380 r += cr + sindent + '</' + node.tag + '>';
1386 instance.web.xml_to_str = function(node) {
1387 if (window.ActiveXObject) {
1390 return (new XMLSerializer()).serializeToString(node);
1393 instance.web.str_to_xml = function(s) {
1394 if (window.DOMParser) {
1395 var dp = new DOMParser();
1396 var r = dp.parseFromString(s, "text/xml");
1397 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1398 throw new Error("Could not parse string to xml");
1404 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1406 throw new Error("Could not find a DOM Parser: " + e.message);
1409 xDoc.preserveWhiteSpace = true;
1415 * Registry for all the main views
1417 instance.web.views = new instance.web.Registry();
1421 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: