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,
24 // if true, the view can't be editable, ignoring the view's and the context's
29 * Core class for list-type displays.
31 * As a view, needs a number of view-related parameters to be correctly
32 * instantiated, provides options and overridable methods for behavioral
35 * See constructor parameters and method documentations for information on
36 * the default behaviors and possible options for the list view.
38 * @constructs instance.web.ListView
39 * @extends instance.web.View
41 * @param parent parent object
42 * @param {instance.web.DataSet} dataset the dataset the view should work with
43 * @param {String} view_id the listview's identifier, if any
44 * @param {Object} options A set of options used to configure the view
45 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
46 * @param {Boolean} [options.header=true] should the list's header be displayed
47 * @param {Boolean} [options.deletable=true] are the list rows deletable
48 * @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.
49 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
50 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
52 init: function(parent, dataset, view_id, options) {
55 this.set_default_options(_.extend({}, this.defaults, options || {}));
56 this.dataset = dataset;
57 this.model = dataset.model;
58 this.view_id = view_id;
59 this.previous_colspan = null;
65 this.records = new Collection();
67 this.set_groups(new (this.options.GroupsType)(this));
69 if (this.dataset instanceof instance.web.DataSetStatic) {
70 this.groups.datagroup = new instance.web.StaticDataGroup(this.dataset);
72 this.groups.datagroup = new instance.web.DataGroup(
75 dataset.get_context());
76 this.groups.datagroup.sort = this.dataset._sort;
80 this.records.bind('change', function (event, record, key) {
81 if (!_(self.aggregate_columns).chain()
82 .pluck('name').contains(key).value()) {
85 self.compute_aggregates();
90 set_default_options: function (options) {
92 _.defaults(this.options, {
93 GroupsType: instance.web.ListView.Groups,
94 ListType: instance.web.ListView.List
99 * Retrieves the view's number of records per page (|| section)
101 * options > defaults > parent.action.limit > indefinite
103 * @returns {Number|null}
106 if (this._limit === undefined) {
107 this._limit = (this.options.limit
108 || this.defaults.limit
109 || (this.getParent().action || {}).limit
115 * Set a custom Group construct as the root of the List View.
117 * @param {instance.web.ListView.Groups} groups
119 set_groups: function (groups) {
122 $(this.groups).unbind("selected deleted action row_link");
126 this.groups = groups;
127 $(this.groups).bind({
128 'selected': function (e, ids, records) {
129 self.do_select(ids, records);
131 'deleted': function (e, ids) {
134 'action': function (e, action_name, id, callback) {
135 self.do_button_action(action_name, id, callback);
137 'row_link': function (e, id, dataset, view) {
138 self.do_activate_record(dataset.index, id, dataset, view);
143 * View startup method, the default behavior is to set the ``oe_listw``
144 * class on its root element and to perform an RPC load call.
146 * @returns {$.Deferred} loading promise
149 this.$element.addClass('oe_list');
150 return this.reload_view(null, null, true);
153 * Returns the style for the provided record in the current view (from the
154 * ``@colors`` and ``@fonts`` attributes)
156 * @param {Record} record record for the current row
157 * @returns {String} CSS style declaration
159 style_for: function (record) {
162 var context = _.extend({}, record.attributes, {
163 uid: this.session.uid,
164 current_date: new Date().toString('yyyy-MM-dd')
165 // TODO: time, datetime, relativedelta
169 for(var i=0, len=this.fonts.length; i<len; ++i) {
170 var pair = this.fonts[i],
172 expression = pair[1];
173 if (py.evaluate(expression, context).toJSON()) {
176 style += 'font-weight: bold;';
179 style += 'font-style: italic;';
182 style += 'text-decoration: underline;';
189 if (!this.colors) { return style; }
190 for(var i=0, len=this.colors.length; i<len; ++i) {
191 var pair = this.colors[i],
193 expression = pair[1];
194 if (py.evaluate(expression, context).toJSON()) {
195 return style += 'color: ' + color + ';';
197 // TODO: handle evaluation errors
202 * Called after loading the list view's description, sets up such things
203 * as the view table's columns, renders the table itself and hooks up the
204 * various table-level and row-level DOM events (action buttons, deletion
205 * buttons, selection of records, [New] button, selection of a given
208 * Sets up the following:
210 * * Processes arch and fields to generate a complete field descriptor for each field
211 * * Create the table itself and allocate visible columns
212 * * Hook in the top-level (header) [New|Add] and [Delete] button
213 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
214 * * Sets up event handlers for action buttons and per-row deletion button
215 * * Hooks global callback for clicking on a row
216 * * Sets up its sidebar, if any
218 * @param {Object} data wrapped fields_view_get result
219 * @param {Object} data.fields_view fields_view_get result (processed)
220 * @param {Object} data.fields_view.fields mapping of fields for the current model
221 * @param {Object} data.fields_view.arch current list view descriptor
222 * @param {Boolean} grouped Is the list view grouped
224 on_loaded: function(data, grouped) {
226 this.fields_view = data;
227 this.name = "" + this.fields_view.arch.attrs.string;
229 if (this.fields_view.arch.attrs.colors) {
230 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
232 .map(function(color_pair) {
233 var pair = color_pair.split(':'),
236 return [color, py.parse(py.tokenize(expr)), expr];
240 if (this.fields_view.arch.attrs.fonts) {
241 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
242 .map(function(font_pair) {
243 var pair = font_pair.split(':'),
246 return [font, py.parse(py.tokenize(expr)), expr];
250 this.setup_columns(this.fields_view.fields, grouped);
252 this.$element.html(QWeb.render(this._template, this));
253 this.$element.addClass(this.fields_view.arch.attrs['class']);
256 this.$element.find('.oe_list_record_selector').click(function(){
257 self.$element.find('.oe_list_record_selector input').prop('checked',
258 self.$element.find('.oe_list_record_selector').prop('checked') || false);
259 var selection = self.groups.get_selection();
260 $(self.groups).trigger(
261 'selected', [selection.ids, selection.records]);
265 this.$element.find('thead').delegate('th.oe_sortable[data-id]', 'click', function (e) {
268 self.dataset.sort($this.data('id'));
269 if($this.hasClass("sortdown") || $this.hasClass("sortup")) {
270 $this.toggleClass("sortdown").toggleClass("sortup");
272 $this.toggleClass("sortdown");
274 $this.siblings('.oe_sortable').removeClass("sortup sortdown");
276 self.reload_content();
279 // Add button and Import link
280 if (!this.$buttons) {
281 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
282 if (this.options.$buttons) {
283 this.$buttons.appendTo(this.options.$buttons);
285 this.$element.find('.oe_list_buttons').replaceWith(this.$buttons);
287 this.$buttons.find('.oe_list_add')
288 .click(this.proxy('do_add_record'))
289 .prop('disabled', grouped && this.options.editable);
290 this.$buttons.on('click', '.oe_list_button_import', function() {
291 self.on_sidebar_import();
298 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
299 if (this.options.$buttons) {
300 this.$pager.appendTo(this.options.$pager);
302 this.$element.find('.oe_list_pager').replaceWith(this.$pager);
306 .on('click', 'a[data-pager-action]', function () {
308 var max_page = Math.floor(self.dataset.size() / self.limit());
309 switch ($this.data('pager-action')) {
311 self.page = 0; break;
313 self.page = max_page - 1;
316 self.page += 1; break;
318 self.page -= 1; break;
321 self.page = max_page;
322 } else if (self.page > max_page) {
325 self.reload_content();
326 }).find('.oe_list_pager_state')
327 .click(function (e) {
331 var $select = $('<select>')
332 .appendTo($this.empty())
333 .click(function (e) {e.stopPropagation();})
334 .append('<option value="80">80</option>' +
335 '<option value="100">100</option>' +
336 '<option value="200">200</option>' +
337 '<option value="500">500</option>' +
338 '<option value="NaN">' + _t("Unlimited") + '</option>')
339 .change(function () {
340 var val = parseInt($select.val(), 10);
341 self._limit = (isNaN(val) ? null : val);
343 self.reload_content();
345 .val(self._limit || 'NaN');
350 if (!this.sidebar && this.options.$sidebar) {
351 this.sidebar = new instance.web.Sidebar(this);
352 this.sidebar.appendTo(this.options.$sidebar);
353 this.sidebar.add_items('other', [
354 { label: _t("Import"), callback: this.on_sidebar_import },
355 { label: _t("Export"), callback: this.on_sidebar_export },
356 { label: _t('Delete'), callback: this.do_delete_selected },
358 this.sidebar.add_toolbar(this.fields_view.toolbar);
362 * Configures the ListView pager based on the provided dataset's information
364 * Horrifying side-effect: sets the dataset's data on this.dataset?
366 * @param {instance.web.DataSet} dataset
368 configure_pager: function (dataset) {
369 this.dataset.ids = dataset.ids;
371 if (dataset._length) {
372 this.dataset._length = dataset._length;
375 var total = dataset.size();
376 var limit = this.limit() || total;
377 this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
380 var range_start = this.page * limit + 1;
381 var range_stop = range_start - 1 + limit;
382 if (range_stop > total) {
385 spager = _.str.sprintf('%d-%d of %d', range_start, range_stop, total);
388 this.$pager.find('.oe_list_pager_state').text(spager);
391 * Sets up the listview's columns: merges view and fields data, move
392 * grouped-by columns to the front of the columns list and make them all
395 * @param {Object} fields fields_view_get's fields section
396 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
398 setup_columns: function (fields, grouped) {
399 var domain_computer = instance.web.form.compute_domain;
401 var noop = function () { return {}; };
402 var field_to_column = function (field) {
403 var name = field.attrs.name;
404 var column = _.extend({id: name, tag: field.tag},
405 fields[name], field.attrs);
406 // modifiers computer
407 if (column.modifiers) {
408 var modifiers = JSON.parse(column.modifiers);
409 column.modifiers_for = function (fields) {
410 if (!modifiers.invisible) {
414 'invisible': domain_computer(modifiers.invisible, fields)
417 if (modifiers['tree_invisible']) {
418 column.invisible = '1';
420 delete column.invisible;
423 column.modifiers_for = noop;
428 this.columns.splice(0, this.columns.length);
429 this.columns.push.apply(
431 _(this.fields_view.arch.children).map(field_to_column));
433 this.columns.unshift({
434 id: '_group', tag: '', string: _t("Group"), meta: true,
435 modifiers_for: function () { return {}; }
437 id: '_count', tag: '', string: '#', meta: true,
438 modifiers_for: function () { return {}; }
442 this.visible_columns = _.filter(this.columns, function (column) {
443 return column.invisible !== '1';
446 this.aggregate_columns = _(this.visible_columns)
447 .map(function (column) {
448 if (column.type !== 'integer' && column.type !== 'float') {
451 var aggregation_func = column['group_operator'] || 'sum';
452 if (!(aggregation_func in column)) {
456 return _.extend({}, column, {
457 'function': aggregation_func,
458 label: column[aggregation_func]
463 * Used to handle a click on a table row, if no other handler caught the
466 * The default implementation asks the list view's view manager to switch
467 * to a different view (by calling
468 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
469 * provided record index (within the current list view's dataset).
471 * If the index is null, ``switch_to_record`` asks for the creation of a
474 * @param {Number|void} index the record index (in the current dataset) to switch to
475 * @param {String} [view="page"] the view type to switch to
477 select_record:function (index, view) {
478 view = view || index == null ? 'form' : 'form';
479 this.dataset.index = index;
480 _.delay(_.bind(function () {
481 this.do_switch_view(view);
484 do_show: function () {
487 this.sidebar.$element.show();
490 this.$buttons.show();
496 do_hide: function () {
498 this.sidebar.$element.hide();
501 this.$buttons.hide();
509 * Reloads the list view based on the current settings (dataset & al)
511 * @param {Boolean} [grouped] Should the list be displayed grouped
512 * @param {Object} [context] context to send the server while loading the view
514 reload_view: function (grouped, context, initial) {
516 var callback = function (field_view_get) {
517 self.on_loaded(field_view_get, grouped);
519 if (this.embedded_view) {
520 return $.Deferred().then(callback).resolve(this.embedded_view);
522 return this.rpc('/web/listview/load', {
524 view_id: this.view_id,
526 context: this.dataset.get_context(context),
527 toolbar: !!this.options.$sidebar
532 * re-renders the content of the list view
534 * @returns {$.Deferred} promise to content reloading
536 reload_content: function () {
538 self.$element.find('.oe_list_record_selector').prop('checked', false);
539 this.records.reset();
540 var reloaded = $.Deferred();
541 this.$element.find('.oe_list_content').append(
542 this.groups.render(function () {
543 if (self.dataset.index == null) {
545 self.records.each(function () { has_one = true; });
547 self.dataset.index = 0;
550 self.compute_aggregates();
557 return reloaded.promise();
559 reload: function () {
560 return this.reload_content();
562 reload_record: function (record) {
563 return this.dataset.read_ids(
565 _.pluck(_(this.columns).filter(function (r) {
566 return r.tag === 'field';
568 ).then(function (records) {
569 _(records[0]).each(function (value, key) {
570 record.set(key, value, {silent: true});
572 record.trigger('change', record);
576 do_load_state: function(state, warm) {
578 if (state.page && this.page !== state.page) {
579 this.page = state.page;
583 if (_.isString(state.limit)) {
586 if (state.limit !== this._limit) {
587 this._limit = state.limit;
592 this.reload_content();
596 * Handler for the result of eval_domain_and_context, actually perform the
599 * @param {Object} results results of evaluating domain and process for a search
601 do_search: function (domain, context, group_by) {
603 this.groups.datagroup = new instance.web.DataGroup(
604 this, this.model, domain, context, group_by);
605 this.groups.datagroup.sort = this.dataset._sort;
607 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
610 this.no_leaf = !!context['group_by_no_leaf'];
612 this.reload_view(!!group_by, context).then(
613 this.proxy('reload_content'));
616 * Handles the signal to delete lines from the records list
618 * @param {Array} ids the ids of the records to delete
620 do_delete: function (ids) {
621 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
625 return $.when(this.dataset.unlink(ids)).then(function () {
626 _(ids).each(function (id) {
627 self.records.remove(self.records.get(id));
629 self.configure_pager(self.dataset);
630 self.compute_aggregates();
634 * Handles the signal indicating that a new record has been selected
636 * @param {Array} ids selected record ids
637 * @param {Array} records selected record values
639 do_select: function (ids, records) {
641 this.dataset.index = 0;
643 this.sidebar.$element.hide();
645 this.compute_aggregates();
649 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
651 this.sidebar.$element.show();
654 this.compute_aggregates(_(records).map(function (record) {
655 return {count: 1, values: record};
659 * Handles action button signals on a record
661 * @param {String} name action name
662 * @param {Object} id id of the record the action should be called on
663 * @param {Function} callback should be called after the action is executed, if non-null
665 do_button_action: function (name, id, callback) {
666 var action = _.detect(this.columns, function (field) {
667 return field.name === name;
669 if (!action) { return; }
670 if ('confirm' in action && !window.confirm(action.confirm)) {
674 var c = new instance.web.CompoundContext();
675 c.set_eval_context(_.extend({
678 active_model: this.dataset.model
679 }, this.records.get(id).toContext()));
680 if (action.context) {
681 c.add(action.context);
684 this.do_execute_action(action, this.dataset, id, callback);
687 * Handles the activation of a record (clicking on it)
689 * @param {Number} index index of the record in the dataset
690 * @param {Object} id identifier of the activated record
691 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
693 do_activate_record: function (index, id, dataset, view) {
694 this.dataset.ids = dataset.ids;
695 this.select_record(index, view);
698 * Handles signal for the addition of a new record (can be a creation,
699 * can be the addition from a remote source, ...)
701 * The default implementation is to switch to a new record on the form view
703 do_add_record: function () {
704 this.select_record(null);
707 * Handles deletion of all selected lines
709 do_delete_selected: function () {
710 var ids = this.groups.get_selection().ids;
712 this.do_delete(this.groups.get_selection().ids);
714 this.do_warn(_t("Warning"), _t("You must select at least one record."));
718 * Computes the aggregates for the current list view, either on the
719 * records provided or on the records of the internal
720 * :js:class:`~instance.web.ListView.Group`, by calling
721 * :js:func:`~instance.web.ListView.group.get_records`.
723 * Then displays the aggregates in the table through
724 * :js:method:`~instance.web.ListView.display_aggregates`.
726 * @param {Array} [records]
728 compute_aggregates: function (records) {
729 var columns = _(this.aggregate_columns).filter(function (column) {
730 return column['function']; });
731 if (_.isEmpty(columns)) { return; }
733 if (_.isEmpty(records)) {
734 records = this.groups.get_records();
736 records = _(records).compact();
738 var count = 0, sums = {};
739 _(columns).each(function (column) {
740 switch (column['function']) {
742 sums[column.id] = -Infinity;
745 sums[column.id] = Infinity;
751 _(records).each(function (record) {
752 count += record.count || 1;
753 _(columns).each(function (column) {
754 var field = column.id,
755 value = record.values[field];
756 switch (column['function']) {
758 sums[field] += value;
761 sums[field] += record.count * value;
764 if (sums[field] > value) {
769 if (sums[field] < value) {
778 _(columns).each(function (column) {
779 var field = column.id;
780 switch (column['function']) {
782 aggregates[field] = {value: sums[field] / count};
785 aggregates[field] = {value: sums[field]};
789 this.display_aggregates(aggregates);
791 display_aggregates: function (aggregation) {
793 var $footer_cells = this.$element.find('.oe_list_footer');
794 _(this.aggregate_columns).each(function (column) {
795 if (!column['function']) {
799 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
800 .html(instance.web.format_cell(aggregation, column, {
801 process_modifiers: false
805 get_selected_ids: function() {
806 var ids = this.groups.get_selection().ids;
810 * Adds padding columns at the start or end of all table rows (including
813 * @param {Number} count number of columns to add
814 * @param {Object} options
815 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
816 * @param {Object} [options.except] content row to not pad
818 pad_columns: function (count, options) {
819 options = options || {};
820 // padding for action/pager header
821 var $first_header = this.$element.find('thead tr:first th');
822 var colspan = $first_header.attr('colspan');
824 if (!this.previous_colspan) {
825 this.previous_colspan = colspan;
827 $first_header.attr('colspan', parseInt(colspan, 10) + count);
829 // Padding for column titles, footer and data rows
830 var $rows = this.$element
831 .find('.oe_list_header_columns, tr:not(thead tr)')
832 .not(options['except']);
833 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
834 if (options.position === 'before') {
835 $rows.prepend(newcols);
837 $rows.append(newcols);
841 * Removes all padding columns of the table
843 unpad_columns: function () {
844 this.$element.find('.oe_list_padding').remove();
845 if (this.previous_colspan) {
847 .find('thead tr:first th')
848 .attr('colspan', this.previous_colspan);
849 this.previous_colspan = null;
852 no_result: function () {
853 this.$element.find('.oe_view_nocontent').remove();
854 if (this.groups.group_by
855 || !this.options.action
856 || !this.options.action.help) {
859 this.$element.find('table:first').hide();
860 this.$element.prepend(
861 $('<div class="oe_view_nocontent">')
862 .append($('<img>', { src: '/web/static/src/img/view_empty_arrow.png' }))
863 .append($('<div>').html(this.options.action.help))
867 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
869 * List display for the ListView, handles basic DOM events and transforms
870 * them in the relevant higher-level events, to which the list view (or
871 * other consumers) can subscribe.
873 * Events on this object are registered via jQuery.
878 * Triggered when a row is selected (using check boxes), provides an
879 * array of ids of all the selected records.
881 * Triggered when deletion buttons are hit, provide an array of ids of
882 * all the records being marked for suppression.
884 * Triggered when an action button is clicked, provides two parameters:
886 * * The name of the action to execute (as a string)
887 * * The id of the record to execute the action on
889 * Triggered when a row of the table is clicked, provides the index (in
890 * the rows array) and id of the selected record to the handle function.
892 * @constructs instance.web.ListView.List
893 * @extends instance.web.Class
895 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
897 init: function (group, opts) {
900 this.view = group.view;
901 this.session = this.view.session;
903 this.options = opts.options;
904 this.columns = opts.columns;
905 this.dataset = opts.dataset;
906 this.records = opts.records;
908 this.record_callbacks = {
909 'remove': function (event, record) {
910 var $row = self.$current.find(
911 '[data-id=' + record.get('id') + ']');
912 var index = $row.data('index');
914 self.refresh_zebra(index);
916 'reset': function () { return self.on_records_reset(); },
917 'change': function (event, record) {
918 var $row = self.$current.find('[data-id=' + record.get('id') + ']');
919 $row.replaceWith(self.render_record(record));
921 'add': function (ev, records, record, index) {
922 var $new_row = $('<tr>').attr({
923 'data-id': record.get('id')
927 $new_row.prependTo(self.$current);
929 var previous_record = records.at(index-1),
930 $previous_sibling = self.$current.find(
931 '[data-id=' + previous_record.get('id') + ']');
932 $new_row.insertAfter($previous_sibling);
935 self.refresh_zebra(index, 1);
938 _(this.record_callbacks).each(function (callback, event) {
939 this.records.bind(event, callback);
942 this.$_element = $('<tbody>')
943 .appendTo(document.body)
944 .delegate('th.oe_list_record_selector', 'click', function (e) {
946 var selection = self.get_selection();
948 'selected', [selection.ids, selection.records]);
950 .delegate('td.oe_list_record_delete button', 'click', function (e) {
952 var $row = $(e.target).closest('tr');
953 $(self).trigger('deleted', [[self.row_id($row)]]);
955 .delegate('td.oe_list_field_cell button', 'click', function (e) {
957 var $target = $(e.currentTarget),
958 field = $target.closest('td').data('field'),
959 $row = $target.closest('tr'),
960 record_id = self.row_id($row);
962 // note: $.data converts data to number if it's composed only
963 // of digits, nice when storing actual numbers, not nice when
964 // storing strings composed only of digits. Force the action
965 // name to be a string
966 $(self).trigger('action', [field.toString(), record_id, function () {
967 return self.reload_record(self.records.get(record_id));
970 .delegate('a', 'click', function (e) {
973 .delegate('tr', 'click', function (e) {
975 var row_id = self.row_id(e.currentTarget);
976 if (row_id !== undefined) {
977 if (!self.dataset.select_id(row_id)) {
978 throw "Could not find id in dataset"
984 row_clicked: function (e, view) {
987 [this.dataset.ids[this.dataset.index],
988 this.dataset, view]);
990 render_cell: function (record, column) {
992 if(column.type === 'reference') {
993 value = record.get(column.id);
995 // Ensure that value is in a reference "shape", otherwise we're
996 // going to loop on performing name_get after we've resolved (and
997 // set) a human-readable version. m2o does not have this issue
998 // because the non-human-readable is just a number, where the
999 // human-readable version is a pair
1000 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
1001 // reference values are in the shape "$model,$id" (as a
1002 // string), we need to split and name_get this pair in order
1003 // to get a correctly displayable value in the field
1004 var model = ref_match[1],
1005 id = parseInt(ref_match[2], 10);
1006 new instance.web.DataSet(this.view, model).name_get([id], function(names) {
1007 if (!names.length) { return; }
1008 record.set(column.id, names[0][1]);
1011 } else if (column.type === 'many2one') {
1012 value = record.get(column.id);
1013 // m2o values are usually name_get formatted, [Number, String]
1014 // pairs, but in some cases only the id is provided. In these
1015 // cases, we need to perform a name_get call to fetch the actual
1016 // displayable value
1017 if (typeof value === 'number' || value instanceof Number) {
1018 // fetch the name, set it on the record (in the right field)
1019 // and let the various registered events handle refreshing the
1021 new instance.web.DataSet(this.view, column.relation)
1022 .name_get([value], function (names) {
1023 if (!names.length) { return; }
1024 record.set(column.id, names[0]);
1028 return instance.web.format_cell(record.toForm().data, column, {
1029 model: this.dataset.model,
1030 id: record.get('id')
1033 render: function () {
1035 if (this.$current) {
1036 this.$current.remove();
1038 this.$current = this.$_element.clone(true);
1039 this.$current.empty().append(
1040 QWeb.render('ListView.rows', _.extend({
1041 render_cell: function () {
1042 return self.render_cell.apply(self, arguments); }
1044 this.pad_table_to(5);
1046 pad_table_to: function (count) {
1047 if (this.records.length >= count ||
1048 _(this.columns).any(function(column) { return column.meta; })) {
1052 if (this.options.selectable) {
1053 cells.push('<th class="oe_list_record_selector"></td>');
1055 _(this.columns).each(function(column) {
1056 if (column.invisible === '1') {
1059 if (column.tag === 'button') {
1060 cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
1062 cells.push('<td title="' + column.string + '"> </td>');
1065 if (this.options.deletable) {
1066 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1068 cells.unshift('<tr>');
1069 cells.push('</tr>');
1071 var row = cells.join('');
1073 .children('tr:not([data-id])').remove().end()
1074 .append(new Array(count - this.records.length + 1).join(row));
1075 this.refresh_zebra(this.records.length);
1078 * Gets the ids of all currently selected records, if any
1079 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1081 get_selection: function () {
1082 var result = {ids: [], records: []};
1083 if (!this.options.selectable) {
1086 var records = this.records;
1087 this.$current.find('th.oe_list_record_selector input:checked')
1088 .closest('tr').each(function () {
1089 var record = records.get($(this).data('id'));
1090 result.ids.push(record.get('id'));
1091 result.records.push(record.attributes);
1096 * Returns the identifier of the object displayed in the provided table
1099 * @param {Object} row the selected table row
1100 * @returns {Number|String} the identifier of the row's object
1102 row_id: function (row) {
1103 return $(row).data('id');
1106 * Death signal, cleans up list display
1108 on_records_reset: function () {
1109 _(this.record_callbacks).each(function (callback, event) {
1110 this.records.unbind(event, callback);
1112 if (!this.$current) { return; }
1113 this.$current.remove();
1114 this.$current = null;
1115 this.$_element.remove();
1117 get_records: function () {
1118 return this.records.map(function (record) {
1119 return {count: 1, values: record.attributes};
1123 * Reloads the provided record by re-reading its content from the server.
1125 * @param {Record} record
1126 * @returns {$.Deferred} promise to the finalization of the reloading
1128 reload_record: function (record) {
1129 return this.view.reload_record(record);
1132 * Renders a list record to HTML
1134 * @param {Record} record index of the record to render in ``this.rows``
1135 * @returns {String} QWeb rendering of the selected record
1137 render_record: function (record) {
1138 var index = this.records.indexOf(record);
1139 return QWeb.render('ListView.row', {
1140 columns: this.columns,
1141 options: this.options,
1143 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1145 render_cell: function () {
1146 return this.render_cell.apply(this, arguments); }
1150 * Fixes fixes the even/odd classes
1152 * @param {Number} [from_index] index from which to resequence
1153 * @param {Number} [offset = 0] selection offset for DOM, in case there are rows to ignore in the table
1155 refresh_zebra: function (from_index, offset) {
1156 offset = offset || 0;
1157 from_index = from_index || 0;
1158 var dom_offset = offset + from_index;
1159 var sel = dom_offset ? ':gt(' + (dom_offset - 1) + ')' : null;
1160 this.$current.children(sel).each(function (i, e) {
1161 var index = from_index + i;
1162 // reset record-index accelerators on rows and even/odd
1163 var even = index%2 === 0;
1164 $(e).toggleClass('even', even)
1165 .toggleClass('odd', !even);
1169 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1170 passtrough_events: 'action deleted row_link',
1172 * Grouped display for the ListView. Handles basic DOM events and interacts
1173 * with the :js:class:`~instance.web.DataGroup` bound to it.
1175 * Provides events similar to those of
1176 * :js:class:`~instance.web.ListView.List`
1178 * @constructs instance.web.ListView.Groups
1179 * @extends instance.web.Class
1181 * @param {instance.web.ListView} view
1182 * @param {Object} [options]
1183 * @param {Collection} [options.records]
1184 * @param {Object} [options.options]
1185 * @param {Array} [options.columns]
1187 init: function (view, options) {
1188 options = options || {};
1190 this.records = options.records || view.records;
1191 this.options = options.options || view.options;
1192 this.columns = options.columns || view.columns;
1193 this.datagroup = null;
1201 this.records.bind('reset', function () {
1202 return self.on_records_reset(); });
1204 make_fragment: function () {
1205 return document.createDocumentFragment();
1208 * Returns a DOM node after which a new tbody can be inserted, so that it
1209 * follows the provided row.
1211 * Necessary to insert the result of a new group or list view within an
1212 * existing groups render, without losing track of the groups's own
1215 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1216 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1218 point_insertion: function (row) {
1220 var red_letter_tboday = $row.closest('tbody')[0];
1222 var $next_siblings = $row.nextAll();
1223 if ($next_siblings.length) {
1224 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1226 $root_kanal.append($next_siblings);
1227 this.elements.splice(
1228 _.indexOf(this.elements, red_letter_tboday),
1232 return red_letter_tboday;
1234 make_paginator: function () {
1236 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1237 .click(function (e) {
1238 e.stopPropagation();
1241 self.$row.closest('tbody').next()
1242 .replaceWith(self.render());
1244 var $next = $('<button type="button" data-pager-action="next">></button>')
1245 .click(function (e) {
1246 e.stopPropagation();
1249 self.$row.closest('tbody').next()
1250 .replaceWith(self.render());
1252 this.$row.children().last()
1254 .append('<span class="oe_list_pager_state"></span>')
1257 open: function (point_insertion) {
1258 this.render().insertAfter(point_insertion);
1260 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1261 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1262 if (no_subgroups && records_terminated) {
1263 this.make_paginator();
1266 close: function () {
1267 this.$row.children().last().empty();
1268 this.records.reset();
1271 * Prefixes ``$node`` with floated spaces in order to indent it relative
1272 * to its own left margin/baseline
1274 * @param {jQuery} $node jQuery object to indent
1275 * @param {Number} level current nesting level, >= 1
1276 * @returns {jQuery} the indentation node created
1278 indent: function ($node, level) {
1280 .css({'float': 'left', 'white-space': 'pre'})
1281 .text(new Array(level).join(' '))
1284 render_groups: function (datagroups) {
1286 var placeholder = this.make_fragment();
1287 _(datagroups).each(function (group) {
1288 if (self.children[group.value]) {
1289 self.records.proxy(group.value).reset();
1290 delete self.children[group.value];
1292 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1293 records: self.records.proxy(group.value),
1294 options: self.options,
1295 columns: self.columns
1297 self.bind_child_events(child);
1298 child.datagroup = group;
1300 var $row = child.$row = $('<tr>');
1301 if (group.openable && group.length) {
1302 $row.click(function (e) {
1303 if (!$row.data('open')) {
1304 $row.data('open', true)
1305 .find('span.ui-icon')
1306 .removeClass('ui-icon-triangle-1-e')
1307 .addClass('ui-icon-triangle-1-s');
1308 child.open(self.point_insertion(e.currentTarget));
1310 $row.removeData('open')
1311 .find('span.ui-icon')
1312 .removeClass('ui-icon-triangle-1-s')
1313 .addClass('ui-icon-triangle-1-e');
1318 placeholder.appendChild($row[0]);
1320 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1321 // Don't fill this if group_by_no_leaf but no group_by
1322 if (group.grouped_on) {
1324 row_data[group.grouped_on] = group;
1325 var group_column = _(self.columns).detect(function (column) {
1326 return column.id === group.grouped_on; });
1328 $group_column.html(instance.web.format_cell(
1329 row_data, group_column, {
1330 value_if_empty: _t("Undefined"),
1331 process_modifiers: false
1334 $group_column.html(row_data[group_column.id].value);
1336 if (group.length && group.openable) {
1337 // Make openable if not terminal group & group_by_no_leaf
1338 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1340 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1341 // wonky background position to ensure nothing is displayed
1342 // there but the rest of the behavior is ui-icon's
1343 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1346 self.indent($group_column, group.level);
1348 $('<td>').text(group.length).appendTo($row);
1350 if (self.options.selectable) {
1351 $row.append('<td>');
1353 _(self.columns).chain()
1354 .filter(function (column) {return !column.invisible;})
1355 .each(function (column) {
1357 // do not do anything
1358 } else if (column.id in group.aggregates) {
1360 r[column.id] = {value: group.aggregates[column.id]};
1361 $('<td class="oe_number">')
1362 .html(instance.web.format_cell(
1363 r, column, {process_modifiers: false}))
1366 $row.append('<td>');
1369 if (self.options.deletable) {
1370 $row.append('<td class="oe_list_group_pagination">');
1375 bind_child_events: function (child) {
1376 var $this = $(this),
1378 $(child).bind('selected', function (e) {
1379 // can have selections spanning multiple links
1380 var selection = self.get_selection();
1381 $this.trigger(e, [selection.ids, selection.records]);
1382 }).bind(this.passtrough_events, function (e) {
1383 // additional positional parameters are provided to trigger as an
1384 // Array, following the event type or event object, but are
1385 // provided to the .bind event handler as *args.
1386 // Convert our *args back into an Array in order to trigger them
1387 // on the group itself, so it can ultimately be forwarded wherever
1388 // it's supposed to go.
1389 var args = Array.prototype.slice.call(arguments, 1);
1390 $this.trigger.call($this, e, args);
1393 render_dataset: function (dataset) {
1395 list = new (this.view.options.ListType)(this, {
1396 options: this.options,
1397 columns: this.columns,
1399 records: this.records
1401 this.bind_child_events(list);
1403 var view = this.view,
1404 limit = view.limit(),
1405 d = new $.Deferred(),
1406 page = this.datagroup.openable ? this.page : view.page;
1408 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1409 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1410 //TODO xmo: investigate why we need to put the setTimeout
1411 $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1412 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1413 if (self.records.length) {
1414 self.records.reset(null, {silent: true});
1416 if (!self.datagroup.openable) {
1417 view.configure_pager(dataset);
1419 if (dataset.size() == records.length) {
1421 self.$row.find('td.oe_list_group_pagination').empty();
1423 var pages = Math.ceil(dataset.size() / limit);
1425 .find('.oe_list_pager_state')
1426 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1431 .find('button[data-pager-action=previous]')
1432 .attr('disabled', page === 0)
1434 .find('button[data-pager-action=next]')
1435 .attr('disabled', page === pages - 1);
1439 self.records.add(records, {silent: true});
1442 if (_.isEmpty(records)) {
1448 setup_resequence_rows: function (list, dataset) {
1449 // drag and drop enabled if list is not sorted and there is a
1450 // "sequence" column in the view.
1451 if ((dataset.sort && dataset.sort())
1452 || !_(this.columns).any(function (column) {
1453 return column.name === 'sequence'; })) {
1456 // ondrop, move relevant record & fix sequences
1457 list.$current.sortable({
1459 items: '> tr[data-id]',
1460 containment: 'parent',
1462 stop: function (event, ui) {
1463 var to_move = list.records.get(ui.item.data('id')),
1464 target_id = ui.item.prev().data('id'),
1465 from_index = list.records.indexOf(to_move),
1466 target = list.records.get(target_id);
1467 if (list.records.at(from_index - 1) == target) {
1471 list.records.remove(to_move);
1472 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1473 list.records.add(to_move, { at: to });
1475 // resequencing time!
1476 var record, index = to,
1477 // if drag to 1st row (to = 0), start sequencing from 0
1478 // (exclusive lower bound)
1479 seq = to ? list.records.at(to - 1).get('sequence') : 0;
1480 while (++seq, record = list.records.at(index++)) {
1481 // write are independent from one another, so we can just
1482 // launch them all at the same time and we don't really
1483 // give a fig about when they're done
1484 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1485 // Accounting > Taxes > Taxes, child tax accounts)
1486 // when synchronous (without setTimeout)
1487 (function (dataset, id, seq) {
1488 $.async_when().then(function () {
1489 dataset.write(id, {sequence: seq});
1491 }(dataset, record.get('id'), seq));
1492 record.set('sequence', seq);
1495 list.refresh_zebra();
1499 render: function (post_render) {
1501 var $element = $('<tbody>');
1502 this.elements = [$element[0]];
1504 this.datagroup.list(
1505 _(this.view.visible_columns).chain()
1506 .filter(function (column) { return column.tag === 'field' })
1507 .pluck('name').value(),
1509 $element[0].appendChild(
1510 self.render_groups(groups));
1511 if (post_render) { post_render(); }
1512 }, function (dataset) {
1513 self.render_dataset(dataset).then(function (list) {
1514 self.children[null] = list;
1516 [list.$current.replaceAll($element)[0]];
1517 self.setup_resequence_rows(list, dataset);
1518 if (post_render) { post_render(); }
1524 * Returns the ids of all selected records for this group, and the records
1527 get_selection: function () {
1528 var ids = [], records = [];
1531 .each(function (child) {
1532 var selection = child.get_selection();
1533 ids.push.apply(ids, selection.ids);
1534 records.push.apply(records, selection.records);
1537 return {ids: ids, records: records};
1539 on_records_reset: function () {
1541 $(this.elements).remove();
1543 get_records: function () {
1544 if (_(this.children).isEmpty()) {
1545 if (!this.datagroup.length) {
1549 count: this.datagroup.length,
1550 values: this.datagroup.aggregates
1553 return _(this.children).chain()
1554 .map(function (child) {
1555 return child.get_records();
1556 }).flatten().value();
1563 var Events = /** @lends Events# */{
1565 * @param {String} event event to listen to on the current object, null for all events
1566 * @param {Function} handler event handler to bind to the relevant event
1569 bind: function (event, handler) {
1570 var calls = this['_callbacks'] || (this._callbacks = {});
1572 if (event in calls) {
1573 calls[event].push(handler);
1575 calls[event] = [handler];
1580 * @param {String} event event to unbind on the current object
1581 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1584 unbind: function (event, handler) {
1585 var calls = this._callbacks || {};
1586 if (!(event in calls)) { return this; }
1588 delete calls[event];
1590 var handlers = calls[event];
1592 _(handlers).indexOf(handler),
1598 * @param {String} event
1601 trigger: function (event) {
1603 if (!(calls = this._callbacks)) { return this; }
1604 var callbacks = (calls[event] || []).concat(calls[null] || []);
1605 for(var i=0, length=callbacks.length; i<length; ++i) {
1606 callbacks[i].apply(this, arguments);
1611 var Record = instance.web.Class.extend(/** @lends Record# */{
1613 * @constructs Record
1614 * @extends instance.web.Class
1617 * @param {Object} [data]
1619 init: function (data) {
1620 this.attributes = data || {};
1623 * @param {String} key
1626 get: function (key) {
1627 return this.attributes[key];
1632 * @param {Object} [options]
1633 * @param {Boolean} [options.silent=false]
1636 set: function (key, value, options) {
1637 options = options || {};
1638 var old_value = this.attributes[key];
1639 if (old_value === value) {
1642 this.attributes[key] = value;
1643 if (!options.silent) {
1644 this.trigger('change:' + key, this, value, old_value);
1645 this.trigger('change', this, key, value, old_value);
1650 * Converts the current record to the format expected by form views:
1652 * .. code-block:: javascript
1661 * @returns {Object} record displayable in a form view
1663 toForm: function () {
1664 var form_data = {}, attrs = this.attributes;
1665 for(var k in attrs) {
1666 form_data[k] = {value: attrs[k]};
1669 return {data: form_data};
1672 * Converts the current record to a format expected by context evaluations
1673 * (identical to record.attributes, except m2o fields are their integer
1674 * value rather than a pair)
1676 toContext: function () {
1677 var output = {}, attrs = this.attributes;
1678 for(var k in attrs) {
1680 if (typeof val !== 'object') {
1682 } else if (val instanceof Array) {
1685 throw new Error("Can't convert value " + val + " to context");
1691 Record.include(Events);
1692 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1694 * Smarter collections, with events, very strongly inspired by Backbone's.
1696 * Using a "dumb" array of records makes synchronization between the
1699 * @constructs Collection
1700 * @extends instance.web.Class
1703 * @param {Array} [records] records to initialize the collection with
1704 * @param {Object} [options]
1706 init: function (records, options) {
1707 options = options || {};
1708 _.bindAll(this, '_onRecordEvent');
1713 this._key = options.key;
1714 this._parent = options.parent;
1721 * @param {Object|Array} record
1722 * @param {Object} [options]
1723 * @param {Number} [options.at]
1724 * @param {Boolean} [options.silent=false]
1727 add: function (record, options) {
1728 options = options || {};
1729 var records = record instanceof Array ? record : [record];
1731 for(var i=0, length=records.length; i<length; ++i) {
1732 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1733 instance_.bind(null, this._onRecordEvent);
1734 this._byId[instance_.get('id')] = instance_;
1735 if (options.at == undefined) {
1736 this.records.push(instance_);
1737 if (!options.silent) {
1738 this.trigger('add', this, instance_, this.records.length-1);
1741 var insertion_index = options.at + i;
1742 this.records.splice(insertion_index, 0, instance_);
1743 if (!options.silent) {
1744 this.trigger('add', this, instance_, insertion_index);
1753 * Get a record by its index in the collection, can also take a group if
1754 * the collection is not degenerate
1756 * @param {Number} index
1757 * @param {String} [group]
1758 * @returns {Record|undefined}
1760 at: function (index, group) {
1762 var groups = group.split('.');
1763 return this._proxies[groups[0]].at(index, groups.join('.'));
1765 return this.records[index];
1768 * Get a record by its database id
1770 * @param {Number} id
1771 * @returns {Record|undefined}
1773 get: function (id) {
1774 if (!_(this._proxies).isEmpty()) {
1776 _(this._proxies).detect(function (proxy) {
1777 return record = proxy.get(id);
1781 return this._byId[id];
1784 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1785 * the subtree's group
1787 * @param {String} section group path section
1788 * @returns {Collection}
1790 proxy: function (section) {
1791 return this._proxies[section] = new Collection(null, {
1794 }).bind(null, this._onRecordEvent);
1797 * @param {Array} [records]
1800 reset: function (records, options) {
1801 options = options || {};
1802 _(this._proxies).each(function (proxy) {
1806 _(this.records).invoke('unbind', null, this._onRecordEvent);
1813 if (!options.silent) {
1814 this.trigger('reset', this);
1819 * Removes the provided record from the collection
1821 * @param {Record} record
1824 remove: function (record) {
1825 var index = _(this.records).indexOf(record);
1827 _(this._proxies).each(function (proxy) {
1828 proxy.remove(record);
1833 record.unbind(null, this._onRecordEvent);
1834 this.records.splice(index, 1);
1835 delete this._byId[record.get('id')];
1837 this.trigger('remove', record, this);
1841 _onRecordEvent: function (event, record, options) {
1842 // don't propagate reset events
1843 if (event === 'reset') { return; }
1844 this.trigger.apply(this, arguments);
1847 // underscore-type methods
1848 each: function (callback) {
1849 for(var section in this._proxies) {
1850 if (this._proxies.hasOwnProperty(section)) {
1851 this._proxies[section].each(callback);
1854 for(var i=0; i<this.length; ++i) {
1855 callback(this.records[i]);
1858 map: function (callback) {
1860 this.each(function (record) {
1861 results.push(callback(record));
1865 pluck: function (fieldname) {
1866 return this.map(function (record) {
1867 return record.get(fieldname);
1870 indexOf: function (record) {
1871 return _(this.records).indexOf(record);
1874 Collection.include(Events);
1875 instance.web.list = {
1878 Collection: Collection
1881 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: