1 openerp.web.list = function (openerp) {
2 var _t = openerp.web._t,
4 var QWeb = openerp.web.qweb;
5 openerp.web.views.add('list', 'openerp.web.ListView');
6 openerp.web.ListView = openerp.web.View.extend( /** @lends openerp.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 openerp.web.ListView
37 * @extends openerp.web.View
39 * @param parent parent object
40 * @param {openerp.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;
62 this.records = new Collection();
64 this.set_groups(new (this.options.GroupsType)(this));
66 if (this.dataset instanceof openerp.web.DataSetStatic) {
67 this.groups.datagroup = new openerp.web.StaticDataGroup(this.dataset);
69 this.groups.datagroup = new openerp.web.DataGroup(
72 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 set_default_options: function (options) {
90 _.defaults(this.options, {
91 GroupsType: openerp.web.ListView.Groups,
92 ListType: openerp.web.ListView.List
97 * Retrieves the view's number of records per page (|| section)
99 * options > defaults > parent.action.limit > indefinite
101 * @returns {Number|null}
104 if (this._limit === undefined) {
105 this._limit = (this.options.limit
106 || this.defaults.limit
107 || (this.widget_parent.action || {}).limit
113 * Set a custom Group construct as the root of the List View.
115 * @param {openerp.web.ListView.Groups} groups
117 set_groups: function (groups) {
120 $(this.groups).unbind("selected deleted action row_link");
124 this.groups = groups;
125 $(this.groups).bind({
126 'selected': function (e, ids, records) {
127 self.do_select(ids, records);
129 'deleted': function (e, ids) {
132 'action': function (e, action_name, id, callback) {
133 self.do_button_action(action_name, id, callback);
135 'row_link': function (e, id, dataset, view) {
136 self.do_activate_record(dataset.index, id, dataset, view);
141 * View startup method, the default behavior is to set the ``oe-listview``
142 * class on its root element and to perform an RPC load call.
144 * @returns {$.Deferred} loading promise
148 this.$element.addClass('oe-listview');
149 return this.reload_view(null, null, true);
152 * Returns the color for the provided record in the current view (from the
153 * ``@colors`` attribute)
155 * @param {Record} record record for the current row
156 * @returns {String} CSS color declaration
158 color_for: function (record) {
159 if (!this.colors) { return ''; }
160 var context = _.extend({}, record.attributes, {
161 uid: this.session.uid,
162 current_date: new Date().toString('yyyy-MM-dd')
163 // TODO: time, datetime, relativedelta
165 for(var i=0, len=this.colors.length; i<len; ++i) {
166 var pair = this.colors[i],
168 expression = pair[1];
169 if (py.evaluate(expression, _.extend({bool: py.bool}, context))) {
170 return 'color: ' + color + ';';
172 // TODO: handle evaluation errors
177 * Called after loading the list view's description, sets up such things
178 * as the view table's columns, renders the table itself and hooks up the
179 * various table-level and row-level DOM events (action buttons, deletion
180 * buttons, selection of records, [New] button, selection of a given
183 * Sets up the following:
185 * * Processes arch and fields to generate a complete field descriptor for each field
186 * * Create the table itself and allocate visible columns
187 * * Hook in the top-level (header) [New|Add] and [Delete] button
188 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
189 * * Sets up event handlers for action buttons and per-row deletion button
190 * * Hooks global callback for clicking on a row
191 * * Sets up its sidebar, if any
193 * @param {Object} data wrapped fields_view_get result
194 * @param {Object} data.fields_view fields_view_get result (processed)
195 * @param {Object} data.fields_view.fields mapping of fields for the current model
196 * @param {Object} data.fields_view.arch current list view descriptor
197 * @param {Boolean} grouped Is the list view grouped
199 on_loaded: function(data, grouped) {
201 this.fields_view = data;
202 this.name = "" + this.fields_view.arch.attrs.string;
204 if (this.fields_view.arch.attrs.colors) {
205 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
207 .map(function(color_pair) {
208 var pair = color_pair.split(':'),
211 return [color, py.parse(py.tokenize(expr)), expr];
215 this.setup_columns(this.fields_view.fields, grouped);
217 this.$element.html(QWeb.render(this._template, this));
219 this.$element.find('.all-record-selector').click(function(){
220 self.$element.find('.oe-record-selector input').prop('checked',
221 self.$element.find('.all-record-selector').prop('checked') || false);
222 var selection = self.groups.get_selection();
223 $(self.groups).trigger(
224 'selected', [selection.ids, selection.records]);
227 this.$element.find('.oe-list-add')
228 .click(this.proxy('do_add_record'))
229 .attr('disabled', grouped && this.options.editable);
230 this.$element.find('.oe-list-delete')
231 .attr('disabled', true)
232 .click(this.proxy('do_delete_selected'));
233 this.$element.find('thead').delegate('th.oe-sortable[data-id]', 'click', function (e) {
237 self.dataset.sort($this.data('id'));
238 if ($this.find('span').length) {
239 $this.find('span').toggleClass(
240 'ui-icon-triangle-1-s ui-icon-triangle-1-n');
242 $this.append('<span class="ui-icon ui-icon-triangle-1-n">')
243 .siblings('.oe-sortable').find('span').remove();
246 self.reload_content();
249 this.$element.find('.oe-list-pager')
250 .delegate('button', 'click', function () {
252 switch ($this.data('pager-action')) {
254 self.page = 0; break;
256 self.page = Math.floor(
257 self.dataset.size() / self.limit());
260 self.page += 1; break;
262 self.page -= 1; break;
264 self.reload_content();
265 }).find('.oe-pager-state')
266 .click(function (e) {
270 var $select = $('<select>')
271 .appendTo($this.empty())
272 .click(function (e) {e.stopPropagation();})
273 .append('<option value="80">80</option>' +
274 '<option value="100">100</option>' +
275 '<option value="200">200</option>' +
276 '<option value="500">500</option>' +
277 '<option value="NaN">' + _t("Unlimited") + '</option>')
278 .change(function () {
279 var val = parseInt($select.val(), 10);
280 self._limit = (isNaN(val) ? null : val);
282 self.reload_content();
284 .val(self._limit || 'NaN');
286 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
287 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
288 this.sidebar.start();
289 this.sidebar.add_toolbar(this.fields_view.toolbar);
290 this.set_common_sidebar_sections(this.sidebar);
294 * Configures the ListView pager based on the provided dataset's information
296 * Horrifying side-effect: sets the dataset's data on this.dataset?
298 * @param {openerp.web.DataSet} dataset
300 configure_pager: function (dataset) {
301 this.dataset.ids = dataset.ids;
303 if (dataset._length) {
304 this.dataset._length = dataset._length;
307 var limit = this.limit(),
308 total = dataset.size(),
309 first = (this.page * limit),
311 if (!limit || (total - first) < limit) {
314 last = first + limit;
316 this.$element.find('span.oe-pager-state').empty().text(_.str.sprintf(
317 _t("[%(first_record)d to %(last_record)d] of %(records_count)d"), {
318 first_record: first + 1,
324 .find('button[data-pager-action=first], button[data-pager-action=previous]')
325 .attr('disabled', this.page === 0)
327 .find('button[data-pager-action=last], button[data-pager-action=next]')
328 .attr('disabled', last === total);
331 * Sets up the listview's columns: merges view and fields data, move
332 * grouped-by columns to the front of the columns list and make them all
335 * @param {Object} fields fields_view_get's fields section
336 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
338 setup_columns: function (fields, grouped) {
339 var domain_computer = openerp.web.form.compute_domain;
341 var noop = function () { return {}; };
342 var field_to_column = function (field) {
343 var name = field.attrs.name;
344 var column = _.extend({id: name, tag: field.tag},
345 fields[name], field.attrs);
346 // modifiers computer
347 if (column.modifiers) {
348 var modifiers = JSON.parse(column.modifiers);
349 column.modifiers_for = function (fields) {
350 if (!modifiers.invisible) {
354 'invisible': domain_computer(modifiers.invisible, fields)
357 if (modifiers['tree_invisible']) {
358 column.invisible = '1';
360 delete column.invisible;
363 column.modifiers_for = noop;
368 this.columns.splice(0, this.columns.length);
369 this.columns.push.apply(
371 _(this.fields_view.arch.children).map(field_to_column));
373 this.columns.unshift({
374 id: '_group', tag: '', string: _t("Group"), meta: true,
375 modifiers_for: function () { return {}; }
377 id: '_count', tag: '', string: '#', meta: true,
378 modifiers_for: function () { return {}; }
382 this.visible_columns = _.filter(this.columns, function (column) {
383 return column.invisible !== '1';
386 this.aggregate_columns = _(this.visible_columns)
387 .map(function (column) {
388 if (column.type !== 'integer' && column.type !== 'float') {
391 var aggregation_func = column['group_operator'] || 'sum';
392 if (!(aggregation_func in column)) {
396 return _.extend({}, column, {
397 'function': aggregation_func,
398 label: column[aggregation_func]
403 * Used to handle a click on a table row, if no other handler caught the
406 * The default implementation asks the list view's view manager to switch
407 * to a different view (by calling
408 * :js:func:`~openerp.web.ViewManager.on_mode_switch`), using the
409 * provided record index (within the current list view's dataset).
411 * If the index is null, ``switch_to_record`` asks for the creation of a
414 * @param {Number|void} index the record index (in the current dataset) to switch to
415 * @param {String} [view="page"] the view type to switch to
417 select_record:function (index, view) {
418 view = view || index == null ? 'form' : 'page';
419 this.dataset.index = index;
420 _.delay(_.bind(function () {
421 this.do_switch_view(view);
424 do_show: function () {
427 this.sidebar.$element.show();
430 do_hide: function () {
433 this.sidebar.$element.hide();
437 * Reloads the list view based on the current settings (dataset & al)
439 * @param {Boolean} [grouped] Should the list be displayed grouped
440 * @param {Object} [context] context to send the server while loading the view
442 reload_view: function (grouped, context, initial) {
444 var callback = function (field_view_get) {
445 self.on_loaded(field_view_get, grouped);
447 if (this.embedded_view) {
448 return $.Deferred().then(callback).resolve(this.embedded_view);
450 return this.rpc('/web/listview/load', {
452 view_id: this.view_id,
454 context: this.dataset.get_context(context),
455 toolbar: this.options.sidebar
460 * re-renders the content of the list view
462 * @returns {$.Deferred} promise to content reloading
464 reload_content: function () {
466 self.$element.find('.all-record-selector').prop('checked', false);
467 this.records.reset();
468 var reloaded = $.Deferred();
469 this.$element.find('.oe-listview-content').append(
470 this.groups.render(function () {
471 if (self.dataset.index == null) {
473 self.records.each(function () { has_one = true; });
475 self.dataset.index = 0;
478 self.compute_aggregates();
485 return reloaded.promise();
487 reload: function () {
488 return this.reload_content();
491 do_load_state: function(state, warm) {
493 if (state.page && this.page !== state.page) {
494 this.page = state.page;
498 if (_.isString(state.limit)) {
501 if (state.limit !== this._limit) {
502 this._limit = state.limit;
507 this.reload_content();
511 * Handler for the result of eval_domain_and_context, actually perform the
514 * @param {Object} results results of evaluating domain and process for a search
516 do_search: function (domain, context, group_by) {
518 this.groups.datagroup = new openerp.web.DataGroup(
519 this, this.model, domain, context, group_by);
520 this.groups.datagroup.sort = this.dataset._sort;
522 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
525 this.no_leaf = !!context['group_by_no_leaf'];
527 this.reload_view(!!group_by, context).then(
528 this.proxy('reload_content'));
531 * Handles the signal to delete lines from the records list
533 * @param {Array} ids the ids of the records to delete
535 do_delete: function (ids) {
536 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
540 return $.when(this.dataset.unlink(ids)).then(function () {
541 _(ids).each(function (id) {
542 self.records.remove(self.records.get(id));
544 self.configure_pager(self.dataset);
545 self.compute_aggregates();
549 * Handles the signal indicating that a new record has been selected
551 * @param {Array} ids selected record ids
552 * @param {Array} records selected record values
554 do_select: function (ids, records) {
555 this.$element.find('.oe-list-delete').attr('disabled', !ids.length);
557 this.dataset.index = 0;
558 if (this.sidebar) { this.sidebar.do_fold(); }
559 this.compute_aggregates();
563 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
564 if (this.sidebar) { this.sidebar.do_unfold(); }
566 this.compute_aggregates(_(records).map(function (record) {
567 return {count: 1, values: record};
571 * Handles action button signals on a record
573 * @param {String} name action name
574 * @param {Object} id id of the record the action should be called on
575 * @param {Function} callback should be called after the action is executed, if non-null
577 do_button_action: function (name, id, callback) {
578 var action = _.detect(this.columns, function (field) {
579 return field.name === name;
581 if (!action) { return; }
582 if ('confirm' in action && !window.confirm(action.confirm)) {
586 var c = new openerp.web.CompoundContext();
587 c.set_eval_context(_.extend({
590 active_model: this.dataset.model
591 }, this.records.get(id).toContext()));
592 if (action.context) {
593 c.add(action.context);
596 this.do_execute_action(action, this.dataset, id, callback);
599 * Handles the activation of a record (clicking on it)
601 * @param {Number} index index of the record in the dataset
602 * @param {Object} id identifier of the activated record
603 * @param {openerp.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
605 do_activate_record: function (index, id, dataset, view) {
606 this.dataset.ids = dataset.ids;
607 this.select_record(index, view);
610 * Handles signal for the addition of a new record (can be a creation,
611 * can be the addition from a remote source, ...)
613 * The default implementation is to switch to a new record on the form view
615 do_add_record: function () {
616 this.select_record(null);
619 * Handles deletion of all selected lines
621 do_delete_selected: function () {
622 this.do_delete(this.groups.get_selection().ids);
625 * Computes the aggregates for the current list view, either on the
626 * records provided or on the records of the internal
627 * :js:class:`~openerp.web.ListView.Group`, by calling
628 * :js:func:`~openerp.web.ListView.group.get_records`.
630 * Then displays the aggregates in the table through
631 * :js:method:`~openerp.web.ListView.display_aggregates`.
633 * @param {Array} [records]
635 compute_aggregates: function (records) {
636 var columns = _(this.aggregate_columns).filter(function (column) {
637 return column['function']; });
638 if (_.isEmpty(columns)) { return; }
640 if (_.isEmpty(records)) {
641 records = this.groups.get_records();
643 records = _(records).compact();
645 var count = 0, sums = {};
646 _(columns).each(function (column) {
647 switch (column['function']) {
649 sums[column.id] = -Infinity;
652 sums[column.id] = Infinity;
658 _(records).each(function (record) {
659 count += record.count || 1;
660 _(columns).each(function (column) {
661 var field = column.id,
662 value = record.values[field];
663 switch (column['function']) {
665 sums[field] += value;
668 sums[field] += record.count * value;
671 if (sums[field] > value) {
676 if (sums[field] < value) {
685 _(columns).each(function (column) {
686 var field = column.id;
687 switch (column['function']) {
689 aggregates[field] = {value: sums[field] / count};
692 aggregates[field] = {value: sums[field]};
696 this.display_aggregates(aggregates);
698 display_aggregates: function (aggregation) {
700 var $footer_cells = this.$element.find('.oe-list-footer');
701 _(this.aggregate_columns).each(function (column) {
702 if (!column['function']) {
706 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
707 .html(openerp.web.format_cell(aggregation, column, {
708 process_modifiers: false
712 get_selected_ids: function() {
713 var ids = this.groups.get_selection().ids;
717 * Adds padding columns at the start or end of all table rows (including
720 * @param {Number} count number of columns to add
721 * @param {Object} options
722 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
723 * @param {Object} [options.except] content row to not pad
725 pad_columns: function (count, options) {
726 options = options || {};
727 // padding for action/pager header
728 var $first_header = this.$element.find('thead tr:first th');
729 var colspan = $first_header.attr('colspan');
731 if (!this.previous_colspan) {
732 this.previous_colspan = colspan;
734 $first_header.attr('colspan', parseInt(colspan, 10) + count);
736 // Padding for column titles, footer and data rows
737 var $rows = this.$element
738 .find('.oe-listview-header-columns, tr:not(thead tr)')
739 .not(options['except']);
740 var newcols = new Array(count+1).join('<td class="oe-listview-padding"></td>');
741 if (options.position === 'before') {
742 $rows.prepend(newcols);
744 $rows.append(newcols);
748 * Removes all padding columns of the table
750 unpad_columns: function () {
751 this.$element.find('.oe-listview-padding').remove();
752 if (this.previous_colspan) {
754 .find('thead tr:first th')
755 .attr('colspan', this.previous_colspan);
756 this.previous_colspan = null;
760 openerp.web.ListView.List = openerp.web.Class.extend( /** @lends openerp.web.ListView.List# */{
762 * List display for the ListView, handles basic DOM events and transforms
763 * them in the relevant higher-level events, to which the list view (or
764 * other consumers) can subscribe.
766 * Events on this object are registered via jQuery.
771 * Triggered when a row is selected (using check boxes), provides an
772 * array of ids of all the selected records.
774 * Triggered when deletion buttons are hit, provide an array of ids of
775 * all the records being marked for suppression.
777 * Triggered when an action button is clicked, provides two parameters:
779 * * The name of the action to execute (as a string)
780 * * The id of the record to execute the action on
782 * Triggered when a row of the table is clicked, provides the index (in
783 * the rows array) and id of the selected record to the handle function.
785 * @constructs openerp.web.ListView.List
786 * @extends openerp.web.Class
788 * @param {Object} opts display options, identical to those of :js:class:`openerp.web.ListView`
790 init: function (group, opts) {
793 this.view = group.view;
794 this.session = this.view.session;
796 this.options = opts.options;
797 this.columns = opts.columns;
798 this.dataset = opts.dataset;
799 this.records = opts.records;
801 this.record_callbacks = {
802 'remove': function (event, record) {
803 var $row = self.$current.find(
804 '[data-id=' + record.get('id') + ']');
805 var index = $row.data('index');
807 self.refresh_zebra(index);
809 'reset': function () { return self.on_records_reset(); },
810 'change': function (event, record) {
811 var $row = self.$current.find('[data-id=' + record.get('id') + ']');
812 $row.replaceWith(self.render_record(record));
814 'add': function (ev, records, record, index) {
815 var $new_row = $('<tr>').attr({
816 'data-id': record.get('id')
820 $new_row.prependTo(self.$current);
822 var previous_record = records.at(index-1),
823 $previous_sibling = self.$current.find(
824 '[data-id=' + previous_record.get('id') + ']');
825 $new_row.insertAfter($previous_sibling);
828 self.refresh_zebra(index, 1);
831 _(this.record_callbacks).each(function (callback, event) {
832 this.records.bind(event, callback);
835 this.$_element = $('<tbody class="ui-widget-content">')
836 .appendTo(document.body)
837 .delegate('th.oe-record-selector', 'click', function (e) {
839 var selection = self.get_selection();
841 'selected', [selection.ids, selection.records]);
843 .delegate('td.oe-record-delete button', 'click', function (e) {
845 var $row = $(e.target).closest('tr');
846 $(self).trigger('deleted', [[self.row_id($row)]]);
848 .delegate('td.oe-field-cell button', 'click', function (e) {
850 var $target = $(e.currentTarget),
851 field = $target.closest('td').data('field'),
852 $row = $target.closest('tr'),
853 record_id = self.row_id($row);
855 // note: $.data converts data to number if it's composed only
856 // of digits, nice when storing actual numbers, not nice when
857 // storing strings composed only of digits. Force the action
858 // name to be a string
859 $(self).trigger('action', [field.toString(), record_id, function () {
860 return self.reload_record(self.records.get(record_id));
863 .delegate('a', 'click', function (e) {
866 .delegate('tr', 'click', function (e) {
868 var row_id = self.row_id(e.currentTarget);
869 if (row_id !== undefined) {
870 if (!self.dataset.select_id(row_id)) {
871 throw "Could not find id in dataset"
874 if ($(e.target).is('.oe-record-edit-link-img')) {
877 self.row_clicked(e, view);
881 row_clicked: function (e, view) {
884 [this.dataset.ids[this.dataset.index],
885 this.dataset, view]);
887 render_cell: function (record, column) {
889 if(column.type === 'reference') {
890 value = record.get(column.id);
892 // Ensure that value is in a reference "shape", otherwise we're
893 // going to loop on performing name_get after we've resolved (and
894 // set) a human-readable version. m2o does not have this issue
895 // because the non-human-readable is just a number, where the
896 // human-readable version is a pair
897 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
898 // reference values are in the shape "$model,$id" (as a
899 // string), we need to split and name_get this pair in order
900 // to get a correctly displayable value in the field
901 var model = ref_match[1],
902 id = parseInt(ref_match[2], 10);
903 new openerp.web.DataSet(this.view, model).name_get([id], function(names) {
904 if (!names.length) { return; }
905 record.set(column.id, names[0][1]);
908 } else if (column.type === 'many2one') {
909 value = record.get(column.id);
910 // m2o values are usually name_get formatted, [Number, String]
911 // pairs, but in some cases only the id is provided. In these
912 // cases, we need to perform a name_get call to fetch the actual
914 if (typeof value === 'number' || value instanceof Number) {
915 // fetch the name, set it on the record (in the right field)
916 // and let the various registered events handle refreshing the
918 new openerp.web.DataSet(this.view, column.relation)
919 .name_get([value], function (names) {
920 if (!names.length) { return; }
921 record.set(column.id, names[0]);
925 return openerp.web.format_cell(record.toForm().data, column, {
926 model: this.dataset.model,
930 render: function () {
933 this.$current.remove();
935 this.$current = this.$_element.clone(true);
936 this.$current.empty().append(
937 QWeb.render('ListView.rows', _.extend({
938 render_cell: function () {
939 return self.render_cell.apply(self, arguments); }
941 this.pad_table_to(5);
943 pad_table_to: function (count) {
944 if (this.records.length >= count ||
945 _(this.columns).any(function(column) { return column.meta; })) {
949 if (this.options.selectable) {
950 cells.push('<th class="oe-record-selector"></td>');
952 if (this.options.isClarkGable) {
953 cells.push('<th class="oe-record-edit-link"></td>');
955 _(this.columns).each(function(column) {
956 if (column.invisible === '1') {
959 if (column.tag === 'button') {
960 cells.push('<td class="oe-button" title="' + column.string + '"> </td>');
962 cells.push('<td title="' + column.string + '"> </td>');
965 if (this.options.deletable) {
966 cells.push('<td class="oe-record-delete"><button type="button" style="visibility: hidden"> </button></td>');
968 cells.unshift('<tr>');
971 var row = cells.join('');
973 .children('tr:not([data-id])').remove().end()
974 .append(new Array(count - this.records.length + 1).join(row));
975 this.refresh_zebra(this.records.length);
978 * Gets the ids of all currently selected records, if any
979 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
981 get_selection: function () {
982 var result = {ids: [], records: []};
983 if (!this.options.selectable) {
986 var records = this.records;
987 this.$current.find('th.oe-record-selector input:checked')
988 .closest('tr').each(function () {
989 var record = records.get($(this).data('id'));
990 result.ids.push(record.get('id'));
991 result.records.push(record.attributes);
996 * Returns the identifier of the object displayed in the provided table
999 * @param {Object} row the selected table row
1000 * @returns {Number|String} the identifier of the row's object
1002 row_id: function (row) {
1003 return $(row).data('id');
1006 * Death signal, cleans up list display
1008 on_records_reset: function () {
1009 _(this.record_callbacks).each(function (callback, event) {
1010 this.records.unbind(event, callback);
1012 if (!this.$current) { return; }
1013 this.$current.remove();
1014 this.$current = null;
1015 this.$_element.remove();
1017 get_records: function () {
1018 return this.records.map(function (record) {
1019 return {count: 1, values: record.attributes};
1023 * Reloads the provided record by re-reading its content from the server.
1025 * @param {Record} record
1026 * @returns {$.Deferred} promise to the finalization of the reloading
1028 reload_record: function (record) {
1029 return this.dataset.read_ids(
1031 _.pluck(_(this.columns).filter(function (r) {
1032 return r.tag === 'field';
1034 ).then(function (records) {
1035 _(records[0]).each(function (value, key) {
1036 record.set(key, value, {silent: true});
1038 record.trigger('change', record);
1042 * Renders a list record to HTML
1044 * @param {Record} record index of the record to render in ``this.rows``
1045 * @returns {String} QWeb rendering of the selected record
1047 render_record: function (record) {
1048 var index = this.records.indexOf(record);
1049 return QWeb.render('ListView.row', {
1050 columns: this.columns,
1051 options: this.options,
1053 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1055 render_cell: function () {
1056 return this.render_cell.apply(this, arguments); }
1060 * Fixes fixes the even/odd classes
1062 * @param {Number} [from_index] index from which to resequence
1063 * @param {Number} [offset = 0] selection offset for DOM, in case there are rows to ignore in the table
1065 refresh_zebra: function (from_index, offset) {
1066 offset = offset || 0;
1067 from_index = from_index || 0;
1068 var dom_offset = offset + from_index;
1069 var sel = dom_offset ? ':gt(' + (dom_offset - 1) + ')' : null;
1070 this.$current.children(sel).each(function (i, e) {
1071 var index = from_index + i;
1072 // reset record-index accelerators on rows and even/odd
1073 var even = index%2 === 0;
1074 $(e).toggleClass('even', even)
1075 .toggleClass('odd', !even);
1079 openerp.web.ListView.Groups = openerp.web.Class.extend( /** @lends openerp.web.ListView.Groups# */{
1080 passtrough_events: 'action deleted row_link',
1082 * Grouped display for the ListView. Handles basic DOM events and interacts
1083 * with the :js:class:`~openerp.web.DataGroup` bound to it.
1085 * Provides events similar to those of
1086 * :js:class:`~openerp.web.ListView.List`
1088 * @constructs openerp.web.ListView.Groups
1089 * @extends openerp.web.Class
1091 * @param {openerp.web.ListView} view
1092 * @param {Object} [options]
1093 * @param {Collection} [options.records]
1094 * @param {Object} [options.options]
1095 * @param {Array} [options.columns]
1097 init: function (view, options) {
1098 options = options || {};
1100 this.records = options.records || view.records;
1101 this.options = options.options || view.options;
1102 this.columns = options.columns || view.columns;
1103 this.datagroup = null;
1111 this.records.bind('reset', function () {
1112 return self.on_records_reset(); });
1114 make_fragment: function () {
1115 return document.createDocumentFragment();
1118 * Returns a DOM node after which a new tbody can be inserted, so that it
1119 * follows the provided row.
1121 * Necessary to insert the result of a new group or list view within an
1122 * existing groups render, without losing track of the groups's own
1125 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1126 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1128 point_insertion: function (row) {
1130 var red_letter_tboday = $row.closest('tbody')[0];
1132 var $next_siblings = $row.nextAll();
1133 if ($next_siblings.length) {
1134 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1136 $root_kanal.append($next_siblings);
1137 this.elements.splice(
1138 _.indexOf(this.elements, red_letter_tboday),
1142 return red_letter_tboday;
1144 make_paginator: function () {
1146 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1147 .click(function (e) {
1148 e.stopPropagation();
1151 self.$row.closest('tbody').next()
1152 .replaceWith(self.render());
1154 var $next = $('<button type="button" data-pager-action="next">></button>')
1155 .click(function (e) {
1156 e.stopPropagation();
1159 self.$row.closest('tbody').next()
1160 .replaceWith(self.render());
1162 this.$row.children().last()
1164 .append('<span class="oe-pager-state"></span>')
1167 open: function (point_insertion) {
1168 this.render().insertAfter(point_insertion);
1170 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1171 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1172 if (no_subgroups && records_terminated) {
1173 this.make_paginator();
1176 close: function () {
1177 this.$row.children().last().empty();
1178 this.records.reset();
1181 * Prefixes ``$node`` with floated spaces in order to indent it relative
1182 * to its own left margin/baseline
1184 * @param {jQuery} $node jQuery object to indent
1185 * @param {Number} level current nesting level, >= 1
1186 * @returns {jQuery} the indentation node created
1188 indent: function ($node, level) {
1190 .css({'float': 'left', 'white-space': 'pre'})
1191 .text(new Array(level).join(' '))
1194 render_groups: function (datagroups) {
1196 var placeholder = this.make_fragment();
1197 _(datagroups).each(function (group) {
1198 if (self.children[group.value]) {
1199 self.records.proxy(group.value).reset();
1200 delete self.children[group.value];
1202 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1203 records: self.records.proxy(group.value),
1204 options: self.options,
1205 columns: self.columns
1207 self.bind_child_events(child);
1208 child.datagroup = group;
1210 var $row = child.$row = $('<tr>');
1211 if (group.openable && group.length) {
1212 $row.click(function (e) {
1213 if (!$row.data('open')) {
1214 $row.data('open', true)
1215 .find('span.ui-icon')
1216 .removeClass('ui-icon-triangle-1-e')
1217 .addClass('ui-icon-triangle-1-s');
1218 child.open(self.point_insertion(e.currentTarget));
1220 $row.removeData('open')
1221 .find('span.ui-icon')
1222 .removeClass('ui-icon-triangle-1-s')
1223 .addClass('ui-icon-triangle-1-e');
1228 placeholder.appendChild($row[0]);
1230 var $group_column = $('<th class="oe-group-name">').appendTo($row);
1231 // Don't fill this if group_by_no_leaf but no group_by
1232 if (group.grouped_on) {
1234 row_data[group.grouped_on] = group;
1235 var group_column = _(self.columns).detect(function (column) {
1236 return column.id === group.grouped_on; });
1238 $group_column.html(openerp.web.format_cell(
1239 row_data, group_column, {
1240 value_if_empty: _t("Undefined"),
1241 process_modifiers: false
1244 $group_column.html(row_data[group_column.id].value);
1246 if (group.length && group.openable) {
1247 // Make openable if not terminal group & group_by_no_leaf
1248 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1250 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1251 // wonky background position to ensure nothing is displayed
1252 // there but the rest of the behavior is ui-icon's
1253 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1256 self.indent($group_column, group.level);
1258 $('<td>').text(group.length).appendTo($row);
1260 if (self.options.selectable) {
1261 $row.append('<td>');
1263 if (self.options.isClarkGable) {
1264 $row.append('<td>');
1266 _(self.columns).chain()
1267 .filter(function (column) {return !column.invisible;})
1268 .each(function (column) {
1270 // do not do anything
1271 } else if (column.id in group.aggregates) {
1273 r[column.id] = {value: group.aggregates[column.id]};
1274 $('<td class="oe-number">')
1275 .html(openerp.web.format_cell(
1276 r, column, {process_modifiers: false}))
1279 $row.append('<td>');
1282 if (self.options.deletable) {
1283 $row.append('<td class="oe-group-pagination">');
1288 bind_child_events: function (child) {
1289 var $this = $(this),
1291 $(child).bind('selected', function (e) {
1292 // can have selections spanning multiple links
1293 var selection = self.get_selection();
1294 $this.trigger(e, [selection.ids, selection.records]);
1295 }).bind(this.passtrough_events, function (e) {
1296 // additional positional parameters are provided to trigger as an
1297 // Array, following the event type or event object, but are
1298 // provided to the .bind event handler as *args.
1299 // Convert our *args back into an Array in order to trigger them
1300 // on the group itself, so it can ultimately be forwarded wherever
1301 // it's supposed to go.
1302 var args = Array.prototype.slice.call(arguments, 1);
1303 $this.trigger.call($this, e, args);
1306 render_dataset: function (dataset) {
1308 list = new (this.view.options.ListType)(this, {
1309 options: this.options,
1310 columns: this.columns,
1312 records: this.records
1314 this.bind_child_events(list);
1316 var view = this.view,
1317 limit = view.limit(),
1318 d = new $.Deferred(),
1319 page = this.datagroup.openable ? this.page : view.page;
1321 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1322 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1323 //TODO xmo: investigate why we need to put the setTimeout
1324 $.async_when().then(function() {dataset.read_slice(fields, options).then(function (records) {
1325 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1326 if (self.records.length) {
1327 self.records.reset(null, {silent: true});
1329 if (!self.datagroup.openable) {
1330 view.configure_pager(dataset);
1332 if (dataset.size() == records.length) {
1334 self.$row.find('td.oe-group-pagination').empty();
1336 var pages = Math.ceil(dataset.size() / limit);
1338 .find('.oe-pager-state')
1339 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1344 .find('button[data-pager-action=previous]')
1345 .attr('disabled', page === 0)
1347 .find('button[data-pager-action=next]')
1348 .attr('disabled', page === pages - 1);
1352 self.records.add(records, {silent: true});
1358 setup_resequence_rows: function (list, dataset) {
1359 // drag and drop enabled if list is not sorted and there is a
1360 // "sequence" column in the view.
1361 if ((dataset.sort && dataset.sort())
1362 || !_(this.columns).any(function (column) {
1363 return column.name === 'sequence'; })) {
1366 // ondrop, move relevant record & fix sequences
1367 list.$current.sortable({
1369 items: '> tr[data-id]',
1370 containment: 'parent',
1372 stop: function (event, ui) {
1373 var to_move = list.records.get(ui.item.data('id')),
1374 target_id = ui.item.prev().data('id'),
1375 from_index = list.records.indexOf(to_move),
1376 target = list.records.get(target_id);
1377 if (list.records.at(from_index - 1) == target) {
1381 list.records.remove(to_move);
1382 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1383 list.records.add(to_move, { at: to });
1385 // resequencing time!
1386 var record, index = to,
1387 // if drag to 1st row (to = 0), start sequencing from 0
1388 // (exclusive lower bound)
1389 seq = to ? list.records.at(to - 1).get('sequence') : 0;
1390 while (++seq, record = list.records.at(index++)) {
1391 // write are independent from one another, so we can just
1392 // launch them all at the same time and we don't really
1393 // give a fig about when they're done
1394 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1395 // Accounting > Taxes > Taxes, child tax accounts)
1396 // when synchronous (without setTimeout)
1397 (function (dataset, id, seq) {
1398 $.async_when().then(function () {
1399 dataset.write(id, {sequence: seq});
1401 }(dataset, record.get('id'), seq));
1402 record.set('sequence', seq);
1405 list.refresh_zebra();
1409 render: function (post_render) {
1411 var $element = $('<tbody>');
1412 this.elements = [$element[0]];
1414 this.datagroup.list(
1415 _(this.view.visible_columns).chain()
1416 .filter(function (column) { return column.tag === 'field' })
1417 .pluck('name').value(),
1419 $element[0].appendChild(
1420 self.render_groups(groups));
1421 if (post_render) { post_render(); }
1422 }, function (dataset) {
1423 self.render_dataset(dataset).then(function (list) {
1424 self.children[null] = list;
1426 [list.$current.replaceAll($element)[0]];
1427 self.setup_resequence_rows(list, dataset);
1428 if (post_render) { post_render(); }
1434 * Returns the ids of all selected records for this group, and the records
1437 get_selection: function () {
1438 var ids = [], records = [];
1441 .each(function (child) {
1442 var selection = child.get_selection();
1443 ids.push.apply(ids, selection.ids);
1444 records.push.apply(records, selection.records);
1447 return {ids: ids, records: records};
1449 on_records_reset: function () {
1451 $(this.elements).remove();
1453 get_records: function () {
1454 if (_(this.children).isEmpty()) {
1455 if (!this.datagroup.length) {
1459 count: this.datagroup.length,
1460 values: this.datagroup.aggregates
1463 return _(this.children).chain()
1464 .map(function (child) {
1465 return child.get_records();
1466 }).flatten().value();
1473 var Events = /** @lends Events# */{
1475 * @param {String} event event to listen to on the current object, null for all events
1476 * @param {Function} handler event handler to bind to the relevant event
1479 bind: function (event, handler) {
1480 var calls = this['_callbacks'] || (this._callbacks = {});
1482 if (event in calls) {
1483 calls[event].push(handler);
1485 calls[event] = [handler];
1490 * @param {String} event event to unbind on the current object
1491 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1494 unbind: function (event, handler) {
1495 var calls = this._callbacks || {};
1496 if (!(event in calls)) { return this; }
1498 delete calls[event];
1500 var handlers = calls[event];
1502 _(handlers).indexOf(handler),
1508 * @param {String} event
1511 trigger: function (event) {
1513 if (!(calls = this._callbacks)) { return this; }
1514 var callbacks = (calls[event] || []).concat(calls[null] || []);
1515 for(var i=0, length=callbacks.length; i<length; ++i) {
1516 callbacks[i].apply(this, arguments);
1521 var Record = openerp.web.Class.extend(/** @lends Record# */{
1523 * @constructs Record
1524 * @extends openerp.web.Class
1527 * @param {Object} [data]
1529 init: function (data) {
1530 this.attributes = data || {};
1533 * @param {String} key
1536 get: function (key) {
1537 return this.attributes[key];
1542 * @param {Object} [options]
1543 * @param {Boolean} [options.silent=false]
1546 set: function (key, value, options) {
1547 options = options || {};
1548 var old_value = this.attributes[key];
1549 if (old_value === value) {
1552 this.attributes[key] = value;
1553 if (!options.silent) {
1554 this.trigger('change:' + key, this, value, old_value);
1555 this.trigger('change', this, key, value, old_value);
1560 * Converts the current record to the format expected by form views:
1562 * .. code-block:: javascript
1571 * @returns {Object} record displayable in a form view
1573 toForm: function () {
1574 var form_data = {}, attrs = this.attributes;
1575 for(var k in attrs) {
1576 form_data[k] = {value: attrs[k]};
1579 return {data: form_data};
1582 * Converts the current record to a format expected by context evaluations
1583 * (identical to record.attributes, except m2o fields are their integer
1584 * value rather than a pair)
1586 toContext: function () {
1587 var output = {}, attrs = this.attributes;
1588 for(var k in attrs) {
1590 if (typeof val !== 'object') {
1592 } else if (val instanceof Array) {
1595 throw new Error("Can't convert value " + val + " to context");
1601 Record.include(Events);
1602 var Collection = openerp.web.Class.extend(/** @lends Collection# */{
1604 * Smarter collections, with events, very strongly inspired by Backbone's.
1606 * Using a "dumb" array of records makes synchronization between the
1609 * @constructs Collection
1610 * @extends openerp.web.Class
1613 * @param {Array} [records] records to initialize the collection with
1614 * @param {Object} [options]
1616 init: function (records, options) {
1617 options = options || {};
1618 _.bindAll(this, '_onRecordEvent');
1623 this._key = options.key;
1624 this._parent = options.parent;
1631 * @param {Object|Array} record
1632 * @param {Object} [options]
1633 * @param {Number} [options.at]
1634 * @param {Boolean} [options.silent=false]
1637 add: function (record, options) {
1638 options = options || {};
1639 var records = record instanceof Array ? record : [record];
1641 for(var i=0, length=records.length; i<length; ++i) {
1642 var instance = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1643 instance.bind(null, this._onRecordEvent);
1644 this._byId[instance.get('id')] = instance;
1645 if (options.at == undefined) {
1646 this.records.push(instance);
1647 if (!options.silent) {
1648 this.trigger('add', this, instance, this.records.length-1);
1651 var insertion_index = options.at + i;
1652 this.records.splice(insertion_index, 0, instance);
1653 if (!options.silent) {
1654 this.trigger('add', this, instance, insertion_index);
1663 * Get a record by its index in the collection, can also take a group if
1664 * the collection is not degenerate
1666 * @param {Number} index
1667 * @param {String} [group]
1668 * @returns {Record|undefined}
1670 at: function (index, group) {
1672 var groups = group.split('.');
1673 return this._proxies[groups[0]].at(index, groups.join('.'));
1675 return this.records[index];
1678 * Get a record by its database id
1680 * @param {Number} id
1681 * @returns {Record|undefined}
1683 get: function (id) {
1684 if (!_(this._proxies).isEmpty()) {
1686 _(this._proxies).detect(function (proxy) {
1687 return record = proxy.get(id);
1691 return this._byId[id];
1694 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1695 * the subtree's group
1697 * @param {String} section group path section
1698 * @returns {Collection}
1700 proxy: function (section) {
1701 return this._proxies[section] = new Collection(null, {
1704 }).bind(null, this._onRecordEvent);
1707 * @param {Array} [records]
1710 reset: function (records, options) {
1711 options = options || {};
1712 _(this._proxies).each(function (proxy) {
1716 _(this.records).invoke('unbind', null, this._onRecordEvent);
1723 if (!options.silent) {
1724 this.trigger('reset', this);
1729 * Removes the provided record from the collection
1731 * @param {Record} record
1734 remove: function (record) {
1735 var index = _(this.records).indexOf(record);
1737 _(this._proxies).each(function (proxy) {
1738 proxy.remove(record);
1743 record.unbind(null, this._onRecordEvent);
1744 this.records.splice(index, 1);
1745 delete this._byId[record.get('id')];
1747 this.trigger('remove', record, this);
1751 _onRecordEvent: function (event, record, options) {
1752 // don't propagate reset events
1753 if (event === 'reset') { return; }
1754 this.trigger.apply(this, arguments);
1757 // underscore-type methods
1758 each: function (callback) {
1759 for(var section in this._proxies) {
1760 if (this._proxies.hasOwnProperty(section)) {
1761 this._proxies[section].each(callback);
1764 for(var i=0; i<this.length; ++i) {
1765 callback(this.records[i]);
1768 map: function (callback) {
1770 this.each(function (record) {
1771 results.push(callback(record));
1775 pluck: function (fieldname) {
1776 return this.map(function (record) {
1777 return record.get(fieldname);
1780 indexOf: function (record) {
1781 return _(this.records).indexOf(record);
1784 Collection.include(Events);
1785 openerp.web.list = {
1788 Collection: Collection
1791 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: