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 // display an edit icon linking to form view
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 instance.web.ListView.Groups(this));
67 if (this.dataset instanceof instance.web.DataSetStatic) {
68 this.groups.datagroup = new instance.web.StaticDataGroup(this.dataset);
70 this.groups.datagroup = new instance.web.DataGroup(
73 dataset.get_context(),
75 this.groups.datagroup.sort = this.dataset._sort;
79 this.records.bind('change', function (event, record, key) {
80 if (!_(self.aggregate_columns).chain()
81 .pluck('name').contains(key).value()) {
84 self.compute_aggregates();
90 * Retrieves the view's number of records per page (|| section)
92 * options > defaults > parent.action.limit > indefinite
94 * @returns {Number|null}
97 if (this._limit === undefined) {
98 this._limit = (this.options.limit
99 || this.defaults.limit
100 || (this.getParent().action || {}).limit
106 * Set a custom Group construct as the root of the List View.
108 * @param {instance.web.ListView.Groups} groups
110 set_groups: function (groups) {
113 $(this.groups).unbind("selected deleted action row_link");
117 this.groups = groups;
118 $(this.groups).bind({
119 'selected': function (e, ids, records) {
120 self.do_select(ids, records);
122 'deleted': function (e, ids) {
125 'action': function (e, action_name, id, callback) {
126 self.do_button_action(action_name, id, callback);
128 'row_link': function (e, id, dataset, view) {
129 self.do_activate_record(dataset.index, id, dataset, view);
134 * View startup method, the default behavior is to set the ``oe-listview``
135 * class on its root element and to perform an RPC load call.
137 * @returns {$.Deferred} loading promise
140 this.$element.addClass('oe-listview');
141 return this.reload_view(null, null, true);
144 * Returns the style for the provided record in the current view (from the
145 * ``@colors`` and ``@fonts`` attributes)
147 * @param {Record} record record for the current row
148 * @returns {String} CSS style declaration
150 style_for: function (record) {
153 var context = _.extend({}, record.attributes, {
154 uid: this.session.uid,
155 current_date: new Date().toString('yyyy-MM-dd')
156 // TODO: time, datetime, relativedelta
160 for(var i=0, len=this.fonts.length; i<len; ++i) {
161 var pair = this.fonts[i],
163 expression = pair[1];
164 if (py.evaluate(expression, context).toJSON()) {
167 style += 'font-weight: bold;';
170 style += 'font-style: italic;';
173 style += 'text-decoration: underline;';
180 if (!this.colors) { return style; }
181 for(var i=0, len=this.colors.length; i<len; ++i) {
182 var pair = this.colors[i],
184 expression = pair[1];
185 if (py.evaluate(expression, context).toJSON()) {
186 return style += 'color: ' + color + ';';
188 // TODO: handle evaluation errors
193 * Called after loading the list view's description, sets up such things
194 * as the view table's columns, renders the table itself and hooks up the
195 * various table-level and row-level DOM events (action buttons, deletion
196 * buttons, selection of records, [New] button, selection of a given
199 * Sets up the following:
201 * * Processes arch and fields to generate a complete field descriptor for each field
202 * * Create the table itself and allocate visible columns
203 * * Hook in the top-level (header) [New|Add] and [Delete] button
204 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
205 * * Sets up event handlers for action buttons and per-row deletion button
206 * * Hooks global callback for clicking on a row
207 * * Sets up its sidebar, if any
209 * @param {Object} data wrapped fields_view_get result
210 * @param {Object} data.fields_view fields_view_get result (processed)
211 * @param {Object} data.fields_view.fields mapping of fields for the current model
212 * @param {Object} data.fields_view.arch current list view descriptor
213 * @param {Boolean} grouped Is the list view grouped
215 on_loaded: function(data, grouped) {
217 this.fields_view = data;
218 this.name = "" + this.fields_view.arch.attrs.string;
220 if (this.fields_view.arch.attrs.colors) {
221 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
223 .map(function(color_pair) {
224 var pair = color_pair.split(':'),
227 return [color, py.parse(py.tokenize(expr)), expr];
231 if (this.fields_view.arch.attrs.fonts) {
232 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
233 .map(function(font_pair) {
234 var pair = font_pair.split(':'),
237 return [font, py.parse(py.tokenize(expr)), expr];
241 this.setup_columns(this.fields_view.fields, grouped);
243 this.$element.html(QWeb.render(this._template, this));
246 this.$element.find('.all-record-selector').click(function(){
247 self.$element.find('.oe-record-selector input').prop('checked',
248 self.$element.find('.all-record-selector').prop('checked') || false);
249 var selection = self.groups.get_selection();
250 $(self.groups).trigger(
251 'selected', [selection.ids, selection.records]);
255 this.$element.find('thead').delegate('th.oe-sortable[data-id]', 'click', function (e) {
258 self.dataset.sort($this.data('id'));
259 if($this.hasClass("sortdown") || $this.hasClass("sortup")) {
260 $this.toggleClass("sortdown").toggleClass("sortup");
262 $this.toggleClass("sortdown");
264 $this.siblings('.oe-sortable').removeClass("sortup sortdown");
266 self.reload_content();
270 if (!this.$buttons) {
271 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
272 if (this.options.$buttons) {
273 this.$buttons.appendTo(this.options.$buttons);
275 this.$element.find('.oe_list_buttons').replaceWith(this.$buttons);
277 this.$buttons.find('.oe_list_add')
278 .click(this.proxy('do_add_record'))
279 .prop('disabled', grouped && this.options.editable)
281 .find('.oe_list_delete')
282 .click(this.proxy('do_delete_selected'))
283 .prop('disabled', true);
288 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
289 if (this.options.$buttons) {
290 this.$pager.appendTo(this.options.$pager);
292 this.$element.find('.oe_list_pager').replaceWith(this.$pager);
296 .on('click', 'a[data-pager-action]', function () {
298 var max_page = Math.floor(self.dataset.size() / self.limit());
299 switch ($this.data('pager-action')) {
301 self.page = 0; break;
303 self.page = max_page - 1;
306 self.page += 1; break;
308 self.page -= 1; break;
311 self.page = max_page;
312 } else if (self.page > max_page) {
315 self.reload_content();
316 }).find('.oe-pager-state')
317 .click(function (e) {
321 var $select = $('<select>')
322 .appendTo($this.empty())
323 .click(function (e) {e.stopPropagation();})
324 .append('<option value="80">80</option>' +
325 '<option value="100">100</option>' +
326 '<option value="200">200</option>' +
327 '<option value="500">500</option>' +
328 '<option value="NaN">' + _t("Unlimited") + '</option>')
329 .change(function () {
330 var val = parseInt($select.val(), 10);
331 self._limit = (isNaN(val) ? null : val);
333 self.reload_content();
335 .val(self._limit || 'NaN');
340 if (!this.sidebar && this.options.$sidebar) {
341 this.sidebar = new instance.web.Sidebar(this);
342 this.sidebar.appendTo(this.options.$sidebar);
343 this.sidebar.add_toolbar(this.fields_view.toolbar);
347 * Configures the ListView pager based on the provided dataset's information
349 * Horrifying side-effect: sets the dataset's data on this.dataset?
351 * @param {instance.web.DataSet} dataset
353 configure_pager: function (dataset) {
354 this.dataset.ids = dataset.ids;
356 if (dataset._length) {
357 this.dataset._length = dataset._length;
360 var page = this.page + 1,
361 total = Math.floor(dataset.size() / this.limit()) + 1;
363 this.$pager.find('.oe-pager-state').text(isNaN(total)
364 ? '-' : _.str.sprintf('%d / %d', page, total));
367 * Sets up the listview's columns: merges view and fields data, move
368 * grouped-by columns to the front of the columns list and make them all
371 * @param {Object} fields fields_view_get's fields section
372 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
374 setup_columns: function (fields, grouped) {
375 var domain_computer = instance.web.form.compute_domain;
377 var noop = function () { return {}; };
378 var field_to_column = function (field) {
379 var name = field.attrs.name;
380 var column = _.extend({id: name, tag: field.tag},
381 fields[name], field.attrs);
382 // modifiers computer
383 if (column.modifiers) {
384 var modifiers = JSON.parse(column.modifiers);
385 column.modifiers_for = function (fields) {
386 if (!modifiers.invisible) {
390 'invisible': domain_computer(modifiers.invisible, fields)
393 if (modifiers['tree_invisible']) {
394 column.invisible = '1';
396 delete column.invisible;
399 column.modifiers_for = noop;
404 this.columns.splice(0, this.columns.length);
405 this.columns.push.apply(
407 _(this.fields_view.arch.children).map(field_to_column));
409 this.columns.unshift({
410 id: '_group', tag: '', string: _t("Group"), meta: true,
411 modifiers_for: function () { return {}; }
413 id: '_count', tag: '', string: '#', meta: true,
414 modifiers_for: function () { return {}; }
418 this.visible_columns = _.filter(this.columns, function (column) {
419 return column.invisible !== '1';
422 this.aggregate_columns = _(this.visible_columns)
423 .map(function (column) {
424 if (column.type !== 'integer' && column.type !== 'float') {
427 var aggregation_func = column['group_operator'] || 'sum';
428 if (!(aggregation_func in column)) {
432 return _.extend({}, column, {
433 'function': aggregation_func,
434 label: column[aggregation_func]
439 * Used to handle a click on a table row, if no other handler caught the
442 * The default implementation asks the list view's view manager to switch
443 * to a different view (by calling
444 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
445 * provided record index (within the current list view's dataset).
447 * If the index is null, ``switch_to_record`` asks for the creation of a
450 * @param {Number|void} index the record index (in the current dataset) to switch to
451 * @param {String} [view="page"] the view type to switch to
453 select_record:function (index, view) {
454 view = view || index == null ? 'form' : 'form';
455 this.dataset.index = index;
456 _.delay(_.bind(function () {
457 this.do_switch_view(view);
460 do_show: function () {
463 this.sidebar.$element.show();
466 this.$buttons.show();
472 do_hide: function () {
474 this.sidebar.$element.hide();
477 this.$buttons.hide();
485 * Reloads the list view based on the current settings (dataset & al)
487 * @param {Boolean} [grouped] Should the list be displayed grouped
488 * @param {Object} [context] context to send the server while loading the view
490 reload_view: function (grouped, context, initial) {
492 var callback = function (field_view_get) {
493 self.on_loaded(field_view_get, grouped);
495 if (this.embedded_view) {
496 return $.Deferred().then(callback).resolve(this.embedded_view);
498 return this.rpc('/web/listview/load', {
500 view_id: this.view_id,
502 context: this.dataset.get_context(context),
503 toolbar: !!this.options.$sidebar
508 * re-renders the content of the list view
510 * @returns {$.Deferred} promise to content reloading
512 reload_content: function () {
514 self.$element.find('.all-record-selector').prop('checked', false);
515 this.records.reset();
516 var reloaded = $.Deferred();
517 this.$element.find('.oe-listview-content').append(
518 this.groups.render(function () {
519 if (self.dataset.index == null) {
521 self.records.each(function () { has_one = true; });
523 self.dataset.index = 0;
526 self.compute_aggregates();
533 return reloaded.promise();
535 reload: function () {
536 return this.reload_content();
538 do_load_state: function(state, warm) {
540 if (state.page && this.page !== state.page) {
541 this.page = state.page;
545 if (_.isString(state.limit)) {
548 if (state.limit !== this._limit) {
549 this._limit = state.limit;
554 this.reload_content();
558 * Handler for the result of eval_domain_and_context, actually perform the
561 * @param {Object} results results of evaluating domain and process for a search
563 do_search: function (domain, context, group_by) {
565 this.groups.datagroup = new instance.web.DataGroup(
566 this, this.model, domain, context, group_by);
567 this.groups.datagroup.sort = this.dataset._sort;
569 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
572 this.no_leaf = !!context['group_by_no_leaf'];
574 this.reload_view(!!group_by, context).then(
575 this.proxy('reload_content'));
578 * Handles the signal to delete lines from the records list
580 * @param {Array} ids the ids of the records to delete
582 do_delete: function (ids) {
583 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
587 return $.when(this.dataset.unlink(ids)).then(function () {
588 _(ids).each(function (id) {
589 self.records.remove(self.records.get(id));
591 self.configure_pager(self.dataset);
592 self.compute_aggregates();
596 * Handles the signal indicating that a new record has been selected
598 * @param {Array} ids selected record ids
599 * @param {Array} records selected record values
601 do_select: function (ids, records) {
602 this.$buttons.find('.oe_list_delete').attr('disabled', !ids.length);
604 this.dataset.index = 0;
606 this.sidebar.$element.hide();
608 this.compute_aggregates();
612 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
614 this.sidebar.$element.show();
617 this.compute_aggregates(_(records).map(function (record) {
618 return {count: 1, values: record};
622 * Handles action button signals on a record
624 * @param {String} name action name
625 * @param {Object} id id of the record the action should be called on
626 * @param {Function} callback should be called after the action is executed, if non-null
628 do_button_action: function (name, id, callback) {
629 var action = _.detect(this.columns, function (field) {
630 return field.name === name;
632 if (!action) { return; }
633 if ('confirm' in action && !window.confirm(action.confirm)) {
637 var c = new instance.web.CompoundContext();
638 c.set_eval_context(_.extend({
641 active_model: this.dataset.model
642 }, this.records.get(id).toContext()));
643 if (action.context) {
644 c.add(action.context);
647 this.do_execute_action(action, this.dataset, id, callback);
650 * Handles the activation of a record (clicking on it)
652 * @param {Number} index index of the record in the dataset
653 * @param {Object} id identifier of the activated record
654 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
656 do_activate_record: function (index, id, dataset, view) {
657 this.dataset.ids = dataset.ids;
658 this.select_record(index, view);
661 * Handles signal for the addition of a new record (can be a creation,
662 * can be the addition from a remote source, ...)
664 * The default implementation is to switch to a new record on the form view
666 do_add_record: function () {
667 this.select_record(null);
670 * Handles deletion of all selected lines
672 do_delete_selected: function () {
673 this.do_delete(this.groups.get_selection().ids);
676 * Computes the aggregates for the current list view, either on the
677 * records provided or on the records of the internal
678 * :js:class:`~instance.web.ListView.Group`, by calling
679 * :js:func:`~instance.web.ListView.group.get_records`.
681 * Then displays the aggregates in the table through
682 * :js:method:`~instance.web.ListView.display_aggregates`.
684 * @param {Array} [records]
686 compute_aggregates: function (records) {
687 var columns = _(this.aggregate_columns).filter(function (column) {
688 return column['function']; });
689 if (_.isEmpty(columns)) { return; }
691 if (_.isEmpty(records)) {
692 records = this.groups.get_records();
694 records = _(records).compact();
696 var count = 0, sums = {};
697 _(columns).each(function (column) {
698 switch (column['function']) {
700 sums[column.id] = -Infinity;
703 sums[column.id] = Infinity;
709 _(records).each(function (record) {
710 count += record.count || 1;
711 _(columns).each(function (column) {
712 var field = column.id,
713 value = record.values[field];
714 switch (column['function']) {
716 sums[field] += value;
719 sums[field] += record.count * value;
722 if (sums[field] > value) {
727 if (sums[field] < value) {
736 _(columns).each(function (column) {
737 var field = column.id;
738 switch (column['function']) {
740 aggregates[field] = {value: sums[field] / count};
743 aggregates[field] = {value: sums[field]};
747 this.display_aggregates(aggregates);
749 display_aggregates: function (aggregation) {
751 var $footer_cells = this.$element.find('.oe-list-footer');
752 _(this.aggregate_columns).each(function (column) {
753 if (!column['function']) {
757 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
758 .html(instance.web.format_cell(aggregation, column, {
759 process_modifiers: false
763 get_selected_ids: function() {
764 var ids = this.groups.get_selection().ids;
768 * Adds padding columns at the start or end of all table rows (including
771 * @param {Number} count number of columns to add
772 * @param {Object} options
773 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
774 * @param {Object} [options.except] content row to not pad
776 pad_columns: function (count, options) {
777 options = options || {};
778 // padding for action/pager header
779 var $first_header = this.$element.find('thead tr:first th');
780 var colspan = $first_header.attr('colspan');
782 if (!this.previous_colspan) {
783 this.previous_colspan = colspan;
785 $first_header.attr('colspan', parseInt(colspan, 10) + count);
787 // Padding for column titles, footer and data rows
788 var $rows = this.$element
789 .find('.oe-listview-header-columns, tr:not(thead tr)')
790 .not(options['except']);
791 var newcols = new Array(count+1).join('<td class="oe-listview-padding"></td>');
792 if (options.position === 'before') {
793 $rows.prepend(newcols);
795 $rows.append(newcols);
799 * Removes all padding columns of the table
801 unpad_columns: function () {
802 this.$element.find('.oe-listview-padding').remove();
803 if (this.previous_colspan) {
805 .find('thead tr:first th')
806 .attr('colspan', this.previous_colspan);
807 this.previous_colspan = null;
810 no_result: function () {
811 if (this.groups.group_by
812 || !this.options.action
813 || !this.options.action.help) {
816 this.$element.children('table').replaceWith(
817 $('<div class="oe_listview_nocontent">')
818 .append($('<img>', { src: '/web/static/src/img/list_empty_arrow.png' }))
819 .append($('<div>').html(this.options.action.help)));
822 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
824 * List display for the ListView, handles basic DOM events and transforms
825 * them in the relevant higher-level events, to which the list view (or
826 * other consumers) can subscribe.
828 * Events on this object are registered via jQuery.
833 * Triggered when a row is selected (using check boxes), provides an
834 * array of ids of all the selected records.
836 * Triggered when deletion buttons are hit, provide an array of ids of
837 * all the records being marked for suppression.
839 * Triggered when an action button is clicked, provides two parameters:
841 * * The name of the action to execute (as a string)
842 * * The id of the record to execute the action on
844 * Triggered when a row of the table is clicked, provides the index (in
845 * the rows array) and id of the selected record to the handle function.
847 * @constructs instance.web.ListView.List
848 * @extends instance.web.Class
850 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
852 init: function (group, opts) {
855 this.view = group.view;
856 this.session = this.view.session;
858 this.options = opts.options;
859 this.columns = opts.columns;
860 this.dataset = opts.dataset;
861 this.records = opts.records;
863 this.record_callbacks = {
864 'remove': function (event, record) {
865 var $row = self.$current.find(
866 '[data-id=' + record.get('id') + ']');
867 var index = $row.data('index');
869 self.refresh_zebra(index);
871 'reset': function () { return self.on_records_reset(); },
872 'change': function (event, record) {
873 var $row = self.$current.find('[data-id=' + record.get('id') + ']');
874 $row.replaceWith(self.render_record(record));
876 'add': function (ev, records, record, index) {
877 var $new_row = $('<tr>').attr({
878 'data-id': record.get('id')
882 $new_row.prependTo(self.$current);
884 var previous_record = records.at(index-1),
885 $previous_sibling = self.$current.find(
886 '[data-id=' + previous_record.get('id') + ']');
887 $new_row.insertAfter($previous_sibling);
890 self.refresh_zebra(index, 1);
893 _(this.record_callbacks).each(function (callback, event) {
894 this.records.bind(event, callback);
897 this.$_element = $('<tbody>')
898 .appendTo(document.body)
899 .delegate('th.oe-record-selector', 'click', function (e) {
901 var selection = self.get_selection();
903 'selected', [selection.ids, selection.records]);
905 .delegate('td.oe-record-delete button', 'click', function (e) {
907 var $row = $(e.target).closest('tr');
908 $(self).trigger('deleted', [[self.row_id($row)]]);
910 .delegate('td.oe-field-cell button', 'click', function (e) {
912 var $target = $(e.currentTarget),
913 field = $target.closest('td').data('field'),
914 $row = $target.closest('tr'),
915 record_id = self.row_id($row);
917 // note: $.data converts data to number if it's composed only
918 // of digits, nice when storing actual numbers, not nice when
919 // storing strings composed only of digits. Force the action
920 // name to be a string
921 $(self).trigger('action', [field.toString(), record_id, function () {
922 return self.reload_record(self.records.get(record_id));
925 .delegate('a', 'click', function (e) {
928 .delegate('tr', 'click', function (e) {
930 var row_id = self.row_id(e.currentTarget);
931 if (row_id !== undefined) {
932 if (!self.dataset.select_id(row_id)) {
933 throw "Could not find id in dataset"
936 if ($(e.target).is('.oe-record-edit-link-img')) {
939 self.row_clicked(e, view);
943 row_clicked: function (e, view) {
946 [this.dataset.ids[this.dataset.index],
947 this.dataset, view]);
949 render_cell: function (record, column) {
951 if(column.type === 'reference') {
952 value = record.get(column.id);
954 // Ensure that value is in a reference "shape", otherwise we're
955 // going to loop on performing name_get after we've resolved (and
956 // set) a human-readable version. m2o does not have this issue
957 // because the non-human-readable is just a number, where the
958 // human-readable version is a pair
959 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
960 // reference values are in the shape "$model,$id" (as a
961 // string), we need to split and name_get this pair in order
962 // to get a correctly displayable value in the field
963 var model = ref_match[1],
964 id = parseInt(ref_match[2], 10);
965 new instance.web.DataSet(this.view, model).name_get([id], function(names) {
966 if (!names.length) { return; }
967 record.set(column.id, names[0][1]);
970 } else if (column.type === 'many2one') {
971 value = record.get(column.id);
972 // m2o values are usually name_get formatted, [Number, String]
973 // pairs, but in some cases only the id is provided. In these
974 // cases, we need to perform a name_get call to fetch the actual
976 if (typeof value === 'number' || value instanceof Number) {
977 // fetch the name, set it on the record (in the right field)
978 // and let the various registered events handle refreshing the
980 new instance.web.DataSet(this.view, column.relation)
981 .name_get([value], function (names) {
982 if (!names.length) { return; }
983 record.set(column.id, names[0]);
987 return instance.web.format_cell(record.toForm().data, column, {
988 model: this.dataset.model,
992 render: function () {
995 this.$current.remove();
997 this.$current = this.$_element.clone(true);
998 this.$current.empty().append(
999 QWeb.render('ListView.rows', _.extend({
1000 render_cell: function () {
1001 return self.render_cell.apply(self, arguments); }
1003 this.pad_table_to(5);
1005 pad_table_to: function (count) {
1006 if (this.records.length >= count ||
1007 _(this.columns).any(function(column) { return column.meta; })) {
1011 if (this.options.selectable) {
1012 cells.push('<th class="oe-record-selector"></td>');
1014 if (this.options.isClarkGable) {
1015 cells.push('<th class="oe-record-edit-link"></td>');
1017 _(this.columns).each(function(column) {
1018 if (column.invisible === '1') {
1021 if (column.tag === 'button') {
1022 cells.push('<td class="oe-button" title="' + column.string + '"> </td>');
1024 cells.push('<td title="' + column.string + '"> </td>');
1027 if (this.options.deletable) {
1028 cells.push('<td class="oe-record-delete"><button type="button" style="visibility: hidden"> </button></td>');
1030 cells.unshift('<tr>');
1031 cells.push('</tr>');
1033 var row = cells.join('');
1035 .children('tr:not([data-id])').remove().end()
1036 .append(new Array(count - this.records.length + 1).join(row));
1037 this.refresh_zebra(this.records.length);
1040 * Gets the ids of all currently selected records, if any
1041 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1043 get_selection: function () {
1044 if (!this.options.selectable) {
1047 var records = this.records;
1048 var result = {ids: [], records: []};
1049 this.$current.find('th.oe-record-selector input:checked')
1050 .closest('tr').each(function () {
1051 var record = records.get($(this).data('id'));
1052 result.ids.push(record.get('id'));
1053 result.records.push(record.attributes);
1058 * Returns the identifier of the object displayed in the provided table
1061 * @param {Object} row the selected table row
1062 * @returns {Number|String} the identifier of the row's object
1064 row_id: function (row) {
1065 return $(row).data('id');
1068 * Death signal, cleans up list display
1070 on_records_reset: function () {
1071 _(this.record_callbacks).each(function (callback, event) {
1072 this.records.unbind(event, callback);
1074 if (!this.$current) { return; }
1075 this.$current.remove();
1076 this.$current = null;
1077 this.$_element.remove();
1079 get_records: function () {
1080 return this.records.map(function (record) {
1081 return {count: 1, values: record.attributes};
1085 * Reloads the provided record by re-reading its content from the server.
1087 * @param {Record} record
1088 * @returns {$.Deferred} promise to the finalization of the reloading
1090 reload_record: function (record) {
1091 return this.dataset.read_ids(
1093 _.pluck(_(this.columns).filter(function (r) {
1094 return r.tag === 'field';
1096 ).then(function (records) {
1097 _(records[0]).each(function (value, key) {
1098 record.set(key, value, {silent: true});
1100 record.trigger('change', record);
1104 * Renders a list record to HTML
1106 * @param {Record} record index of the record to render in ``this.rows``
1107 * @returns {String} QWeb rendering of the selected record
1109 render_record: function (record) {
1110 var index = this.records.indexOf(record);
1111 return QWeb.render('ListView.row', {
1112 columns: this.columns,
1113 options: this.options,
1115 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1117 render_cell: function () {
1118 return this.render_cell.apply(this, arguments); }
1122 * Fixes fixes the even/odd classes
1124 * @param {Number} [from_index] index from which to resequence
1125 * @param {Number} [offset = 0] selection offset for DOM, in case there are rows to ignore in the table
1127 refresh_zebra: function (from_index, offset) {
1128 offset = offset || 0;
1129 from_index = from_index || 0;
1130 var dom_offset = offset + from_index;
1131 var sel = dom_offset ? ':gt(' + (dom_offset - 1) + ')' : null;
1132 this.$current.children(sel).each(function (i, e) {
1133 var index = from_index + i;
1134 // reset record-index accelerators on rows and even/odd
1135 var even = index%2 === 0;
1136 $(e).toggleClass('even', even)
1137 .toggleClass('odd', !even);
1141 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1142 passtrough_events: 'action deleted row_link',
1144 * Grouped display for the ListView. Handles basic DOM events and interacts
1145 * with the :js:class:`~instance.web.DataGroup` bound to it.
1147 * Provides events similar to those of
1148 * :js:class:`~instance.web.ListView.List`
1150 * @constructs instance.web.ListView.Groups
1151 * @extends instance.web.Class
1153 * @param {instance.web.ListView} view
1154 * @param {Object} [options]
1155 * @param {Collection} [options.records]
1156 * @param {Object} [options.options]
1157 * @param {Array} [options.columns]
1159 init: function (view, options) {
1160 options = options || {};
1162 this.records = options.records || view.records;
1163 this.options = options.options || view.options;
1164 this.columns = options.columns || view.columns;
1165 this.datagroup = null;
1173 this.records.bind('reset', function () {
1174 return self.on_records_reset(); });
1176 make_fragment: function () {
1177 return document.createDocumentFragment();
1180 * Returns a DOM node after which a new tbody can be inserted, so that it
1181 * follows the provided row.
1183 * Necessary to insert the result of a new group or list view within an
1184 * existing groups render, without losing track of the groups's own
1187 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1188 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1190 point_insertion: function (row) {
1192 var red_letter_tboday = $row.closest('tbody')[0];
1194 var $next_siblings = $row.nextAll();
1195 if ($next_siblings.length) {
1196 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1198 $root_kanal.append($next_siblings);
1199 this.elements.splice(
1200 _.indexOf(this.elements, red_letter_tboday),
1204 return red_letter_tboday;
1206 make_paginator: function () {
1208 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1209 .click(function (e) {
1210 e.stopPropagation();
1213 self.$row.closest('tbody').next()
1214 .replaceWith(self.render());
1216 var $next = $('<button type="button" data-pager-action="next">></button>')
1217 .click(function (e) {
1218 e.stopPropagation();
1221 self.$row.closest('tbody').next()
1222 .replaceWith(self.render());
1224 this.$row.children().last()
1226 .append('<span class="oe-pager-state"></span>')
1229 open: function (point_insertion) {
1230 this.render().insertAfter(point_insertion);
1232 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1233 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1234 if (no_subgroups && records_terminated) {
1235 this.make_paginator();
1238 close: function () {
1239 this.$row.children().last().empty();
1240 this.records.reset();
1243 * Prefixes ``$node`` with floated spaces in order to indent it relative
1244 * to its own left margin/baseline
1246 * @param {jQuery} $node jQuery object to indent
1247 * @param {Number} level current nesting level, >= 1
1248 * @returns {jQuery} the indentation node created
1250 indent: function ($node, level) {
1252 .css({'float': 'left', 'white-space': 'pre'})
1253 .text(new Array(level).join(' '))
1256 render_groups: function (datagroups) {
1258 var placeholder = this.make_fragment();
1259 _(datagroups).each(function (group) {
1260 if (self.children[group.value]) {
1261 self.records.proxy(group.value).reset();
1262 delete self.children[group.value];
1264 var child = self.children[group.value] = new instance.web.ListView.Groups(self.view, {
1265 records: self.records.proxy(group.value),
1266 options: self.options,
1267 columns: self.columns
1269 self.bind_child_events(child);
1270 child.datagroup = group;
1272 var $row = child.$row = $('<tr>');
1273 if (group.openable && group.length) {
1274 $row.click(function (e) {
1275 if (!$row.data('open')) {
1276 $row.data('open', true)
1277 .find('span.ui-icon')
1278 .removeClass('ui-icon-triangle-1-e')
1279 .addClass('ui-icon-triangle-1-s');
1280 child.open(self.point_insertion(e.currentTarget));
1282 $row.removeData('open')
1283 .find('span.ui-icon')
1284 .removeClass('ui-icon-triangle-1-s')
1285 .addClass('ui-icon-triangle-1-e');
1290 placeholder.appendChild($row[0]);
1292 var $group_column = $('<th class="oe-group-name">').appendTo($row);
1293 // Don't fill this if group_by_no_leaf but no group_by
1294 if (group.grouped_on) {
1296 row_data[group.grouped_on] = group;
1297 var group_column = _(self.columns).detect(function (column) {
1298 return column.id === group.grouped_on; });
1300 $group_column.html(instance.web.format_cell(
1301 row_data, group_column, {
1302 value_if_empty: _t("Undefined"),
1303 process_modifiers: false
1306 $group_column.html(row_data[group_column.id].value);
1308 if (group.length && group.openable) {
1309 // Make openable if not terminal group & group_by_no_leaf
1310 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1312 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1313 // wonky background position to ensure nothing is displayed
1314 // there but the rest of the behavior is ui-icon's
1315 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1318 self.indent($group_column, group.level);
1320 $('<td>').text(group.length).appendTo($row);
1322 if (self.options.selectable) {
1323 $row.append('<td>');
1325 if (self.options.isClarkGable) {
1326 $row.append('<td>');
1328 _(self.columns).chain()
1329 .filter(function (column) {return !column.invisible;})
1330 .each(function (column) {
1332 // do not do anything
1333 } else if (column.id in group.aggregates) {
1335 r[column.id] = {value: group.aggregates[column.id]};
1336 $('<td class="oe-number">')
1337 .html(instance.web.format_cell(
1338 r, column, {process_modifiers: false}))
1341 $row.append('<td>');
1344 if (self.options.deletable) {
1345 $row.append('<td class="oe-group-pagination">');
1350 bind_child_events: function (child) {
1351 var $this = $(this),
1353 $(child).bind('selected', function (e) {
1354 // can have selections spanning multiple links
1355 var selection = self.get_selection();
1356 $this.trigger(e, [selection.ids, selection.records]);
1357 }).bind(this.passtrough_events, function (e) {
1358 // additional positional parameters are provided to trigger as an
1359 // Array, following the event type or event object, but are
1360 // provided to the .bind event handler as *args.
1361 // Convert our *args back into an Array in order to trigger them
1362 // on the group itself, so it can ultimately be forwarded wherever
1363 // it's supposed to go.
1364 var args = Array.prototype.slice.call(arguments, 1);
1365 $this.trigger.call($this, e, args);
1368 render_dataset: function (dataset) {
1370 list = new instance.web.ListView.List(this, {
1371 options: this.options,
1372 columns: this.columns,
1374 records: this.records
1376 this.bind_child_events(list);
1378 var view = this.view,
1379 limit = view.limit(),
1380 d = new $.Deferred(),
1381 page = this.datagroup.openable ? this.page : view.page;
1383 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1384 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1385 //TODO xmo: investigate why we need to put the setTimeout
1386 $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1387 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1388 if (self.records.length) {
1389 self.records.reset(null, {silent: true});
1391 if (!self.datagroup.openable) {
1392 view.configure_pager(dataset);
1394 if (dataset.size() == records.length) {
1396 self.$row.find('td.oe-group-pagination').empty();
1398 var pages = Math.ceil(dataset.size() / limit);
1400 .find('.oe-pager-state')
1401 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1406 .find('button[data-pager-action=previous]')
1407 .attr('disabled', page === 0)
1409 .find('button[data-pager-action=next]')
1410 .attr('disabled', page === pages - 1);
1414 self.records.add(records, {silent: true});
1417 if (_.isEmpty(records)) {
1423 setup_resequence_rows: function (list, dataset) {
1424 // drag and drop enabled if list is not sorted and there is a
1425 // "sequence" column in the view.
1426 if ((dataset.sort && dataset.sort())
1427 || !_(this.columns).any(function (column) {
1428 return column.name === 'sequence'; })) {
1431 // ondrop, move relevant record & fix sequences
1432 list.$current.sortable({
1434 items: '> tr[data-id]',
1435 containment: 'parent',
1437 stop: function (event, ui) {
1438 var to_move = list.records.get(ui.item.data('id')),
1439 target_id = ui.item.prev().data('id'),
1440 from_index = list.records.indexOf(to_move),
1441 target = list.records.get(target_id);
1442 if (list.records.at(from_index - 1) == target) {
1446 list.records.remove(to_move);
1447 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1448 list.records.add(to_move, { at: to });
1450 // resequencing time!
1451 var record, index = to,
1452 // if drag to 1st row (to = 0), start sequencing from 0
1453 // (exclusive lower bound)
1454 seq = to ? list.records.at(to - 1).get('sequence') : 0;
1455 while (++seq, record = list.records.at(index++)) {
1456 // write are independent from one another, so we can just
1457 // launch them all at the same time and we don't really
1458 // give a fig about when they're done
1459 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1460 // Accounting > Taxes > Taxes, child tax accounts)
1461 // when synchronous (without setTimeout)
1462 (function (dataset, id, seq) {
1463 $.async_when().then(function () {
1464 dataset.write(id, {sequence: seq});
1466 }(dataset, record.get('id'), seq));
1467 record.set('sequence', seq);
1470 list.refresh_zebra();
1474 render: function (post_render) {
1476 var $element = $('<tbody>');
1477 this.elements = [$element[0]];
1479 this.datagroup.list(
1480 _(this.view.visible_columns).chain()
1481 .filter(function (column) { return column.tag === 'field' })
1482 .pluck('name').value(),
1484 $element[0].appendChild(
1485 self.render_groups(groups));
1486 if (post_render) { post_render(); }
1487 }, function (dataset) {
1488 self.render_dataset(dataset).then(function (list) {
1489 self.children[null] = list;
1491 [list.$current.replaceAll($element)[0]];
1492 self.setup_resequence_rows(list, dataset);
1493 if (post_render) { post_render(); }
1499 * Returns the ids of all selected records for this group, and the records
1502 get_selection: function () {
1503 var ids = [], records = [];
1506 .each(function (child) {
1507 var selection = child.get_selection();
1508 ids.push.apply(ids, selection.ids);
1509 records.push.apply(records, selection.records);
1512 return {ids: ids, records: records};
1514 on_records_reset: function () {
1516 $(this.elements).remove();
1518 get_records: function () {
1519 if (_(this.children).isEmpty()) {
1520 if (!this.datagroup.length) {
1524 count: this.datagroup.length,
1525 values: this.datagroup.aggregates
1528 return _(this.children).chain()
1529 .map(function (child) {
1530 return child.get_records();
1531 }).flatten().value();
1538 var Events = /** @lends Events# */{
1540 * @param {String} event event to listen to on the current object, null for all events
1541 * @param {Function} handler event handler to bind to the relevant event
1544 bind: function (event, handler) {
1545 var calls = this['_callbacks'] || (this._callbacks = {});
1547 if (event in calls) {
1548 calls[event].push(handler);
1550 calls[event] = [handler];
1555 * @param {String} event event to unbind on the current object
1556 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1559 unbind: function (event, handler) {
1560 var calls = this._callbacks || {};
1561 if (!(event in calls)) { return this; }
1563 delete calls[event];
1565 var handlers = calls[event];
1567 _(handlers).indexOf(handler),
1573 * @param {String} event
1576 trigger: function (event) {
1578 if (!(calls = this._callbacks)) { return this; }
1579 var callbacks = (calls[event] || []).concat(calls[null] || []);
1580 for(var i=0, length=callbacks.length; i<length; ++i) {
1581 callbacks[i].apply(this, arguments);
1586 var Record = instance.web.Class.extend(/** @lends Record# */{
1588 * @constructs Record
1589 * @extends instance.web.Class
1592 * @param {Object} [data]
1594 init: function (data) {
1595 this.attributes = data || {};
1598 * @param {String} key
1601 get: function (key) {
1602 return this.attributes[key];
1607 * @param {Object} [options]
1608 * @param {Boolean} [options.silent=false]
1611 set: function (key, value, options) {
1612 options = options || {};
1613 var old_value = this.attributes[key];
1614 if (old_value === value) {
1617 this.attributes[key] = value;
1618 if (!options.silent) {
1619 this.trigger('change:' + key, this, value, old_value);
1620 this.trigger('change', this, key, value, old_value);
1625 * Converts the current record to the format expected by form views:
1627 * .. code-block:: javascript
1636 * @returns {Object} record displayable in a form view
1638 toForm: function () {
1639 var form_data = {}, attrs = this.attributes;
1640 for(var k in attrs) {
1641 form_data[k] = {value: attrs[k]};
1644 return {data: form_data};
1647 * Converts the current record to a format expected by context evaluations
1648 * (identical to record.attributes, except m2o fields are their integer
1649 * value rather than a pair)
1651 toContext: function () {
1652 var output = {}, attrs = this.attributes;
1653 for(var k in attrs) {
1655 if (typeof val !== 'object') {
1657 } else if (val instanceof Array) {
1660 throw new Error("Can't convert value " + val + " to context");
1666 Record.include(Events);
1667 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1669 * Smarter collections, with events, very strongly inspired by Backbone's.
1671 * Using a "dumb" array of records makes synchronization between the
1674 * @constructs Collection
1675 * @extends instance.web.Class
1678 * @param {Array} [records] records to initialize the collection with
1679 * @param {Object} [options]
1681 init: function (records, options) {
1682 options = options || {};
1683 _.bindAll(this, '_onRecordEvent');
1688 this._key = options.key;
1689 this._parent = options.parent;
1696 * @param {Object|Array} record
1697 * @param {Object} [options]
1698 * @param {Number} [options.at]
1699 * @param {Boolean} [options.silent=false]
1702 add: function (record, options) {
1703 options = options || {};
1704 var records = record instanceof Array ? record : [record];
1706 for(var i=0, length=records.length; i<length; ++i) {
1707 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1708 instance_.bind(null, this._onRecordEvent);
1709 this._byId[instance_.get('id')] = instance_;
1710 if (options.at == undefined) {
1711 this.records.push(instance_);
1712 if (!options.silent) {
1713 this.trigger('add', this, instance_, this.records.length-1);
1716 var insertion_index = options.at + i;
1717 this.records.splice(insertion_index, 0, instance_);
1718 if (!options.silent) {
1719 this.trigger('add', this, instance_, insertion_index);
1728 * Get a record by its index in the collection, can also take a group if
1729 * the collection is not degenerate
1731 * @param {Number} index
1732 * @param {String} [group]
1733 * @returns {Record|undefined}
1735 at: function (index, group) {
1737 var groups = group.split('.');
1738 return this._proxies[groups[0]].at(index, groups.join('.'));
1740 return this.records[index];
1743 * Get a record by its database id
1745 * @param {Number} id
1746 * @returns {Record|undefined}
1748 get: function (id) {
1749 if (!_(this._proxies).isEmpty()) {
1751 _(this._proxies).detect(function (proxy) {
1752 return record = proxy.get(id);
1756 return this._byId[id];
1759 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1760 * the subtree's group
1762 * @param {String} section group path section
1763 * @returns {Collection}
1765 proxy: function (section) {
1766 return this._proxies[section] = new Collection(null, {
1769 }).bind(null, this._onRecordEvent);
1772 * @param {Array} [records]
1775 reset: function (records, options) {
1776 options = options || {};
1777 _(this._proxies).each(function (proxy) {
1781 _(this.records).invoke('unbind', null, this._onRecordEvent);
1788 if (!options.silent) {
1789 this.trigger('reset', this);
1794 * Removes the provided record from the collection
1796 * @param {Record} record
1799 remove: function (record) {
1800 var index = _(this.records).indexOf(record);
1802 _(this._proxies).each(function (proxy) {
1803 proxy.remove(record);
1808 record.unbind(null, this._onRecordEvent);
1809 this.records.splice(index, 1);
1810 delete this._byId[record.get('id')];
1812 this.trigger('remove', record, this);
1816 _onRecordEvent: function (event, record, options) {
1817 // don't propagate reset events
1818 if (event === 'reset') { return; }
1819 this.trigger.apply(this, arguments);
1822 // underscore-type methods
1823 each: function (callback) {
1824 for(var section in this._proxies) {
1825 if (this._proxies.hasOwnProperty(section)) {
1826 this._proxies[section].each(callback);
1829 for(var i=0; i<this.length; ++i) {
1830 callback(this.records[i]);
1833 map: function (callback) {
1835 this.each(function (record) {
1836 results.push(callback(record));
1840 pluck: function (fieldname) {
1841 return this.map(function (record) {
1842 return record.get(fieldname);
1845 indexOf: function (record) {
1846 return _(this.records).indexOf(record);
1849 Collection.include(Events);
1850 instance.web.list = {
1853 Collection: Collection
1856 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: