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,
27 * Core class for list-type displays.
29 * As a view, needs a number of view-related parameters to be correctly
30 * instantiated, provides options and overridable methods for behavioral
33 * See constructor parameters and method documentations for information on
34 * the default behaviors and possible options for the list view.
36 * @constructs instance.web.ListView
37 * @extends instance.web.View
39 * @param parent parent object
40 * @param {instance.web.DataSet} dataset the dataset the view should work with
41 * @param {String} view_id the listview's identifier, if any
42 * @param {Object} options A set of options used to configure the view
43 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
44 * @param {Boolean} [options.header=true] should the list's header be displayed
45 * @param {Boolean} [options.deletable=true] are the list rows deletable
46 * @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.
47 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
48 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
50 init: function(parent, dataset, view_id, options) {
53 this.set_default_options(_.extend({}, this.defaults, options || {}));
54 this.dataset = dataset;
55 this.model = dataset.model;
56 this.view_id = view_id;
57 this.previous_colspan = null;
63 this.records = new Collection();
65 this.set_groups(new (this.options.GroupsType)(this));
67 if (this.dataset instanceof instance.web.DataSetStatic) {
68 this.groups.datagroup = new StaticDataGroup(this.dataset);
70 this.groups.datagroup = new DataGroup(
73 dataset.get_context());
74 this.groups.datagroup.sort = this.dataset._sort;
78 this.records.bind('change', function (event, record, key) {
79 if (!_(self.aggregate_columns).chain()
80 .pluck('name').contains(key).value()) {
83 self.compute_aggregates();
88 this.on('view_loaded', self, self.load_list);
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_list``
144 * class on its root element and to perform an RPC load call.
146 * @returns {$.Deferred} loading promise
149 this.$el.addClass('oe_list');
150 return this._super();
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 load_list: function(data) {
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, this.grouped);
252 this.$el.html(QWeb.render(this._template, this));
253 this.$el.addClass(this.fields_view.arch.attrs['class']);
257 this.$el.find('.oe_list_record_selector').click(function(){
258 self.$el.find('.oe_list_record_selector input').prop('checked',
259 self.$el.find('.oe_list_record_selector').prop('checked') || false);
260 var selection = self.groups.get_selection();
261 $(self.groups).trigger(
262 'selected', [selection.ids, selection.records]);
266 this.$el.find('thead').delegate('th.oe_sortable[data-id]', 'click', function (e) {
269 self.dataset.sort($this.data('id'));
270 if($this.hasClass("sortdown") || $this.hasClass("sortup")) {
271 $this.toggleClass("sortdown").toggleClass("sortup");
273 $this.toggleClass("sortdown");
275 $this.siblings('.oe_sortable').removeClass("sortup sortdown");
277 self.reload_content();
281 if (!this.$buttons) {
282 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
283 if (this.options.$buttons) {
284 this.$buttons.appendTo(this.options.$buttons);
286 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
288 this.$buttons.find('.oe_list_add')
289 .click(this.proxy('do_add_record'))
290 .prop('disabled', this.grouped);
295 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
296 if (this.options.$buttons) {
297 this.$pager.appendTo(this.options.$pager);
299 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
303 .on('click', 'a[data-pager-action]', function () {
305 var max_page = Math.floor(self.dataset.size() / self.limit());
306 switch ($this.data('pager-action')) {
308 self.page = 0; break;
310 self.page = max_page - 1;
313 self.page += 1; break;
315 self.page -= 1; break;
318 self.page = max_page;
319 } else if (self.page > max_page) {
322 self.reload_content();
323 }).find('.oe_list_pager_state')
324 .click(function (e) {
328 var $select = $('<select>')
329 .appendTo($this.empty())
330 .click(function (e) {e.stopPropagation();})
331 .append('<option value="80">80</option>' +
332 '<option value="100">100</option>' +
333 '<option value="200">200</option>' +
334 '<option value="500">500</option>' +
335 '<option value="NaN">' + _t("Unlimited") + '</option>')
336 .change(function () {
337 var val = parseInt($select.val(), 10);
338 self._limit = (isNaN(val) ? null : val);
340 self.reload_content();
342 $(this).trigger('change');
344 .val(self._limit || 'NaN');
349 if (!this.sidebar && this.options.$sidebar) {
350 this.sidebar = new instance.web.Sidebar(this);
351 this.sidebar.appendTo(this.options.$sidebar);
352 this.sidebar.add_items('other', _.compact([
353 { label: _t("Export"), callback: this.on_sidebar_export },
354 self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
356 this.sidebar.add_toolbar(this.fields_view.toolbar);
357 this.sidebar.$el.hide();
359 this.trigger('list_view_loaded', data, this.grouped);
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;
380 this.$pager.css("display", "");
381 this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
384 var range_start = this.page * limit + 1;
385 var range_stop = range_start - 1 + limit;
386 if (range_stop > total) {
389 spager = _.str.sprintf('%d-%d of %d', range_start, range_stop, total);
392 this.$pager.find('.oe_list_pager_state').text(spager);
395 * Sets up the listview's columns: merges view and fields data, move
396 * grouped-by columns to the front of the columns list and make them all
399 * @param {Object} fields fields_view_get's fields section
400 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
402 setup_columns: function (fields, grouped) {
403 var registry = instance.web.list.columns;
404 this.columns.splice(0, this.columns.length);
405 this.columns.push.apply(this.columns,
406 _(this.fields_view.arch.children).map(function (field) {
407 var id = field.attrs.name;
408 return registry.for_(id, fields[id], field);
411 this.columns.unshift(
412 new instance.web.list.MetaColumn('_group', _t("Group")));
415 this.visible_columns = _.filter(this.columns, function (column) {
416 return column.invisible !== '1';
419 this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
422 * Used to handle a click on a table row, if no other handler caught the
425 * The default implementation asks the list view's view manager to switch
426 * to a different view (by calling
427 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
428 * provided record index (within the current list view's dataset).
430 * If the index is null, ``switch_to_record`` asks for the creation of a
433 * @param {Number|void} index the record index (in the current dataset) to switch to
434 * @param {String} [view="page"] the view type to switch to
436 select_record:function (index, view) {
437 view = view || index == null ? 'form' : 'form';
438 this.dataset.index = index;
439 _.delay(_.bind(function () {
440 this.do_switch_view(view);
443 do_show: function () {
446 this.$buttons.show();
452 do_hide: function () {
454 this.sidebar.$el.hide();
457 this.$buttons.hide();
465 * Reloads the list view based on the current settings (dataset & al)
468 * @param {Boolean} [grouped] Should the list be displayed grouped
469 * @param {Object} [context] context to send the server while loading the view
471 reload_view: function (grouped, context, initial) {
472 return this.load_view(context);
475 * re-renders the content of the list view
477 * @returns {$.Deferred} promise to content reloading
479 reload_content: function () {
481 self.$el.find('.oe_list_record_selector').prop('checked', false);
482 this.records.reset();
483 var reloaded = $.Deferred();
484 this.$el.find('.oe_list_content').append(
485 this.groups.render(function () {
486 if (self.dataset.index == null) {
488 self.records.each(function () { has_one = true; });
490 self.dataset.index = 0;
493 self.compute_aggregates();
500 return reloaded.promise();
502 reload: function () {
503 return this.reload_content();
505 reload_record: function (record) {
506 return this.dataset.read_ids(
508 _.pluck(_(this.columns).filter(function (r) {
509 return r.tag === 'field';
511 ).done(function (records) {
512 _(records[0]).each(function (value, key) {
513 record.set(key, value, {silent: true});
515 record.trigger('change', record);
519 do_load_state: function(state, warm) {
521 if (state.page && this.page !== state.page) {
522 this.page = state.page;
526 if (_.isString(state.limit)) {
529 if (state.limit !== this._limit) {
530 this._limit = state.limit;
535 this.reload_content();
539 * Handler for the result of eval_domain_and_context, actually perform the
542 * @param {Object} results results of evaluating domain and process for a search
544 do_search: function (domain, context, group_by) {
546 this.groups.datagroup = new DataGroup(
547 this, this.model, domain, context, group_by);
548 this.groups.datagroup.sort = this.dataset._sort;
550 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
553 this.no_leaf = !!context['group_by_no_leaf'];
554 this.grouped = !!group_by;
556 return this.load_view(context).then(
557 this.proxy('reload_content'));
560 * Handles the signal to delete lines from the records list
562 * @param {Array} ids the ids of the records to delete
564 do_delete: function (ids) {
565 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
569 return $.when(this.dataset.unlink(ids)).done(function () {
570 _(ids).each(function (id) {
571 self.records.remove(self.records.get(id));
573 self.configure_pager(self.dataset);
574 self.compute_aggregates();
578 * Handles the signal indicating that a new record has been selected
580 * @param {Array} ids selected record ids
581 * @param {Array} records selected record values
583 do_select: function (ids, records) {
585 this.dataset.index = 0;
587 this.sidebar.$el.hide();
589 this.compute_aggregates();
593 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
595 this.sidebar.$el.show();
598 this.compute_aggregates(_(records).map(function (record) {
599 return {count: 1, values: record};
603 * Handles action button signals on a record
605 * @param {String} name action name
606 * @param {Object} id id of the record the action should be called on
607 * @param {Function} callback should be called after the action is executed, if non-null
609 do_button_action: function (name, id, callback) {
610 this.handle_button(name, id, callback);
613 * Base handling of buttons, can be called when overriding do_button_action
614 * in order to bypass parent overrides.
616 * The callback will be provided with the ``id`` as its parameter, in case
617 * handle_button's caller had to alter the ``id`` (or even create one)
618 * while not being ``callback``'s creator.
620 * This method should not be overridden.
622 * @param {String} name action name
623 * @param {Object} id id of the record the action should be called on
624 * @param {Function} callback should be called after the action is executed, if non-null
626 handle_button: function (name, id, callback) {
627 var action = _.detect(this.columns, function (field) {
628 return field.name === name;
630 if (!action) { return; }
631 if ('confirm' in action && !window.confirm(action.confirm)) {
635 var c = new instance.web.CompoundContext();
636 c.set_eval_context(_.extend({
639 active_model: this.dataset.model
640 }, this.records.get(id).toContext()));
641 if (action.context) {
642 c.add(action.context);
645 this.do_execute_action(
646 action, this.dataset, id, _.bind(callback, null, id));
649 * Handles the activation of a record (clicking on it)
651 * @param {Number} index index of the record in the dataset
652 * @param {Object} id identifier of the activated record
653 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
655 do_activate_record: function (index, id, dataset, view) {
656 this.dataset.ids = dataset.ids;
657 this.select_record(index, view);
660 * Handles signal for the addition of a new record (can be a creation,
661 * can be the addition from a remote source, ...)
663 * The default implementation is to switch to a new record on the form view
665 do_add_record: function () {
666 this.select_record(null);
669 * Handles deletion of all selected lines
671 do_delete_selected: function () {
672 var ids = this.groups.get_selection().ids;
674 this.do_delete(this.groups.get_selection().ids);
676 this.do_warn(_t("Warning"), _t("You must select at least one record."));
680 * Computes the aggregates for the current list view, either on the
681 * records provided or on the records of the internal
682 * :js:class:`~instance.web.ListView.Group`, by calling
683 * :js:func:`~instance.web.ListView.group.get_records`.
685 * Then displays the aggregates in the table through
686 * :js:method:`~instance.web.ListView.display_aggregates`.
688 * @param {Array} [records]
690 compute_aggregates: function (records) {
691 var columns = _(this.aggregate_columns).filter(function (column) {
692 return column['function']; });
693 if (_.isEmpty(columns)) { return; }
695 if (_.isEmpty(records)) {
696 records = this.groups.get_records();
698 records = _(records).compact();
700 var count = 0, sums = {};
701 _(columns).each(function (column) {
702 switch (column['function']) {
704 sums[column.id] = -Infinity;
707 sums[column.id] = Infinity;
713 _(records).each(function (record) {
714 count += record.count || 1;
715 _(columns).each(function (column) {
716 var field = column.id,
717 value = record.values[field];
718 switch (column['function']) {
720 sums[field] += value;
723 sums[field] += record.count * value;
726 if (sums[field] > value) {
731 if (sums[field] < value) {
740 _(columns).each(function (column) {
741 var field = column.id;
742 switch (column['function']) {
744 aggregates[field] = {value: sums[field] / count};
747 aggregates[field] = {value: sums[field]};
751 this.display_aggregates(aggregates);
753 display_aggregates: function (aggregation) {
755 var $footer_cells = this.$el.find('.oe_list_footer');
756 _(this.aggregate_columns).each(function (column) {
757 if (!column['function']) {
761 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
762 .html(column.format(aggregation, { process_modifiers: false }));
765 get_selected_ids: function() {
766 var ids = this.groups.get_selection().ids;
770 * Adds padding columns at the start or end of all table rows (including
773 * @param {Number} count number of columns to add
774 * @param {Object} options
775 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
776 * @param {Object} [options.except] content row to not pad
778 pad_columns: function (count, options) {
779 options = options || {};
780 // padding for action/pager header
781 var $first_header = this.$el.find('thead tr:first th');
782 var colspan = $first_header.attr('colspan');
784 if (!this.previous_colspan) {
785 this.previous_colspan = colspan;
787 $first_header.attr('colspan', parseInt(colspan, 10) + count);
789 // Padding for column titles, footer and data rows
791 .find('.oe_list_header_columns, tr:not(thead tr)')
792 .not(options['except']);
793 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
794 if (options.position === 'before') {
795 $rows.prepend(newcols);
797 $rows.append(newcols);
801 * Removes all padding columns of the table
803 unpad_columns: function () {
804 this.$el.find('.oe_list_padding').remove();
805 if (this.previous_colspan) {
807 .find('thead tr:first th')
808 .attr('colspan', this.previous_colspan);
809 this.previous_colspan = null;
812 no_result: function () {
813 this.$el.find('.oe_view_nocontent').remove();
814 if (this.groups.group_by
815 || !this.options.action
816 || !this.options.action.help) {
819 this.$el.find('table:first').hide();
821 $('<div class="oe_view_nocontent">').html(this.options.action.help)
823 var create_nocontent = this.$buttons;
824 this.$el.find('.oe_view_nocontent').click(function() {
825 create_nocontent.effect('bounce', {distance: 18, times: 5}, 150);
829 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
831 * List display for the ListView, handles basic DOM events and transforms
832 * them in the relevant higher-level events, to which the list view (or
833 * other consumers) can subscribe.
835 * Events on this object are registered via jQuery.
840 * Triggered when a row is selected (using check boxes), provides an
841 * array of ids of all the selected records.
843 * Triggered when deletion buttons are hit, provide an array of ids of
844 * all the records being marked for suppression.
846 * Triggered when an action button is clicked, provides two parameters:
848 * * The name of the action to execute (as a string)
849 * * The id of the record to execute the action on
851 * Triggered when a row of the table is clicked, provides the index (in
852 * the rows array) and id of the selected record to the handle function.
854 * @constructs instance.web.ListView.List
855 * @extends instance.web.Class
857 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
859 init: function (group, opts) {
862 this.view = group.view;
863 this.session = this.view.session;
865 this.options = opts.options;
866 this.columns = opts.columns;
867 this.dataset = opts.dataset;
868 this.records = opts.records;
870 this.record_callbacks = {
871 'remove': function (event, record) {
872 var $row = self.$current.children(
873 '[data-id=' + record.get('id') + ']');
874 var index = $row.data('index');
877 'reset': function () { return self.on_records_reset(); },
878 'change': function (event, record, attribute, value, old_value) {
880 if (attribute === 'id') {
882 throw new Error("Setting 'id' attribute on existing record "
883 + JSON.stringify(record.attributes));
885 if (!_.contains(self.dataset.ids, value)) {
886 // add record to dataset if not already in (added by
888 self.dataset.ids.splice(
889 self.records.indexOf(record), 0, value);
891 // Set id on new record
892 $row = self.$current.children('[data-id=false]');
894 $row = self.$current.children(
895 '[data-id=' + record.get('id') + ']');
897 $row.replaceWith(self.render_record(record));
899 'add': function (ev, records, record, index) {
900 var $new_row = $(self.render_record(record));
903 $new_row.prependTo(self.$current);
905 var previous_record = records.at(index-1),
906 $previous_sibling = self.$current.children(
907 '[data-id=' + previous_record.get('id') + ']');
908 $new_row.insertAfter($previous_sibling);
912 _(this.record_callbacks).each(function (callback, event) {
913 this.records.bind(event, callback);
916 this.$current = $('<tbody>')
917 .delegate('th.oe_list_record_selector', 'click', function (e) {
919 var selection = self.get_selection();
921 'selected', [selection.ids, selection.records]);
923 .delegate('td.oe_list_record_delete button', 'click', function (e) {
925 var $row = $(e.target).closest('tr');
926 $(self).trigger('deleted', [[self.row_id($row)]]);
928 .delegate('td.oe_list_field_cell button', 'click', function (e) {
930 var $target = $(e.currentTarget),
931 field = $target.closest('td').data('field'),
932 $row = $target.closest('tr'),
933 record_id = self.row_id($row);
935 // note: $.data converts data to number if it's composed only
936 // of digits, nice when storing actual numbers, not nice when
937 // storing strings composed only of digits. Force the action
938 // name to be a string
939 $(self).trigger('action', [field.toString(), record_id, function (id) {
940 return self.reload_record(self.records.get(id));
943 .delegate('a', 'click', function (e) {
946 .delegate('tr', 'click', function (e) {
947 var row_id = self.row_id(e.currentTarget);
950 if (!self.dataset.select_id(row_id)) {
951 throw new Error("Could not find id in dataset");
957 row_clicked: function (e, view) {
960 [this.dataset.ids[this.dataset.index],
961 this.dataset, view]);
963 render_cell: function (record, column) {
965 if(column.type === 'reference') {
966 value = record.get(column.id);
968 // Ensure that value is in a reference "shape", otherwise we're
969 // going to loop on performing name_get after we've resolved (and
970 // set) a human-readable version. m2o does not have this issue
971 // because the non-human-readable is just a number, where the
972 // human-readable version is a pair
973 if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
974 // reference values are in the shape "$model,$id" (as a
975 // string), we need to split and name_get this pair in order
976 // to get a correctly displayable value in the field
977 var model = ref_match[1],
978 id = parseInt(ref_match[2], 10);
979 new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
980 if (!names.length) { return; }
981 record.set(column.id, names[0][1]);
984 } else if (column.type === 'many2one') {
985 value = record.get(column.id);
986 // m2o values are usually name_get formatted, [Number, String]
987 // pairs, but in some cases only the id is provided. In these
988 // cases, we need to perform a name_get call to fetch the actual
990 if (typeof value === 'number' || value instanceof Number) {
991 // fetch the name, set it on the record (in the right field)
992 // and let the various registered events handle refreshing the
994 new instance.web.DataSet(this.view, column.relation)
995 .name_get([value]).done(function (names) {
996 if (!names.length) { return; }
997 record.set(column.id, names[0]);
1000 } else if (column.type === 'many2many') {
1001 value = record.get(column.id);
1002 // non-resolved (string) m2m values are arrays
1003 if (value instanceof Array && !_.isEmpty(value)
1004 && !record.get(column.id + '__display')) {
1006 // they come in two shapes:
1007 if (value[0] instanceof Array) {
1008 var command = value[0];
1009 // 1. an array of m2m commands (usually (6, false, ids))
1010 if (command[0] !== 6) {
1011 throw new Error(_t("Unknown m2m command ") + command[0]);
1015 // 2. an array of ids
1018 new instance.web.Model(column.relation)
1019 .call('name_get', [ids]).done(function (names) {
1020 // FIXME: nth horrible hack in this poor listview
1021 record.set(column.id + '__display',
1022 _(names).pluck(1).join(', '));
1023 record.set(column.id, ids);
1026 record.set(column.id, false);
1029 return column.format(record.toForm().data, {
1030 model: this.dataset.model,
1031 id: record.get('id')
1034 render: function () {
1035 this.$current.empty().append(
1036 QWeb.render('ListView.rows', _.extend({
1037 render_cell: function () {
1038 return self.render_cell.apply(self, arguments); }
1040 this.pad_table_to(4);
1042 pad_table_to: function (count) {
1043 if (this.records.length >= count ||
1044 _(this.columns).any(function(column) { return column.meta; })) {
1048 if (this.options.selectable) {
1049 cells.push('<th class="oe_list_record_selector"></td>');
1051 _(this.columns).each(function(column) {
1052 if (column.invisible === '1') {
1055 if (column.tag === 'button') {
1056 cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
1058 cells.push('<td title="' + column.string + '"> </td>');
1061 if (this.options.deletable) {
1062 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1064 cells.unshift('<tr>');
1065 cells.push('</tr>');
1067 var row = cells.join('');
1069 .children('tr:not([data-id])').remove().end()
1070 .append(new Array(count - this.records.length + 1).join(row));
1073 * Gets the ids of all currently selected records, if any
1074 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1076 get_selection: function () {
1077 var result = {ids: [], records: []};
1078 if (!this.options.selectable) {
1081 var records = this.records;
1082 this.$current.find('th.oe_list_record_selector input:checked')
1083 .closest('tr').each(function () {
1084 var record = records.get($(this).data('id'));
1085 result.ids.push(record.get('id'));
1086 result.records.push(record.attributes);
1091 * Returns the identifier of the object displayed in the provided table
1094 * @param {Object} row the selected table row
1095 * @returns {Number|String} the identifier of the row's object
1097 row_id: function (row) {
1098 return $(row).data('id');
1101 * Death signal, cleans up list display
1103 on_records_reset: function () {
1104 _(this.record_callbacks).each(function (callback, event) {
1105 this.records.unbind(event, callback);
1107 if (!this.$current) { return; }
1108 this.$current.remove();
1110 get_records: function () {
1111 return this.records.map(function (record) {
1112 return {count: 1, values: record.attributes};
1116 * Reloads the provided record by re-reading its content from the server.
1118 * @param {Record} record
1119 * @returns {$.Deferred} promise to the finalization of the reloading
1121 reload_record: function (record) {
1122 return this.view.reload_record(record);
1125 * Renders a list record to HTML
1127 * @param {Record} record index of the record to render in ``this.rows``
1128 * @returns {String} QWeb rendering of the selected record
1130 render_record: function (record) {
1132 var index = this.records.indexOf(record);
1133 return QWeb.render('ListView.row', {
1134 columns: this.columns,
1135 options: this.options,
1137 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1139 render_cell: function () {
1140 return self.render_cell.apply(self, arguments); }
1144 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1145 passtrough_events: 'action deleted row_link',
1147 * Grouped display for the ListView. Handles basic DOM events and interacts
1148 * with the :js:class:`~DataGroup` bound to it.
1150 * Provides events similar to those of
1151 * :js:class:`~instance.web.ListView.List`
1153 * @constructs instance.web.ListView.Groups
1154 * @extends instance.web.Class
1156 * @param {instance.web.ListView} view
1157 * @param {Object} [options]
1158 * @param {Collection} [options.records]
1159 * @param {Object} [options.options]
1160 * @param {Array} [options.columns]
1162 init: function (view, options) {
1163 options = options || {};
1165 this.records = options.records || view.records;
1166 this.options = options.options || view.options;
1167 this.columns = options.columns || view.columns;
1168 this.datagroup = null;
1176 this.records.bind('reset', function () {
1177 return self.on_records_reset(); });
1179 make_fragment: function () {
1180 return document.createDocumentFragment();
1183 * Returns a DOM node after which a new tbody can be inserted, so that it
1184 * follows the provided row.
1186 * Necessary to insert the result of a new group or list view within an
1187 * existing groups render, without losing track of the groups's own
1190 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1191 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1193 point_insertion: function (row) {
1195 var red_letter_tboday = $row.closest('tbody')[0];
1197 var $next_siblings = $row.nextAll();
1198 if ($next_siblings.length) {
1199 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1201 $root_kanal.append($next_siblings);
1202 this.elements.splice(
1203 _.indexOf(this.elements, red_letter_tboday),
1207 return red_letter_tboday;
1209 make_paginator: function () {
1211 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1212 .click(function (e) {
1213 e.stopPropagation();
1216 self.$row.closest('tbody').next()
1217 .replaceWith(self.render());
1219 var $next = $('<button type="button" data-pager-action="next">></button>')
1220 .click(function (e) {
1221 e.stopPropagation();
1224 self.$row.closest('tbody').next()
1225 .replaceWith(self.render());
1227 this.$row.children().last()
1228 .addClass('oe_list_group_pagination')
1230 .append('<span class="oe_list_pager_state"></span>')
1233 open: function (point_insertion) {
1234 this.render().insertAfter(point_insertion);
1236 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1237 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1238 if (no_subgroups && records_terminated) {
1239 this.make_paginator();
1242 close: function () {
1243 this.$row.children().last().empty();
1244 this.records.reset();
1247 * Prefixes ``$node`` with floated spaces in order to indent it relative
1248 * to its own left margin/baseline
1250 * @param {jQuery} $node jQuery object to indent
1251 * @param {Number} level current nesting level, >= 1
1252 * @returns {jQuery} the indentation node created
1254 indent: function ($node, level) {
1256 .css({'float': 'left', 'white-space': 'pre'})
1257 .text(new Array(level).join(' '))
1260 render_groups: function (datagroups) {
1262 var placeholder = this.make_fragment();
1263 _(datagroups).each(function (group) {
1264 if (self.children[group.value]) {
1265 self.records.proxy(group.value).reset();
1266 delete self.children[group.value];
1268 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1269 records: self.records.proxy(group.value),
1270 options: self.options,
1271 columns: self.columns
1273 self.bind_child_events(child);
1274 child.datagroup = group;
1276 var $row = child.$row = $('<tr class="oe_group_header">');
1277 if (group.openable && group.length) {
1278 $row.click(function (e) {
1279 if (!$row.data('open')) {
1280 $row.data('open', true)
1281 .find('span.ui-icon')
1282 .removeClass('ui-icon-triangle-1-e')
1283 .addClass('ui-icon-triangle-1-s');
1284 child.open(self.point_insertion(e.currentTarget));
1286 $row.removeData('open')
1287 .find('span.ui-icon')
1288 .removeClass('ui-icon-triangle-1-s')
1289 .addClass('ui-icon-triangle-1-e');
1294 placeholder.appendChild($row[0]);
1296 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1297 // Don't fill this if group_by_no_leaf but no group_by
1298 if (group.grouped_on) {
1300 row_data[group.grouped_on] = group;
1301 var group_column = _(self.columns).detect(function (column) {
1302 return column.id === group.grouped_on; });
1303 if (! group_column) {
1304 throw new Error(_.str.sprintf(
1305 _t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
1310 group_label = group_column.format(row_data, {
1311 value_if_empty: _t("Undefined"),
1312 process_modifiers: false
1315 group_label = _.str.escapeHTML(row_data[group_column.id].value);
1317 // group_label is html-clean (through format or explicit
1318 // escaping if format failed), can inject straight into HTML
1319 $group_column.html(_.str.sprintf("%s (%d)",
1320 group_label, group.length));
1322 if (group.length && group.openable) {
1323 // Make openable if not terminal group & group_by_no_leaf
1324 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1326 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1327 // wonky background position to ensure nothing is displayed
1328 // there but the rest of the behavior is ui-icon's
1329 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1332 self.indent($group_column, group.level);
1334 if (self.options.selectable) {
1335 $row.append('<td>');
1337 _(self.columns).chain()
1338 .filter(function (column) { return column.invisible !== '1'; })
1339 .each(function (column) {
1341 // do not do anything
1342 } else if (column.id in group.aggregates) {
1344 r[column.id] = {value: group.aggregates[column.id]};
1345 $('<td class="oe_number">')
1346 .html(column.format(r, {process_modifiers: false}))
1349 $row.append('<td>');
1352 if (self.options.deletable) {
1353 $row.append('<td class="oe_list_group_pagination">');
1358 bind_child_events: function (child) {
1359 var $this = $(this),
1361 $(child).bind('selected', function (e) {
1362 // can have selections spanning multiple links
1363 var selection = self.get_selection();
1364 $this.trigger(e, [selection.ids, selection.records]);
1365 }).bind(this.passtrough_events, function (e) {
1366 // additional positional parameters are provided to trigger as an
1367 // Array, following the event type or event object, but are
1368 // provided to the .bind event handler as *args.
1369 // Convert our *args back into an Array in order to trigger them
1370 // on the group itself, so it can ultimately be forwarded wherever
1371 // it's supposed to go.
1372 var args = Array.prototype.slice.call(arguments, 1);
1373 $this.trigger.call($this, e, args);
1376 render_dataset: function (dataset) {
1378 list = new (this.view.options.ListType)(this, {
1379 options: this.options,
1380 columns: this.columns,
1382 records: this.records
1384 this.bind_child_events(list);
1386 var view = this.view,
1387 limit = view.limit(),
1388 d = new $.Deferred(),
1389 page = this.datagroup.openable ? this.page : view.page;
1391 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1392 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1393 //TODO xmo: investigate why we need to put the setTimeout
1394 $.async_when().done(function() {
1395 dataset.read_slice(fields, options).done(function (records) {
1396 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1397 if (self.records.length) {
1398 self.records.reset(null, {silent: true});
1400 if (!self.datagroup.openable) {
1401 view.configure_pager(dataset);
1403 if (dataset.size() == records.length) {
1405 self.$row.find('td.oe_list_group_pagination').empty();
1407 var pages = Math.ceil(dataset.size() / limit);
1409 .find('.oe_list_pager_state')
1410 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1415 .find('button[data-pager-action=previous]')
1417 page === 0 ? 'hidden' : '')
1419 .find('button[data-pager-action=next]')
1421 page === pages - 1 ? 'hidden' : '');
1425 self.records.add(records, {silent: true});
1428 if (_.isEmpty(records)) {
1435 setup_resequence_rows: function (list, dataset) {
1436 // drag and drop enabled if list is not sorted and there is a
1437 // visible column with @widget=handle or "sequence" column in the view.
1438 if ((dataset.sort && dataset.sort())
1439 || !_(this.columns).any(function (column) {
1440 return column.widget === 'handle'
1441 || column.name === 'sequence'; })) {
1444 var sequence_field = _(this.columns).find(function (c) {
1445 return c.widget === 'handle';
1447 var seqname = sequence_field ? sequence_field.name : 'sequence';
1449 // ondrop, move relevant record & fix sequences
1450 list.$current.sortable({
1452 items: '> tr[data-id]',
1455 if (sequence_field) {
1456 list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1458 list.$current.sortable('option', {
1459 start: function (e, ui) {
1460 ui.placeholder.height(ui.item.height());
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(seqname) : 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().done(function () {
1490 attrs[seqname] = seq;
1491 dataset.write(id, attrs);
1493 }(dataset, record.get('id'), seq));
1494 record.set(seqname, seq);
1499 render: function (post_render) {
1501 var $el = $('<tbody>');
1502 this.elements = [$el[0]];
1504 this.datagroup.list(
1505 _(this.view.visible_columns).chain()
1506 .filter(function (column) { return column.tag === 'field' })
1507 .pluck('name').value(),
1510 self.render_groups(groups));
1511 if (post_render) { post_render(); }
1512 }, function (dataset) {
1513 self.render_dataset(dataset).done(function (list) {
1514 self.children[null] = list;
1516 [list.$current.replaceAll($el)[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();
1560 var DataGroup = instance.web.CallbackEnabled.extend({
1561 init: function(parent, model, domain, context, group_by, level) {
1562 this._super(parent, null);
1563 this.model = new instance.web.Model(model, context, domain);
1564 this.group_by = group_by;
1565 this.context = context;
1566 this.domain = domain;
1568 this.level = level || 0;
1570 list: function (fields, ifGroups, ifRecords) {
1572 var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
1573 $.when(query).done(function (querygroups) {
1576 var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
1577 ds._sort = self.sort;
1582 var child_datagroups = _(querygroups).map(function (group) {
1583 var child_context = _.extend(
1584 {}, self.model.context(), group.model.context());
1585 var child_dg = new DataGroup(
1586 self, self.model.name, group.model.domain(),
1587 child_context, group.model._context.group_by,
1589 child_dg.sort = self.sort;
1590 // copy querygroup properties
1591 child_dg.__context = child_context;
1592 child_dg.__domain = group.model.domain();
1593 child_dg.folded = group.get('folded');
1594 child_dg.grouped_on = group.get('grouped_on');
1595 child_dg.length = group.get('length');
1596 child_dg.value = group.get('value');
1597 child_dg.openable = group.get('has_children');
1598 child_dg.aggregates = group.get('aggregates');
1601 ifGroups(child_datagroups);
1605 var StaticDataGroup = DataGroup.extend({
1606 init: function (dataset) {
1607 this.dataset = dataset;
1609 list: function (fields, ifGroups, ifRecords) {
1610 ifRecords(this.dataset);
1617 var Events = /** @lends Events# */{
1619 * @param {String} event event to listen to on the current object, null for all events
1620 * @param {Function} handler event handler to bind to the relevant event
1623 bind: function (event, handler) {
1624 var calls = this['_callbacks'] || (this._callbacks = {});
1626 if (event in calls) {
1627 calls[event].push(handler);
1629 calls[event] = [handler];
1634 * @param {String} event event to unbind on the current object
1635 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1638 unbind: function (event, handler) {
1639 var calls = this._callbacks || {};
1640 if (!(event in calls)) { return this; }
1642 delete calls[event];
1644 var handlers = calls[event];
1646 _(handlers).indexOf(handler),
1652 * @param {String} event
1655 trigger: function (event) {
1657 if (!(calls = this._callbacks)) { return this; }
1658 var callbacks = (calls[event] || []).concat(calls[null] || []);
1659 for(var i=0, length=callbacks.length; i<length; ++i) {
1660 callbacks[i].apply(this, arguments);
1665 var Record = instance.web.Class.extend(/** @lends Record# */{
1667 * @constructs Record
1668 * @extends instance.web.Class
1671 * @param {Object} [data]
1673 init: function (data) {
1674 this.attributes = data || {};
1677 * @param {String} key
1680 get: function (key) {
1681 return this.attributes[key];
1686 * @param {Object} [options]
1687 * @param {Boolean} [options.silent=false]
1690 set: function (key, value, options) {
1691 options = options || {};
1692 var old_value = this.attributes[key];
1693 if (old_value === value) {
1696 this.attributes[key] = value;
1697 if (!options.silent) {
1698 this.trigger('change:' + key, this, value, old_value);
1699 this.trigger('change', this, key, value, old_value);
1704 * Converts the current record to the format expected by form views:
1706 * .. code-block:: javascript
1715 * @returns {Object} record displayable in a form view
1717 toForm: function () {
1718 var form_data = {}, attrs = this.attributes;
1719 for(var k in attrs) {
1720 form_data[k] = {value: attrs[k]};
1723 return {data: form_data};
1726 * Converts the current record to a format expected by context evaluations
1727 * (identical to record.attributes, except m2o fields are their integer
1728 * value rather than a pair)
1730 toContext: function () {
1731 var output = {}, attrs = this.attributes;
1732 for(var k in attrs) {
1734 if (typeof val !== 'object') {
1736 } else if (val instanceof Array) {
1739 throw new Error("Can't convert value " + val + " to context");
1745 Record.include(Events);
1746 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1748 * Smarter collections, with events, very strongly inspired by Backbone's.
1750 * Using a "dumb" array of records makes synchronization between the
1753 * @constructs Collection
1754 * @extends instance.web.Class
1757 * @param {Array} [records] records to initialize the collection with
1758 * @param {Object} [options]
1760 init: function (records, options) {
1761 options = options || {};
1762 _.bindAll(this, '_onRecordEvent');
1767 this._key = options.key;
1768 this._parent = options.parent;
1775 * @param {Object|Array} record
1776 * @param {Object} [options]
1777 * @param {Number} [options.at]
1778 * @param {Boolean} [options.silent=false]
1781 add: function (record, options) {
1782 options = options || {};
1783 var records = record instanceof Array ? record : [record];
1785 for(var i=0, length=records.length; i<length; ++i) {
1786 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1787 instance_.bind(null, this._onRecordEvent);
1788 this._byId[instance_.get('id')] = instance_;
1789 if (options.at == undefined) {
1790 this.records.push(instance_);
1791 if (!options.silent) {
1792 this.trigger('add', this, instance_, this.records.length-1);
1795 var insertion_index = options.at + i;
1796 this.records.splice(insertion_index, 0, instance_);
1797 if (!options.silent) {
1798 this.trigger('add', this, instance_, insertion_index);
1807 * Get a record by its index in the collection, can also take a group if
1808 * the collection is not degenerate
1810 * @param {Number} index
1811 * @param {String} [group]
1812 * @returns {Record|undefined}
1814 at: function (index, group) {
1816 var groups = group.split('.');
1817 return this._proxies[groups[0]].at(index, groups.join('.'));
1819 return this.records[index];
1822 * Get a record by its database id
1824 * @param {Number} id
1825 * @returns {Record|undefined}
1827 get: function (id) {
1828 if (!_(this._proxies).isEmpty()) {
1830 _(this._proxies).detect(function (proxy) {
1831 return record = proxy.get(id);
1835 return this._byId[id];
1838 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1839 * the subtree's group
1841 * @param {String} section group path section
1842 * @returns {Collection}
1844 proxy: function (section) {
1845 return this._proxies[section] = new Collection(null, {
1848 }).bind(null, this._onRecordEvent);
1851 * @param {Array} [records]
1854 reset: function (records, options) {
1855 options = options || {};
1856 _(this._proxies).each(function (proxy) {
1860 _(this.records).invoke('unbind', null, this._onRecordEvent);
1867 if (!options.silent) {
1868 this.trigger('reset', this);
1873 * Removes the provided record from the collection
1875 * @param {Record} record
1878 remove: function (record) {
1879 var index = this.indexOf(record);
1881 _(this._proxies).each(function (proxy) {
1882 proxy.remove(record);
1887 record.unbind(null, this._onRecordEvent);
1888 this.records.splice(index, 1);
1889 delete this._byId[record.get('id')];
1891 this.trigger('remove', record, this);
1895 _onRecordEvent: function (event) {
1897 // don't propagate reset events
1898 case 'reset': return;
1900 var record = arguments[1];
1901 var new_value = arguments[2];
1902 var old_value = arguments[3];
1903 // [change:id, record, new_value, old_value]
1904 if (this._byId[old_value] === record) {
1905 delete this._byId[old_value];
1906 this._byId[new_value] = record;
1910 this.trigger.apply(this, arguments);
1913 // underscore-type methods
1914 find: function (callback) {
1916 for(var section in this._proxies) {
1917 if (!this._proxies.hasOwnProperty(section)) {
1920 if ((record = this._proxies[section].find(callback))) {
1924 for(var i=0; i<this.length; ++i) {
1925 record = this.records[i];
1926 if (callback(record)) {
1931 each: function (callback) {
1932 for(var section in this._proxies) {
1933 if (this._proxies.hasOwnProperty(section)) {
1934 this._proxies[section].each(callback);
1937 for(var i=0; i<this.length; ++i) {
1938 callback(this.records[i]);
1941 map: function (callback) {
1943 this.each(function (record) {
1944 results.push(callback(record));
1948 pluck: function (fieldname) {
1949 return this.map(function (record) {
1950 return record.get(fieldname);
1953 indexOf: function (record) {
1954 return _(this.records).indexOf(record);
1956 succ: function (record, options) {
1957 options = options || {wraparound: false};
1959 for(var section in this._proxies) {
1960 if (!this._proxies.hasOwnProperty(section)) {
1963 if ((result = this._proxies[section].succ(record, options))) {
1967 var index = this.indexOf(record);
1968 if (index === -1) { return null; }
1969 var next_index = index + 1;
1970 if (options.wraparound && (next_index === this.length)) {
1973 return this.at(next_index);
1975 pred: function (record, options) {
1976 options = options || {wraparound: false};
1979 for (var section in this._proxies) {
1980 if (!this._proxies.hasOwnProperty(section)) {
1983 if ((result = this._proxies[section].pred(record, options))) {
1988 var index = this.indexOf(record);
1989 if (index === -1) { return null; }
1990 var next_index = index - 1;
1991 if (options.wraparound && (next_index === -1)) {
1992 return this.at(this.length - 1);
1994 return this.at(next_index);
1997 Collection.include(Events);
1998 instance.web.list = {
2001 Collection: Collection
2004 * Registry for column objects used to format table cells (and some other tasks
2005 * e.g. aggregation computations).
2007 * Maps a field or button to a Column type via its ``$tag.$widget``,
2008 * ``$tag.$type`` or its ``$tag`` (alone).
2010 * This specific registry has a dedicated utility method ``for_`` taking a
2011 * field (from fields_get/fields_view_get.field) and a node (from a view) and
2012 * returning the right object *already instantiated from the data provided*.
2014 * @type {instance.web.Registry}
2016 instance.web.list.columns = new instance.web.Registry({
2017 'field': 'instance.web.list.Column',
2018 'field.boolean': 'instance.web.list.Boolean',
2019 'field.binary': 'instance.web.list.Binary',
2020 'field.progressbar': 'instance.web.list.ProgressBar',
2021 'field.handle': 'instance.web.list.Handle',
2022 'button': 'instance.web.list.Button',
2023 'field.many2onebutton': 'instance.web.list.Many2OneButton',
2024 'field.many2many': 'instance.web.list.Many2Many'
2026 instance.web.list.columns.for_ = function (id, field, node) {
2027 var description = _.extend({tag: node.tag}, field, node.attrs);
2028 var tag = description.tag;
2029 var Type = this.get_any([
2030 tag + '.' + description.widget,
2031 tag + '.'+ description.type,
2034 return new Type(id, node.tag, description)
2037 instance.web.list.Column = instance.web.Class.extend({
2038 init: function (id, tag, attrs) {
2044 this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
2045 delete attrs.modifiers;
2046 _.extend(this, attrs);
2048 if (this.modifiers['tree_invisible']) {
2049 this.invisible = '1';
2050 } else { delete this.invisible; }
2052 modifiers_for: function (fields) {
2054 var domain_computer = instance.web.form.compute_domain;
2056 for (var attr in this.modifiers) {
2057 if (!this.modifiers.hasOwnProperty(attr)) { continue; }
2058 var modifier = this.modifiers[attr];
2059 out[attr] = _.isBoolean(modifier)
2061 : domain_computer(modifier, fields);
2066 to_aggregate: function () {
2067 if (this.type !== 'integer' && this.type !== 'float') {
2070 var aggregation_func = this['group_operator'] || 'sum';
2071 if (!(aggregation_func in this)) {
2074 var C = function (fn, label) {
2075 this['function'] = fn;
2079 return new C(aggregation_func, this[aggregation_func]);
2083 * @param row_data record whose values should be displayed in the cell
2084 * @param {Object} [options]
2085 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2086 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2087 * @param {String} [options.model] current record's model
2088 * @param {Number} [options.id] current record's id
2091 format: function (row_data, options) {
2092 options = options || {};
2094 if (options.process_modifiers !== false) {
2095 attrs = this.modifiers_for(row_data);
2097 if (attrs.invisible) { return ''; }
2099 if (!row_data[this.id]) {
2100 return options.value_if_empty === undefined
2102 : options.value_if_empty;
2104 return this._format(row_data, options);
2107 * Method to override in order to provide alternative HTML content for the
2108 * cell. Column._format will simply call ``instance.web.format_value`` and
2109 * escape the output.
2111 * The output of ``_format`` will *not* be escaped by ``format``, any
2112 * escaping *must be done* by ``format``.
2116 _format: function (row_data, options) {
2117 return _.escape(instance.web.format_value(
2118 row_data[this.id].value, this, options.value_if_empty));
2121 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2123 init: function (id, string) {
2124 this._super(id, '', {string: string});
2127 instance.web.list.Button = instance.web.list.Column.extend({
2129 * Return an actual ``<button>`` tag
2131 format: function (row_data, options) {
2132 options = options || {};
2134 if (options.process_modifiers !== false) {
2135 attrs = this.modifiers_for(row_data);
2137 if (attrs.invisible) { return ''; }
2139 return QWeb.render('ListView.row.button', {
2141 prefix: instance.session.prefix,
2142 disabled: attrs.readonly
2143 || isNaN(row_data.id.value)
2144 || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
2148 instance.web.list.Boolean = instance.web.list.Column.extend({
2150 * Return a potentially disabled checkbox input
2154 _format: function (row_data, options) {
2155 return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
2156 row_data[this.id].value ? 'checked="checked"' : '');
2159 instance.web.list.Binary = instance.web.list.Column.extend({
2161 * Return a link to the binary data as a file
2165 _format: function (row_data, options) {
2166 var text = _t("Download");
2167 var download_url = _.str.sprintf(
2168 '/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d',
2169 instance.session.session_id, options.model, this.id, options.id);
2170 if (this.filename) {
2171 download_url += '&filename_field=' + this.filename;
2172 if (row_data[this.filename]) {
2173 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2174 row_data[this.filename].value, {type: 'char'}));
2177 return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
2180 size: row_data[this.id].value
2184 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2186 * Return a formatted progress bar display
2190 _format: function (row_data, options) {
2192 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2193 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2197 instance.web.list.Handle = instance.web.list.Column.extend({
2199 this._super.apply(this, arguments);
2200 // Handle overrides the field to not be form-editable.
2201 this.modifiers.readonly = true;
2204 * Return styling hooks for a drag handle
2208 _format: function (row_data, options) {
2209 return '<div class="oe_list_handle">';
2212 instance.web.list.Many2OneButton = instance.web.list.Column.extend({
2213 _format: function (row_data, options) {
2214 this.has_value = !!row_data[this.id].value;
2215 return QWeb.render('Many2OneButton.cell', {'widget': this});
2218 instance.web.list.Many2Many = instance.web.list.Column.extend({
2219 _format: function (row_data, options) {
2220 if (!_.isEmpty(row_data[this.id].value)) {
2221 // If value, use __display version for printing
2222 row_data[this.id] = row_data[this.id + '__display'];
2224 return this._super(row_data, options);
2228 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: