1 openerp.web.list = function (instance) {
2 var _t = instance.web._t,
3 _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
5 instance.web.views.add('list', 'instance.web.ListView');
6 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
8 display_name: _lt('List'),
10 // records can be selected one by one
12 // list rows can be deleted
14 // whether the column headers should be displayed
16 // display addition button, with that label
17 'addable': _lt("Create"),
18 // whether the list view can be sorted, note that once a view has been
19 // sorted it can not be reordered anymore
21 // whether the view rows can be reordered (via vertical drag & drop)
23 'action_buttons': true,
26 * Core class for list-type displays.
28 * As a view, needs a number of view-related parameters to be correctly
29 * instantiated, provides options and overridable methods for behavioral
32 * See constructor parameters and method documentations for information on
33 * the default behaviors and possible options for the list view.
35 * @constructs instance.web.ListView
36 * @extends instance.web.View
38 * @param parent parent object
39 * @param {instance.web.DataSet} dataset the dataset the view should work with
40 * @param {String} view_id the listview's identifier, if any
41 * @param {Object} options A set of options used to configure the view
42 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
43 * @param {Boolean} [options.header=true] should the list's header be displayed
44 * @param {Boolean} [options.deletable=true] are the list rows deletable
45 * @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
46 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
47 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
49 init: function(parent, dataset, view_id, options) {
52 this.set_default_options(_.extend({}, this.defaults, options || {}));
53 this.dataset = dataset;
54 this.model = dataset.model;
55 this.view_id = view_id;
56 this.previous_colspan = null;
62 this.records = new Collection();
64 this.set_groups(new instance.web.ListView.Groups(this));
66 if (this.dataset instanceof instance.web.DataSetStatic) {
67 this.groups.datagroup = new instance.web.StaticDataGroup(this.dataset);
69 this.groups.datagroup = new instance.web.DataGroup(
72 dataset.get_context());
73 this.groups.datagroup.sort = this.dataset._sort;
77 this.records.bind('change', function (event, record, key) {
78 if (!_(self.aggregate_columns).chain()
79 .pluck('name').contains(key).value()) {
82 self.compute_aggregates();
88 * Retrieves the view's number of records per page (|| section)
90 * options > defaults > parent.action.limit > indefinite
92 * @returns {Number|null}
95 if (this._limit === undefined) {
96 this._limit = (this.options.limit
97 || this.defaults.limit
98 || (this.getParent().action || {}).limit
104 * Set a custom Group construct as the root of the List View.
106 * @param {instance.web.ListView.Groups} groups
108 set_groups: function (groups) {
111 $(this.groups).unbind("selected deleted action row_link");
115 this.groups = groups;
116 $(this.groups).bind({
117 'selected': function (e, ids, records) {
118 self.do_select(ids, records);
120 'deleted': function (e, ids) {
123 'action': function (e, action_name, id, callback) {
124 self.do_button_action(action_name, id, callback);
126 'row_link': function (e, id, dataset, view) {
127 self.do_activate_record(dataset.index, id, dataset, view);
132 * View startup method, the default behavior is to set the ``oe-listview``
133 * class on its root element and to perform an RPC load call.
135 * @returns {$.Deferred} loading promise
138 this.$element.addClass('oe-listview');
139 return this.reload_view(null, null, true);
142 * Returns the style for the provided record in the current view (from the
143 * ``@colors`` and ``@fonts`` attributes)
145 * @param {Record} record record for the current row
146 * @returns {String} CSS style declaration
148 style_for: function (record) {
151 var context = _.extend({}, record.attributes, {
152 uid: this.session.uid,
153 current_date: new Date().toString('yyyy-MM-dd')
154 // TODO: time, datetime, relativedelta
158 for(var i=0, len=this.fonts.length; i<len; ++i) {
159 var pair = this.fonts[i],
161 expression = pair[1];
162 if (py.evaluate(expression, context).toJSON()) {
165 style += 'font-weight: bold;';
168 style += 'font-style: italic;';
171 style += 'text-decoration: underline;';
178 if (!this.colors) { return style; }
179 for(var i=0, len=this.colors.length; i<len; ++i) {
180 var pair = this.colors[i],
182 expression = pair[1];
183 if (py.evaluate(expression, context).toJSON()) {
184 return style += 'color: ' + color + ';';
186 // TODO: handle evaluation errors
191 * Called after loading the list view's description, sets up such things
192 * as the view table's columns, renders the table itself and hooks up the
193 * various table-level and row-level DOM events (action buttons, deletion
194 * buttons, selection of records, [New] button, selection of a given
197 * Sets up the following:
199 * * Processes arch and fields to generate a complete field descriptor for each field
200 * * Create the table itself and allocate visible columns
201 * * Hook in the top-level (header) [New|Add] and [Delete] button
202 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
203 * * Sets up event handlers for action buttons and per-row deletion button
204 * * Hooks global callback for clicking on a row
205 * * Sets up its sidebar, if any
207 * @param {Object} data wrapped fields_view_get result
208 * @param {Object} data.fields_view fields_view_get result (processed)
209 * @param {Object} data.fields_view.fields mapping of fields for the current model
210 * @param {Object} data.fields_view.arch current list view descriptor
211 * @param {Boolean} grouped Is the list view grouped
213 on_loaded: function(data, grouped) {
215 this.fields_view = data;
216 this.name = "" + this.fields_view.arch.attrs.string;
218 if (this.fields_view.arch.attrs.colors) {
219 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
221 .map(function(color_pair) {
222 var pair = color_pair.split(':'),
225 return [color, py.parse(py.tokenize(expr)), expr];
229 if (this.fields_view.arch.attrs.fonts) {
230 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
231 .map(function(font_pair) {
232 var pair = font_pair.split(':'),
235 return [font, py.parse(py.tokenize(expr)), expr];
239 this.setup_columns(this.fields_view.fields, grouped);
241 this.$element.html(QWeb.render(this._template, this));
244 this.$element.find('.all-record-selector').click(function(){
245 self.$element.find('.oe-record-selector input').prop('checked',
246 self.$element.find('.all-record-selector').prop('checked') || false);
247 var selection = self.groups.get_selection();
248 $(self.groups).trigger(
249 'selected', [selection.ids, selection.records]);
253 this.$element.find('thead').delegate('th.oe-sortable[data-id]', 'click', function (e) {
256 self.dataset.sort($this.data('id'));
257 if($this.hasClass("sortdown") || $this.hasClass("sortup")) {
258 $this.toggleClass("sortdown").toggleClass("sortup");
260 $this.toggleClass("sortdown");
262 $this.siblings('.oe-sortable').removeClass("sortup sortdown");
264 self.reload_content();
267 // Add button and Import link
268 if (!this.$buttons) {
269 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
270 if (this.options.$buttons) {
271 this.$buttons.appendTo(this.options.$buttons);
273 this.$element.find('.oe_list_buttons').replaceWith(this.$buttons);
275 this.$buttons.find('.oe_list_add')
276 .click(this.proxy('do_add_record'))
277 .prop('disabled', grouped && this.options.editable);
278 this.$buttons.on('click', '.oe_list_button_import', function() {
279 self.on_sidebar_import();
286 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
287 if (this.options.$buttons) {
288 this.$pager.appendTo(this.options.$pager);
290 this.$element.find('.oe_list_pager').replaceWith(this.$pager);
294 .on('click', 'a[data-pager-action]', function () {
296 var max_page = Math.floor(self.dataset.size() / self.limit());
297 switch ($this.data('pager-action')) {
299 self.page = 0; break;
301 self.page = max_page - 1;
304 self.page += 1; break;
306 self.page -= 1; break;
309 self.page = max_page;
310 } else if (self.page > max_page) {
313 self.reload_content();
314 }).find('.oe-pager-state')
315 .click(function (e) {
319 var $select = $('<select>')
320 .appendTo($this.empty())
321 .click(function (e) {e.stopPropagation();})
322 .append('<option value="80">80</option>' +
323 '<option value="100">100</option>' +
324 '<option value="200">200</option>' +
325 '<option value="500">500</option>' +
326 '<option value="NaN">' + _t("Unlimited") + '</option>')
327 .change(function () {
328 var val = parseInt($select.val(), 10);
329 self._limit = (isNaN(val) ? null : val);
331 self.reload_content();
333 .val(self._limit || 'NaN');
338 if (!this.sidebar && this.options.$sidebar) {
339 this.sidebar = new instance.web.Sidebar(this);
340 this.sidebar.appendTo(this.options.$sidebar);
341 this.sidebar.add_items('other', [
342 { label: _t('Delete'), callback: this.do_delete_selected },
344 this.sidebar.add_toolbar(this.fields_view.toolbar);
348 * Configures the ListView pager based on the provided dataset's information
350 * Horrifying side-effect: sets the dataset's data on this.dataset?
352 * @param {instance.web.DataSet} dataset
354 configure_pager: function (dataset) {
355 this.dataset.ids = dataset.ids;
357 if (dataset._length) {
358 this.dataset._length = dataset._length;
361 var total = dataset.size();
364 var range_start = this.page * this.limit() + 1;
365 var range_stop = range_start - 1 + this.limit();
366 if (range_stop > total) {
369 spager = _.str.sprintf('%d-%d of %d', range_start, range_stop, total);
372 this.$pager.find('.oe-pager-state').text(spager);
375 * Sets up the listview's columns: merges view and fields data, move
376 * grouped-by columns to the front of the columns list and make them all
379 * @param {Object} fields fields_view_get's fields section
380 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
382 setup_columns: function (fields, grouped) {
383 var domain_computer = instance.web.form.compute_domain;
385 var noop = function () { return {}; };
386 var field_to_column = function (field) {
387 var name = field.attrs.name;
388 var column = _.extend({id: name, tag: field.tag},
389 fields[name], field.attrs);
390 // modifiers computer
391 if (column.modifiers) {
392 var modifiers = JSON.parse(column.modifiers);
393 column.modifiers_for = function (fields) {
394 if (!modifiers.invisible) {
398 'invisible': domain_computer(modifiers.invisible, fields)
401 if (modifiers['tree_invisible']) {
402 column.invisible = '1';
404 delete column.invisible;
407 column.modifiers_for = noop;
412 this.columns.splice(0, this.columns.length);
413 this.columns.push.apply(
415 _(this.fields_view.arch.children).map(field_to_column));
417 this.columns.unshift({
418 id: '_group', tag: '', string: _t("Group"), meta: true,
419 modifiers_for: function () { return {}; }
421 id: '_count', tag: '', string: '#', meta: true,
422 modifiers_for: function () { return {}; }
426 this.visible_columns = _.filter(this.columns, function (column) {
427 return column.invisible !== '1';
430 this.aggregate_columns = _(this.visible_columns)
431 .map(function (column) {
432 if (column.type !== 'integer' && column.type !== 'float') {
435 var aggregation_func = column['group_operator'] || 'sum';
436 if (!(aggregation_func in column)) {
440 return _.extend({}, column, {
441 'function': aggregation_func,
442 label: column[aggregation_func]
447 * Used to handle a click on a table row, if no other handler caught the
450 * The default implementation asks the list view's view manager to switch
451 * to a different view (by calling
452 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
453 * provided record index (within the current list view's dataset).
455 * If the index is null, ``switch_to_record`` asks for the creation of a
458 * @param {Number|void} index the record index (in the current dataset) to switch to
459 * @param {String} [view="page"] the view type to switch to
461 select_record:function (index, view) {
462 view = view || index == null ? 'form' : 'form';
463 this.dataset.index = index;
464 _.delay(_.bind(function () {
465 this.do_switch_view(view);
468 do_show: function () {
471 this.sidebar.$element.show();
474 this.$buttons.show();
480 do_hide: function () {
482 this.sidebar.$element.hide();
485 this.$buttons.hide();
493 * Reloads the list view based on the current settings (dataset & al)
495 * @param {Boolean} [grouped] Should the list be displayed grouped
496 * @param {Object} [context] context to send the server while loading the view
498 reload_view: function (grouped, context, initial) {
500 var callback = function (field_view_get) {
501 self.on_loaded(field_view_get, grouped);
503 if (this.embedded_view) {
504 return $.Deferred().then(callback).resolve(this.embedded_view);
506 return this.rpc('/web/listview/load', {
508 view_id: this.view_id,
510 context: this.dataset.get_context(context),
511 toolbar: !!this.options.$sidebar
516 * re-renders the content of the list view
518 * @returns {$.Deferred} promise to content reloading
520 reload_content: function () {
522 self.$element.find('.all-record-selector').prop('checked', false);
523 this.records.reset();
524 var reloaded = $.Deferred();
525 this.$element.find('.oe-listview-content').append(
526 this.groups.render(function () {
527 if (self.dataset.index == null) {
529 self.records.each(function () { has_one = true; });
531 self.dataset.index = 0;
534 self.compute_aggregates();
541 return reloaded.promise();
543 reload: function () {
544 return this.reload_content();
546 do_load_state: function(state, warm) {
548 if (state.page && this.page !== state.page) {
549 this.page = state.page;
553 if (_.isString(state.limit)) {
556 if (state.limit !== this._limit) {
557 this._limit = state.limit;
562 this.reload_content();
566 * Handler for the result of eval_domain_and_context, actually perform the
569 * @param {Object} results results of evaluating domain and process for a search
571 do_search: function (domain, context, group_by) {
573 this.groups.datagroup = new instance.web.DataGroup(
574 this, this.model, domain, context, group_by);
575 this.groups.datagroup.sort = this.dataset._sort;
577 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
580 this.no_leaf = !!context['group_by_no_leaf'];
582 this.reload_view(!!group_by, context).then(
583 this.proxy('reload_content'));
586 * Handles the signal to delete lines from the records list
588 * @param {Array} ids the ids of the records to delete
590 do_delete: function (ids) {
591 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
595 return $.when(this.dataset.unlink(ids)).then(function () {
596 _(ids).each(function (id) {
597 self.records.remove(self.records.get(id));
599 self.configure_pager(self.dataset);
600 self.compute_aggregates();
604 * Handles the signal indicating that a new record has been selected
606 * @param {Array} ids selected record ids
607 * @param {Array} records selected record values
609 do_select: function (ids, records) {
611 this.dataset.index = 0;
613 this.sidebar.$element.hide();
615 this.compute_aggregates();
619 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
621 this.sidebar.$element.show();
624 this.compute_aggregates(_(records).map(function (record) {
625 return {count: 1, values: record};
629 * Handles action button signals on a record
631 * @param {String} name action name
632 * @param {Object} id id of the record the action should be called on
633 * @param {Function} callback should be called after the action is executed, if non-null
635 do_button_action: function (name, id, callback) {
636 var action = _.detect(this.columns, function (field) {
637 return field.name === name;
639 if (!action) { return; }
640 if ('confirm' in action && !window.confirm(action.confirm)) {
644 var c = new instance.web.CompoundContext();
645 c.set_eval_context(_.extend({
648 active_model: this.dataset.model
649 }, this.records.get(id).toContext()));
650 if (action.context) {
651 c.add(action.context);
654 this.do_execute_action(action, this.dataset, id, callback);
657 * Handles the activation of a record (clicking on it)
659 * @param {Number} index index of the record in the dataset
660 * @param {Object} id identifier of the activated record
661 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
663 do_activate_record: function (index, id, dataset, view) {
664 this.dataset.ids = dataset.ids;
665 this.select_record(index, view);
668 * Handles signal for the addition of a new record (can be a creation,
669 * can be the addition from a remote source, ...)
671 * The default implementation is to switch to a new record on the form view
673 do_add_record: function () {
674 this.select_record(null);
677 * Handles deletion of all selected lines
679 do_delete_selected: function () {
680 var ids = this.groups.get_selection().ids;
682 this.do_delete(this.groups.get_selection().ids);
684 this.do_warn(_t("Warning"), _t("You must select at least one record."));
688 * Computes the aggregates for the current list view, either on the
689 * records provided or on the records of the internal
690 * :js:class:`~instance.web.ListView.Group`, by calling
691 * :js:func:`~instance.web.ListView.group.get_records`.
693 * Then displays the aggregates in the table through
694 * :js:method:`~instance.web.ListView.display_aggregates`.
696 * @param {Array} [records]
698 compute_aggregates: function (records) {
699 var columns = _(this.aggregate_columns).filter(function (column) {
700 return column['function']; });
701 if (_.isEmpty(columns)) { return; }
703 if (_.isEmpty(records)) {
704 records = this.groups.get_records();
706 records = _(records).compact();
708 var count = 0, sums = {};
709 _(columns).each(function (column) {
710 switch (column['function']) {
712 sums[column.id] = -Infinity;
715 sums[column.id] = Infinity;
721 _(records).each(function (record) {
722 count += record.count || 1;
723 _(columns).each(function (column) {
724 var field = column.id,
725 value = record.values[field];
726 switch (column['function']) {
728 sums[field] += value;
731 sums[field] += record.count * value;
734 if (sums[field] > value) {
739 if (sums[field] < value) {
748 _(columns).each(function (column) {
749 var field = column.id;
750 switch (column['function']) {
752 aggregates[field] = {value: sums[field] / count};
755 aggregates[field] = {value: sums[field]};
759 this.display_aggregates(aggregates);
761 display_aggregates: function (aggregation) {
763 var $footer_cells = this.$element.find('.oe-list-footer');
764 _(this.aggregate_columns).each(function (column) {
765 if (!column['function']) {
769 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
770 .html(instance.web.format_cell(aggregation, column, {
771 process_modifiers: false
775 get_selected_ids: function() {
776 var ids = this.groups.get_selection().ids;
780 * Adds padding columns at the start or end of all table rows (including
783 * @param {Number} count number of columns to add
784 * @param {Object} options
785 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
786 * @param {Object} [options.except] content row to not pad
788 pad_columns: function (count, options) {
789 options = options || {};
790 // padding for action/pager header
791 var $first_header = this.$element.find('thead tr:first th');
792 var colspan = $first_header.attr('colspan');
794 if (!this.previous_colspan) {
795 this.previous_colspan = colspan;
797 $first_header.attr('colspan', parseInt(colspan, 10) + count);
799 // Padding for column titles, footer and data rows
800 var $rows = this.$element
801 .find('.oe-listview-header-columns, tr:not(thead tr)')
802 .not(options['except']);
803 var newcols = new Array(count+1).join('<td class="oe-listview-padding"></td>');
804 if (options.position === 'before') {
805 $rows.prepend(newcols);
807 $rows.append(newcols);
811 * Removes all padding columns of the table
813 unpad_columns: function () {
814 this.$element.find('.oe-listview-padding').remove();
815 if (this.previous_colspan) {
817 .find('thead tr:first th')
818 .attr('colspan', this.previous_colspan);
819 this.previous_colspan = null;
822 no_result: function () {
823 this.$element.find('.oe_view_nocontent').remove();
824 if (this.groups.group_by
825 || !this.options.action
826 || !this.options.action.help) {
829 this.$element.find('table:first').hide();
830 this.$element.prepend(
831 $('<div class="oe_view_nocontent">')
832 .append($('<img>', { src: '/web/static/src/img/view_empty_arrow.png' }))
833 .append($('<div>').html(this.options.action.help))
837 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
839 * List display for the ListView, handles basic DOM events and transforms
840 * them in the relevant higher-level events, to which the list view (or
841 * other consumers) can subscribe.
843 * Events on this object are registered via jQuery.
848 * Triggered when a row is selected (using check boxes), provides an
849 * array of ids of all the selected records.
851 * Triggered when deletion buttons are hit, provide an array of ids of
852 * all the records being marked for suppression.
854 * Triggered when an action button is clicked, provides two parameters:
856 * * The name of the action to execute (as a string)
857 * * The id of the record to execute the action on
859 * Triggered when a row of the table is clicked, provides the index (in
860 * the rows array) and id of the selected record to the handle function.
862 * @constructs instance.web.ListView.List
863 * @extends instance.web.Class
865 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
867 init: function (group, opts) {
870 this.view = group.view;
871 this.session = this.view.session;
873 this.options = opts.options;
874 this.columns = opts.columns;
875 this.dataset = opts.dataset;
876 this.records = opts.records;
878 this.record_callbacks = {
879 'remove': function (event, record) {
880 var $row = self.$current.find(
881 '[data-id=' + record.get('id') + ']');
882 var index = $row.data('index');
884 self.refresh_zebra(index);
886 'reset': function () { return self.on_records_reset(); },
887 'change': function (event, record) {
888 var $row = self.$current.find('[data-id=' + record.get('id') + ']');
889 $row.replaceWith(self.render_record(record));
891 'add': function (ev, records, record, index) {
892 var $new_row = $('<tr>').attr({
893 'data-id': record.get('id')
897 $new_row.prependTo(self.$current);
899 var previous_record = records.at(index-1),
900 $previous_sibling = self.$current.find(
901 '[data-id=' + previous_record.get('id') + ']');
902 $new_row.insertAfter($previous_sibling);
905 self.refresh_zebra(index, 1);
908 _(this.record_callbacks).each(function (callback, event) {
909 this.records.bind(event, callback);
912 this.$_element = $('<tbody>')
913 .appendTo(document.body)
914 .delegate('th.oe-record-selector', 'click', function (e) {
916 var selection = self.get_selection();
918 'selected', [selection.ids, selection.records]);
920 .delegate('td.oe-record-delete button', 'click', function (e) {
922 var $row = $(e.target).closest('tr');
923 $(self).trigger('deleted', [[self.row_id($row)]]);
925 .delegate('td.oe-field-cell button', 'click', function (e) {
927 var $target = $(e.currentTarget),
928 field = $target.closest('td').data('field'),
929 $row = $target.closest('tr'),
930 record_id = self.row_id($row);
932 // note: $.data converts data to number if it's composed only
933 // of digits, nice when storing actual numbers, not nice when
934 // storing strings composed only of digits. Force the action
935 // name to be a string
936 $(self).trigger('action', [field.toString(), record_id, function () {
937 return self.reload_record(self.records.get(record_id));
940 .delegate('a', 'click', function (e) {
943 .delegate('tr', 'click', function (e) {
945 var row_id = self.row_id(e.currentTarget);
946 if (row_id !== undefined) {
947 if (!self.dataset.select_id(row_id)) {
948 throw "Could not find id in dataset"
954 row_clicked: function (e, view) {
957 [this.dataset.ids[this.dataset.index],
958 this.dataset, view]);
960 render_cell: function (record, column) {
962 if(column.type === 'reference') {
963 value = record.get(column.id);
965 // Ensure that value is in a reference "shape", otherwise we're
966 // going to loop on performing name_get after we've resolved (and
967 // set) a human-readable version. m2o does not have this issue
968 // because the non-human-readable is just a number, where the
969 // human-readable version is a pair
970 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
971 // reference values are in the shape "$model,$id" (as a
972 // string), we need to split and name_get this pair in order
973 // to get a correctly displayable value in the field
974 var model = ref_match[1],
975 id = parseInt(ref_match[2], 10);
976 new instance.web.DataSet(this.view, model).name_get([id], function(names) {
977 if (!names.length) { return; }
978 record.set(column.id, names[0][1]);
981 } else if (column.type === 'many2one') {
982 value = record.get(column.id);
983 // m2o values are usually name_get formatted, [Number, String]
984 // pairs, but in some cases only the id is provided. In these
985 // cases, we need to perform a name_get call to fetch the actual
987 if (typeof value === 'number' || value instanceof Number) {
988 // fetch the name, set it on the record (in the right field)
989 // and let the various registered events handle refreshing the
991 new instance.web.DataSet(this.view, column.relation)
992 .name_get([value], function (names) {
993 if (!names.length) { return; }
994 record.set(column.id, names[0]);
998 return instance.web.format_cell(record.toForm().data, column, {
999 model: this.dataset.model,
1000 id: record.get('id')
1003 render: function () {
1005 if (this.$current) {
1006 this.$current.remove();
1008 this.$current = this.$_element.clone(true);
1009 this.$current.empty().append(
1010 QWeb.render('ListView.rows', _.extend({
1011 render_cell: function () {
1012 return self.render_cell.apply(self, arguments); }
1014 this.pad_table_to(5);
1016 pad_table_to: function (count) {
1017 if (this.records.length >= count ||
1018 _(this.columns).any(function(column) { return column.meta; })) {
1022 if (this.options.selectable) {
1023 cells.push('<th class="oe-record-selector"></td>');
1025 _(this.columns).each(function(column) {
1026 if (column.invisible === '1') {
1029 if (column.tag === 'button') {
1030 cells.push('<td class="oe-button" title="' + column.string + '"> </td>');
1032 cells.push('<td title="' + column.string + '"> </td>');
1035 if (this.options.deletable) {
1036 cells.push('<td class="oe-record-delete"><button type="button" style="visibility: hidden"> </button></td>');
1038 cells.unshift('<tr>');
1039 cells.push('</tr>');
1041 var row = cells.join('');
1043 .children('tr:not([data-id])').remove().end()
1044 .append(new Array(count - this.records.length + 1).join(row));
1045 this.refresh_zebra(this.records.length);
1048 * Gets the ids of all currently selected records, if any
1049 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1051 get_selection: function () {
1052 if (!this.options.selectable) {
1055 var records = this.records;
1056 var result = {ids: [], records: []};
1057 this.$current.find('th.oe-record-selector input:checked')
1058 .closest('tr').each(function () {
1059 var record = records.get($(this).data('id'));
1060 result.ids.push(record.get('id'));
1061 result.records.push(record.attributes);
1066 * Returns the identifier of the object displayed in the provided table
1069 * @param {Object} row the selected table row
1070 * @returns {Number|String} the identifier of the row's object
1072 row_id: function (row) {
1073 return $(row).data('id');
1076 * Death signal, cleans up list display
1078 on_records_reset: function () {
1079 _(this.record_callbacks).each(function (callback, event) {
1080 this.records.unbind(event, callback);
1082 if (!this.$current) { return; }
1083 this.$current.remove();
1084 this.$current = null;
1085 this.$_element.remove();
1087 get_records: function () {
1088 return this.records.map(function (record) {
1089 return {count: 1, values: record.attributes};
1093 * Reloads the provided record by re-reading its content from the server.
1095 * @param {Record} record
1096 * @returns {$.Deferred} promise to the finalization of the reloading
1098 reload_record: function (record) {
1099 return this.dataset.read_ids(
1101 _.pluck(_(this.columns).filter(function (r) {
1102 return r.tag === 'field';
1104 ).then(function (records) {
1105 _(records[0]).each(function (value, key) {
1106 record.set(key, value, {silent: true});
1108 record.trigger('change', record);
1112 * Renders a list record to HTML
1114 * @param {Record} record index of the record to render in ``this.rows``
1115 * @returns {String} QWeb rendering of the selected record
1117 render_record: function (record) {
1118 var index = this.records.indexOf(record);
1119 return QWeb.render('ListView.row', {
1120 columns: this.columns,
1121 options: this.options,
1123 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1125 render_cell: function () {
1126 return this.render_cell.apply(this, arguments); }
1130 * Fixes fixes the even/odd classes
1132 * @param {Number} [from_index] index from which to resequence
1133 * @param {Number} [offset = 0] selection offset for DOM, in case there are rows to ignore in the table
1135 refresh_zebra: function (from_index, offset) {
1136 offset = offset || 0;
1137 from_index = from_index || 0;
1138 var dom_offset = offset + from_index;
1139 var sel = dom_offset ? ':gt(' + (dom_offset - 1) + ')' : null;
1140 this.$current.children(sel).each(function (i, e) {
1141 var index = from_index + i;
1142 // reset record-index accelerators on rows and even/odd
1143 var even = index%2 === 0;
1144 $(e).toggleClass('even', even)
1145 .toggleClass('odd', !even);
1149 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1150 passtrough_events: 'action deleted row_link',
1152 * Grouped display for the ListView. Handles basic DOM events and interacts
1153 * with the :js:class:`~instance.web.DataGroup` bound to it.
1155 * Provides events similar to those of
1156 * :js:class:`~instance.web.ListView.List`
1158 * @constructs instance.web.ListView.Groups
1159 * @extends instance.web.Class
1161 * @param {instance.web.ListView} view
1162 * @param {Object} [options]
1163 * @param {Collection} [options.records]
1164 * @param {Object} [options.options]
1165 * @param {Array} [options.columns]
1167 init: function (view, options) {
1168 options = options || {};
1170 this.records = options.records || view.records;
1171 this.options = options.options || view.options;
1172 this.columns = options.columns || view.columns;
1173 this.datagroup = null;
1181 this.records.bind('reset', function () {
1182 return self.on_records_reset(); });
1184 make_fragment: function () {
1185 return document.createDocumentFragment();
1188 * Returns a DOM node after which a new tbody can be inserted, so that it
1189 * follows the provided row.
1191 * Necessary to insert the result of a new group or list view within an
1192 * existing groups render, without losing track of the groups's own
1195 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1196 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1198 point_insertion: function (row) {
1200 var red_letter_tboday = $row.closest('tbody')[0];
1202 var $next_siblings = $row.nextAll();
1203 if ($next_siblings.length) {
1204 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1206 $root_kanal.append($next_siblings);
1207 this.elements.splice(
1208 _.indexOf(this.elements, red_letter_tboday),
1212 return red_letter_tboday;
1214 make_paginator: function () {
1216 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1217 .click(function (e) {
1218 e.stopPropagation();
1221 self.$row.closest('tbody').next()
1222 .replaceWith(self.render());
1224 var $next = $('<button type="button" data-pager-action="next">></button>')
1225 .click(function (e) {
1226 e.stopPropagation();
1229 self.$row.closest('tbody').next()
1230 .replaceWith(self.render());
1232 this.$row.children().last()
1234 .append('<span class="oe-pager-state"></span>')
1237 open: function (point_insertion) {
1238 this.render().insertAfter(point_insertion);
1240 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1241 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1242 if (no_subgroups && records_terminated) {
1243 this.make_paginator();
1246 close: function () {
1247 this.$row.children().last().empty();
1248 this.records.reset();
1251 * Prefixes ``$node`` with floated spaces in order to indent it relative
1252 * to its own left margin/baseline
1254 * @param {jQuery} $node jQuery object to indent
1255 * @param {Number} level current nesting level, >= 1
1256 * @returns {jQuery} the indentation node created
1258 indent: function ($node, level) {
1260 .css({'float': 'left', 'white-space': 'pre'})
1261 .text(new Array(level).join(' '))
1264 render_groups: function (datagroups) {
1266 var placeholder = this.make_fragment();
1267 _(datagroups).each(function (group) {
1268 if (self.children[group.value]) {
1269 self.records.proxy(group.value).reset();
1270 delete self.children[group.value];
1272 var child = self.children[group.value] = new instance.web.ListView.Groups(self.view, {
1273 records: self.records.proxy(group.value),
1274 options: self.options,
1275 columns: self.columns
1277 self.bind_child_events(child);
1278 child.datagroup = group;
1280 var $row = child.$row = $('<tr>');
1281 if (group.openable && group.length) {
1282 $row.click(function (e) {
1283 if (!$row.data('open')) {
1284 $row.data('open', true)
1285 .find('span.ui-icon')
1286 .removeClass('ui-icon-triangle-1-e')
1287 .addClass('ui-icon-triangle-1-s');
1288 child.open(self.point_insertion(e.currentTarget));
1290 $row.removeData('open')
1291 .find('span.ui-icon')
1292 .removeClass('ui-icon-triangle-1-s')
1293 .addClass('ui-icon-triangle-1-e');
1298 placeholder.appendChild($row[0]);
1300 var $group_column = $('<th class="oe-group-name">').appendTo($row);
1301 // Don't fill this if group_by_no_leaf but no group_by
1302 if (group.grouped_on) {
1304 row_data[group.grouped_on] = group;
1305 var group_column = _(self.columns).detect(function (column) {
1306 return column.id === group.grouped_on; });
1308 $group_column.html(instance.web.format_cell(
1309 row_data, group_column, {
1310 value_if_empty: _t("Undefined"),
1311 process_modifiers: false
1314 $group_column.html(row_data[group_column.id].value);
1316 if (group.length && group.openable) {
1317 // Make openable if not terminal group & group_by_no_leaf
1318 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1320 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1321 // wonky background position to ensure nothing is displayed
1322 // there but the rest of the behavior is ui-icon's
1323 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1326 self.indent($group_column, group.level);
1328 $('<td>').text(group.length).appendTo($row);
1330 if (self.options.selectable) {
1331 $row.append('<td>');
1333 _(self.columns).chain()
1334 .filter(function (column) {return !column.invisible;})
1335 .each(function (column) {
1337 // do not do anything
1338 } else if (column.id in group.aggregates) {
1340 r[column.id] = {value: group.aggregates[column.id]};
1341 $('<td class="oe_number">')
1342 .html(instance.web.format_cell(
1343 r, column, {process_modifiers: false}))
1346 $row.append('<td>');
1349 if (self.options.deletable) {
1350 $row.append('<td class="oe-group-pagination">');
1355 bind_child_events: function (child) {
1356 var $this = $(this),
1358 $(child).bind('selected', function (e) {
1359 // can have selections spanning multiple links
1360 var selection = self.get_selection();
1361 $this.trigger(e, [selection.ids, selection.records]);
1362 }).bind(this.passtrough_events, function (e) {
1363 // additional positional parameters are provided to trigger as an
1364 // Array, following the event type or event object, but are
1365 // provided to the .bind event handler as *args.
1366 // Convert our *args back into an Array in order to trigger them
1367 // on the group itself, so it can ultimately be forwarded wherever
1368 // it's supposed to go.
1369 var args = Array.prototype.slice.call(arguments, 1);
1370 $this.trigger.call($this, e, args);
1373 render_dataset: function (dataset) {
1375 list = new instance.web.ListView.List(this, {
1376 options: this.options,
1377 columns: this.columns,
1379 records: this.records
1381 this.bind_child_events(list);
1383 var view = this.view,
1384 limit = view.limit(),
1385 d = new $.Deferred(),
1386 page = this.datagroup.openable ? this.page : view.page;
1388 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1389 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1390 //TODO xmo: investigate why we need to put the setTimeout
1391 $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1392 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1393 if (self.records.length) {
1394 self.records.reset(null, {silent: true});
1396 if (!self.datagroup.openable) {
1397 view.configure_pager(dataset);
1399 if (dataset.size() == records.length) {
1401 self.$row.find('td.oe-group-pagination').empty();
1403 var pages = Math.ceil(dataset.size() / limit);
1405 .find('.oe-pager-state')
1406 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1411 .find('button[data-pager-action=previous]')
1412 .attr('disabled', page === 0)
1414 .find('button[data-pager-action=next]')
1415 .attr('disabled', page === pages - 1);
1419 self.records.add(records, {silent: true});
1422 if (_.isEmpty(records)) {
1428 setup_resequence_rows: function (list, dataset) {
1429 // drag and drop enabled if list is not sorted and there is a
1430 // "sequence" column in the view.
1431 if ((dataset.sort && dataset.sort())
1432 || !_(this.columns).any(function (column) {
1433 return column.name === 'sequence'; })) {
1436 // ondrop, move relevant record & fix sequences
1437 list.$current.sortable({
1439 items: '> tr[data-id]',
1440 containment: 'parent',
1442 stop: function (event, ui) {
1443 var to_move = list.records.get(ui.item.data('id')),
1444 target_id = ui.item.prev().data('id'),
1445 from_index = list.records.indexOf(to_move),
1446 target = list.records.get(target_id);
1447 if (list.records.at(from_index - 1) == target) {
1451 list.records.remove(to_move);
1452 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1453 list.records.add(to_move, { at: to });
1455 // resequencing time!
1456 var record, index = to,
1457 // if drag to 1st row (to = 0), start sequencing from 0
1458 // (exclusive lower bound)
1459 seq = to ? list.records.at(to - 1).get('sequence') : 0;
1460 while (++seq, record = list.records.at(index++)) {
1461 // write are independent from one another, so we can just
1462 // launch them all at the same time and we don't really
1463 // give a fig about when they're done
1464 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1465 // Accounting > Taxes > Taxes, child tax accounts)
1466 // when synchronous (without setTimeout)
1467 (function (dataset, id, seq) {
1468 $.async_when().then(function () {
1469 dataset.write(id, {sequence: seq});
1471 }(dataset, record.get('id'), seq));
1472 record.set('sequence', seq);
1475 list.refresh_zebra();
1479 render: function (post_render) {
1481 var $element = $('<tbody>');
1482 this.elements = [$element[0]];
1484 this.datagroup.list(
1485 _(this.view.visible_columns).chain()
1486 .filter(function (column) { return column.tag === 'field' })
1487 .pluck('name').value(),
1489 $element[0].appendChild(
1490 self.render_groups(groups));
1491 if (post_render) { post_render(); }
1492 }, function (dataset) {
1493 self.render_dataset(dataset).then(function (list) {
1494 self.children[null] = list;
1496 [list.$current.replaceAll($element)[0]];
1497 self.setup_resequence_rows(list, dataset);
1498 if (post_render) { post_render(); }
1504 * Returns the ids of all selected records for this group, and the records
1507 get_selection: function () {
1508 var ids = [], records = [];
1511 .each(function (child) {
1512 var selection = child.get_selection();
1513 ids.push.apply(ids, selection.ids);
1514 records.push.apply(records, selection.records);
1517 return {ids: ids, records: records};
1519 on_records_reset: function () {
1521 $(this.elements).remove();
1523 get_records: function () {
1524 if (_(this.children).isEmpty()) {
1525 if (!this.datagroup.length) {
1529 count: this.datagroup.length,
1530 values: this.datagroup.aggregates
1533 return _(this.children).chain()
1534 .map(function (child) {
1535 return child.get_records();
1536 }).flatten().value();
1543 var Events = /** @lends Events# */{
1545 * @param {String} event event to listen to on the current object, null for all events
1546 * @param {Function} handler event handler to bind to the relevant event
1549 bind: function (event, handler) {
1550 var calls = this['_callbacks'] || (this._callbacks = {});
1552 if (event in calls) {
1553 calls[event].push(handler);
1555 calls[event] = [handler];
1560 * @param {String} event event to unbind on the current object
1561 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1564 unbind: function (event, handler) {
1565 var calls = this._callbacks || {};
1566 if (!(event in calls)) { return this; }
1568 delete calls[event];
1570 var handlers = calls[event];
1572 _(handlers).indexOf(handler),
1578 * @param {String} event
1581 trigger: function (event) {
1583 if (!(calls = this._callbacks)) { return this; }
1584 var callbacks = (calls[event] || []).concat(calls[null] || []);
1585 for(var i=0, length=callbacks.length; i<length; ++i) {
1586 callbacks[i].apply(this, arguments);
1591 var Record = instance.web.Class.extend(/** @lends Record# */{
1593 * @constructs Record
1594 * @extends instance.web.Class
1597 * @param {Object} [data]
1599 init: function (data) {
1600 this.attributes = data || {};
1603 * @param {String} key
1606 get: function (key) {
1607 return this.attributes[key];
1612 * @param {Object} [options]
1613 * @param {Boolean} [options.silent=false]
1616 set: function (key, value, options) {
1617 options = options || {};
1618 var old_value = this.attributes[key];
1619 if (old_value === value) {
1622 this.attributes[key] = value;
1623 if (!options.silent) {
1624 this.trigger('change:' + key, this, value, old_value);
1625 this.trigger('change', this, key, value, old_value);
1630 * Converts the current record to the format expected by form views:
1632 * .. code-block:: javascript
1641 * @returns {Object} record displayable in a form view
1643 toForm: function () {
1644 var form_data = {}, attrs = this.attributes;
1645 for(var k in attrs) {
1646 form_data[k] = {value: attrs[k]};
1649 return {data: form_data};
1652 * Converts the current record to a format expected by context evaluations
1653 * (identical to record.attributes, except m2o fields are their integer
1654 * value rather than a pair)
1656 toContext: function () {
1657 var output = {}, attrs = this.attributes;
1658 for(var k in attrs) {
1660 if (typeof val !== 'object') {
1662 } else if (val instanceof Array) {
1665 throw new Error("Can't convert value " + val + " to context");
1671 Record.include(Events);
1672 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1674 * Smarter collections, with events, very strongly inspired by Backbone's.
1676 * Using a "dumb" array of records makes synchronization between the
1679 * @constructs Collection
1680 * @extends instance.web.Class
1683 * @param {Array} [records] records to initialize the collection with
1684 * @param {Object} [options]
1686 init: function (records, options) {
1687 options = options || {};
1688 _.bindAll(this, '_onRecordEvent');
1693 this._key = options.key;
1694 this._parent = options.parent;
1701 * @param {Object|Array} record
1702 * @param {Object} [options]
1703 * @param {Number} [options.at]
1704 * @param {Boolean} [options.silent=false]
1707 add: function (record, options) {
1708 options = options || {};
1709 var records = record instanceof Array ? record : [record];
1711 for(var i=0, length=records.length; i<length; ++i) {
1712 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1713 instance_.bind(null, this._onRecordEvent);
1714 this._byId[instance_.get('id')] = instance_;
1715 if (options.at == undefined) {
1716 this.records.push(instance_);
1717 if (!options.silent) {
1718 this.trigger('add', this, instance_, this.records.length-1);
1721 var insertion_index = options.at + i;
1722 this.records.splice(insertion_index, 0, instance_);
1723 if (!options.silent) {
1724 this.trigger('add', this, instance_, insertion_index);
1733 * Get a record by its index in the collection, can also take a group if
1734 * the collection is not degenerate
1736 * @param {Number} index
1737 * @param {String} [group]
1738 * @returns {Record|undefined}
1740 at: function (index, group) {
1742 var groups = group.split('.');
1743 return this._proxies[groups[0]].at(index, groups.join('.'));
1745 return this.records[index];
1748 * Get a record by its database id
1750 * @param {Number} id
1751 * @returns {Record|undefined}
1753 get: function (id) {
1754 if (!_(this._proxies).isEmpty()) {
1756 _(this._proxies).detect(function (proxy) {
1757 return record = proxy.get(id);
1761 return this._byId[id];
1764 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1765 * the subtree's group
1767 * @param {String} section group path section
1768 * @returns {Collection}
1770 proxy: function (section) {
1771 return this._proxies[section] = new Collection(null, {
1774 }).bind(null, this._onRecordEvent);
1777 * @param {Array} [records]
1780 reset: function (records, options) {
1781 options = options || {};
1782 _(this._proxies).each(function (proxy) {
1786 _(this.records).invoke('unbind', null, this._onRecordEvent);
1793 if (!options.silent) {
1794 this.trigger('reset', this);
1799 * Removes the provided record from the collection
1801 * @param {Record} record
1804 remove: function (record) {
1805 var index = _(this.records).indexOf(record);
1807 _(this._proxies).each(function (proxy) {
1808 proxy.remove(record);
1813 record.unbind(null, this._onRecordEvent);
1814 this.records.splice(index, 1);
1815 delete this._byId[record.get('id')];
1817 this.trigger('remove', record, this);
1821 _onRecordEvent: function (event, record, options) {
1822 // don't propagate reset events
1823 if (event === 'reset') { return; }
1824 this.trigger.apply(this, arguments);
1827 // underscore-type methods
1828 each: function (callback) {
1829 for(var section in this._proxies) {
1830 if (this._proxies.hasOwnProperty(section)) {
1831 this._proxies[section].each(callback);
1834 for(var i=0; i<this.length; ++i) {
1835 callback(this.records[i]);
1838 map: function (callback) {
1840 this.each(function (record) {
1841 results.push(callback(record));
1845 pluck: function (fieldname) {
1846 return this.map(function (record) {
1847 return record.get(fieldname);
1850 indexOf: function (record) {
1851 return _(this.records).indexOf(record);
1854 Collection.include(Events);
1855 instance.web.list = {
1858 Collection: Collection
1861 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: