3 var instance = openerp;
5 var _t = instance.web._t,
6 _lt = instance.web._lt;
7 var QWeb = instance.web.qweb;
8 instance.web.views.add('list', 'instance.web.ListView');
9 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
10 _template: 'ListView',
11 display_name: _lt('List'),
13 // records can be selected one by one
15 // list rows can be deleted
17 // whether the column headers should be displayed
19 // display addition button, with that label
20 'addable': _lt("Create"),
21 // whether the list view can be sorted, note that once a view has been
22 // sorted it can not be reordered anymore
24 // whether the view rows can be reordered (via vertical drag & drop)
26 'action_buttons': true,
27 //whether the editable property of the view has to be disabled
28 'disable_editable_mode': false,
32 'click thead th.oe_sortable[data-id]': 'sort_by_column'
35 * Core class for list-type displays.
37 * As a view, needs a number of view-related parameters to be correctly
38 * instantiated, provides options and overridable methods for behavioral
41 * See constructor parameters and method documentations for information on
42 * the default behaviors and possible options for the list view.
44 * @constructs instance.web.ListView
45 * @extends instance.web.View
47 * @param parent parent object
48 * @param {instance.web.DataSet} dataset the dataset the view should work with
49 * @param {String} view_id the listview's identifier, if any
50 * @param {Object} options A set of options used to configure the view
51 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
52 * @param {Boolean} [options.header=true] should the list's header be displayed
53 * @param {Boolean} [options.deletable=true] are the list rows deletable
54 * @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.
55 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
56 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
58 init: function(parent, dataset, view_id, options) {
61 this.set_default_options(_.extend({}, this.defaults, options || {}));
62 this.dataset = dataset;
63 this.model = dataset.model;
64 this.view_id = view_id;
65 this.previous_colspan = null;
71 this.records = new Collection();
73 this.set_groups(new (this.options.GroupsType)(this));
75 if (this.dataset instanceof instance.web.DataSetStatic) {
76 this.groups.datagroup = new StaticDataGroup(this.dataset);
78 this.groups.datagroup = new DataGroup(
81 dataset.get_context());
82 this.groups.datagroup.sort = this.dataset._sort;
86 this.records.bind('change', function (event, record, key) {
87 if (!_(self.aggregate_columns).chain()
88 .pluck('name').contains(key).value()) {
91 self.compute_aggregates();
97 view_loading: function(r) {
98 return this.load_list(r);
100 set_default_options: function (options) {
101 this._super(options);
102 _.defaults(this.options, {
103 GroupsType: instance.web.ListView.Groups,
104 ListType: instance.web.ListView.List
109 * Retrieves the view's number of records per page (|| section)
111 * options > defaults > parent.action.limit > indefinite
113 * @returns {Number|null}
116 if (this._limit === undefined) {
117 this._limit = (this.options.limit
118 || this.defaults.limit
119 || (this.getParent().action || {}).limit
125 * Set a custom Group construct as the root of the List View.
127 * @param {instance.web.ListView.Groups} groups
129 set_groups: function (groups) {
132 $(this.groups).unbind("selected deleted action row_link");
136 this.groups = groups;
137 $(this.groups).bind({
138 'selected': function (e, ids, records, deselected) {
139 self.do_select(ids, records, deselected);
141 'deleted': function (e, ids) {
144 'action': function (e, action_name, id, callback) {
145 self.do_button_action(action_name, id, callback);
147 'row_link': function (e, id, dataset, view) {
148 self.do_activate_record(dataset.index, id, dataset, view);
153 * View startup method, the default behavior is to set the ``oe_list``
154 * class on its root element and to perform an RPC load call.
156 * @returns {$.Deferred} loading promise
159 this.$el.addClass('oe_list');
160 return this._super();
163 * Returns the style for the provided record in the current view (from the
164 * ``@colors`` and ``@fonts`` attributes)
166 * @param {Record} record record for the current row
167 * @returns {String} CSS style declaration
169 style_for: function (record) {
172 var context = _.extend({}, record.attributes, {
173 uid: this.session.uid,
174 current_date: new Date().toString('yyyy-MM-dd')
175 // TODO: time, datetime, relativedelta
181 for(i=0, len=this.fonts.length; i<len; ++i) {
182 pair = this.fonts[i];
184 expression = pair[1];
185 if (py.evaluate(expression, context).toJSON()) {
188 style += 'font-weight: bold;';
191 style += 'font-style: italic;';
194 style += 'text-decoration: underline;';
201 if (!this.colors) { return style; }
202 for(i=0, len=this.colors.length; i<len; ++i) {
203 pair = this.colors[i];
205 expression = pair[1];
206 if (py.evaluate(expression, context).toJSON()) {
207 return style += 'color: ' + color + ';';
209 // TODO: handle evaluation errors
214 * Called after loading the list view's description, sets up such things
215 * as the view table's columns, renders the table itself and hooks up the
216 * various table-level and row-level DOM events (action buttons, deletion
217 * buttons, selection of records, [New] button, selection of a given
220 * Sets up the following:
222 * * Processes arch and fields to generate a complete field descriptor for each field
223 * * Create the table itself and allocate visible columns
224 * * Hook in the top-level (header) [New|Add] and [Delete] button
225 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
226 * * Sets up event handlers for action buttons and per-row deletion button
227 * * Hooks global callback for clicking on a row
228 * * Sets up its sidebar, if any
230 * @param {Object} data wrapped fields_view_get result
231 * @param {Object} data.fields_view fields_view_get result (processed)
232 * @param {Object} data.fields_view.fields mapping of fields for the current model
233 * @param {Object} data.fields_view.arch current list view descriptor
234 * @param {Boolean} grouped Is the list view grouped
236 load_list: function(data) {
238 this.fields_view = data;
239 this.name = "" + this.fields_view.arch.attrs.string;
241 if (this.fields_view.arch.attrs.colors) {
242 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
244 .map(function(color_pair) {
245 var pair = color_pair.split(':'),
248 return [color, py.parse(py.tokenize(expr)), expr];
252 if (this.fields_view.arch.attrs.fonts) {
253 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
254 .map(function(font_pair) {
255 var pair = font_pair.split(':'),
258 return [font, py.parse(py.tokenize(expr)), expr];
262 this.setup_columns(this.fields_view.fields, this.grouped);
264 this.$el.html(QWeb.render(this._template, this));
265 this.$el.addClass(this.fields_view.arch.attrs['class']);
269 this.$el.find('.oe_list_record_selector').click(function(){
270 self.$el.find('.oe_list_record_selector input').prop('checked',
271 self.$el.find('.oe_list_record_selector').prop('checked') || false);
272 var selection = self.groups.get_selection();
273 $(self.groups).trigger(
274 'selected', [selection.ids, selection.records]);
278 if (!this.$buttons) {
279 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
280 if (this.options.$buttons) {
281 this.$buttons.appendTo(this.options.$buttons);
283 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
285 this.$buttons.find('.oe_list_add')
286 .click(this.proxy('do_add_record'))
287 .prop('disabled', this.grouped);
292 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
293 if (this.options.$buttons) {
294 this.$pager.appendTo(this.options.$pager);
296 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
300 .on('click', 'a[data-pager-action]', function () {
302 var max_page = Math.floor(self.dataset.size() / self.limit());
303 switch ($this.data('pager-action')) {
305 self.page = 0; break;
307 self.page = max_page - 1;
310 self.page += 1; break;
312 self.page -= 1; break;
315 self.page = max_page;
316 } else if (self.page > max_page) {
319 self.reload_content();
320 }).find('.oe_list_pager_state')
321 .click(function (e) {
325 var $select = $('<select>')
326 .appendTo($this.empty())
327 .click(function (e) {e.stopPropagation();})
328 .append('<option value="80">80</option>' +
329 '<option value="200">200</option>' +
330 '<option value="500">500</option>' +
331 '<option value="2000">2000</option>' +
332 '<option value="NaN">' + _t("Unlimited") + '</option>')
333 .change(function () {
334 var val = parseInt($select.val(), 10);
335 self._limit = (isNaN(val) ? null : val);
337 self.reload_content();
339 $(this).trigger('change');
341 .val(self._limit || 'NaN');
346 if (!this.sidebar && this.options.$sidebar) {
347 this.sidebar = new instance.web.Sidebar(this);
348 this.sidebar.appendTo(this.options.$sidebar);
349 this.sidebar.add_items('other', _.compact([
350 { label: _t("Export"), callback: this.on_sidebar_export },
351 self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
353 this.sidebar.add_toolbar(this.fields_view.toolbar);
354 this.sidebar.$el.hide();
357 if(this.dataset._sort.length){
358 if(this.dataset._sort[0].indexOf('-') == -1){
359 this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
361 this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
364 this.trigger('list_view_loaded', data, this.grouped);
366 sort_by_column: function (e) {
368 var $column = $(e.currentTarget);
369 var col_name = $column.data('id');
370 var field = this.fields_view.fields[col_name];
371 // test if the field is a function field with store=false, since it's impossible
372 // for the server to sort those fields we desactivate the feature
373 if (field && field.store === false) {
376 this.dataset.sort(col_name);
377 if($column.hasClass("sortdown") || $column.hasClass("sortup")) {
378 $column.toggleClass("sortup sortdown");
380 $column.addClass("sortdown");
382 $column.siblings('.oe_sortable').removeClass("sortup sortdown");
384 this.reload_content();
387 * Configures the ListView pager based on the provided dataset's information
389 * Horrifying side-effect: sets the dataset's data on this.dataset?
391 * @param {instance.web.DataSet} dataset
393 configure_pager: function (dataset) {
394 this.dataset.ids = dataset.ids;
396 if (dataset._length) {
397 this.dataset._length = dataset._length;
400 var total = dataset.size();
401 var limit = this.limit() || total;
405 this.$pager.css("display", "");
406 this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
409 var range_start = this.page * limit + 1;
410 var range_stop = range_start - 1 + limit;
411 if (range_stop > total) {
414 spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
417 this.$pager.find('.oe_list_pager_state').text(spager);
420 * Sets up the listview's columns: merges view and fields data, move
421 * grouped-by columns to the front of the columns list and make them all
424 * @param {Object} fields fields_view_get's fields section
425 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
427 setup_columns: function (fields, grouped) {
428 var registry = instance.web.list.columns;
429 this.columns.splice(0, this.columns.length);
430 this.columns.push.apply(this.columns,
431 _(this.fields_view.arch.children).map(function (field) {
432 var id = field.attrs.name;
433 return registry.for_(id, fields[id], field);
436 this.columns.unshift(
437 new instance.web.list.MetaColumn('_group', _t("Group")));
440 this.visible_columns = _.filter(this.columns, function (column) {
441 return column.invisible !== '1';
444 this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
447 * Used to handle a click on a table row, if no other handler caught the
450 * The default implementation asks the list view's view manager to switch
451 * to a different view (by calling
452 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
453 * provided record index (within the current list view's dataset).
455 * If the index is null, ``switch_to_record`` asks for the creation of a
458 * @param {Number|void} index the record index (in the current dataset) to switch to
459 * @param {String} [view="page"] the view type to switch to
461 select_record:function (index, view) {
462 view = view || index === null || index === undefined ? 'form' : 'form';
463 this.dataset.index = index;
464 _.delay(_.bind(function () {
465 this.do_switch_view(view);
468 do_show: function () {
471 this.$buttons.show();
477 do_hide: function () {
479 this.sidebar.$el.hide();
482 this.$buttons.hide();
490 * Reloads the list view based on the current settings (dataset & al)
493 * @param {Boolean} [grouped] Should the list be displayed grouped
494 * @param {Object} [context] context to send the server while loading the view
496 reload_view: function (grouped, context, initial) {
497 return this.load_view(context);
500 * re-renders the content of the list view
502 * @returns {$.Deferred} promise to content reloading
504 reload_content: synchronized(function () {
506 self.$el.find('.oe_list_record_selector').prop('checked', false);
507 this.records.reset();
508 var reloaded = $.Deferred();
509 this.$el.find('.oe_list_content').append(
510 this.groups.render(function () {
511 // Keep '=='. This is not a mistake, this is a wanted behaviour to match null & undefined
512 if (self.dataset.index == null) {
513 if (self.records.length) {
514 self.dataset.index = 0;
516 } else if (self.dataset.index >= self.records.length) {
517 self.dataset.index = 0;
520 self.compute_aggregates();
527 return reloaded.promise();
529 reload: function () {
530 return this.reload_content();
532 reload_record: function (record) {
534 return this.dataset.read_ids(
536 _.pluck(_(this.columns).filter(function (r) {
537 return r.tag === 'field';
539 ).done(function (records) {
540 var values = records[0];
542 self.records.remove(record);
545 _(_.keys(values)).each(function(key){
546 record.set(key, values[key], {silent: true});
548 record.trigger('change', record);
552 do_load_state: function(state, warm) {
554 if (state.page && this.page !== state.page) {
555 this.page = state.page;
559 if (_.isString(state.limit)) {
562 if (state.limit !== this._limit) {
563 this._limit = state.limit;
568 this.reload_content();
572 * Handler for the result of eval_domain_and_context, actually perform the
575 * @param {Object} results results of evaluating domain and process for a search
577 do_search: function (domain, context, group_by) {
579 this.groups.datagroup = new DataGroup(
580 this, this.model, domain, context, group_by);
581 this.groups.datagroup.sort = this.dataset._sort;
583 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
586 this.no_leaf = !!context['group_by_no_leaf'];
587 this.grouped = !!group_by;
589 return this.alive(this.load_view(context)).then(
590 this.proxy('reload_content'));
593 * Handles the signal to delete lines from the records list
595 * @param {Array} ids the ids of the records to delete
597 do_delete: function (ids) {
598 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
602 return $.when(this.dataset.unlink(ids)).done(function () {
603 _(ids).each(function (id) {
604 self.records.remove(self.records.get(id));
606 self.configure_pager(self.dataset);
607 self.compute_aggregates();
611 * Handles the signal indicating that a new record has been selected
613 * @param {Array} ids selected record ids
614 * @param {Array} records selected record values
616 do_select: function (ids, records, deselected) {
617 // uncheck header hook if at least one row has been deselected
619 this.$('.oe_list_record_selector').prop('checked', false);
623 this.dataset.index = 0;
625 this.sidebar.$el.hide();
627 this.compute_aggregates();
631 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
633 this.options.$sidebar.show();
634 this.sidebar.$el.show();
637 this.compute_aggregates(_(records).map(function (record) {
638 return {count: 1, values: record};
642 * Handles action button signals on a record
644 * @param {String} name action name
645 * @param {Object} id id of the record the action should be called on
646 * @param {Function} callback should be called after the action is executed, if non-null
648 do_button_action: function (name, id, callback) {
649 this.handle_button(name, id, callback);
652 * Base handling of buttons, can be called when overriding do_button_action
653 * in order to bypass parent overrides.
655 * The callback will be provided with the ``id`` as its parameter, in case
656 * handle_button's caller had to alter the ``id`` (or even create one)
657 * while not being ``callback``'s creator.
659 * This method should not be overridden.
661 * @param {String} name action name
662 * @param {Object} id id of the record the action should be called on
663 * @param {Function} callback should be called after the action is executed, if non-null
665 handle_button: function (name, id, callback) {
666 var action = _.detect(this.columns, function (field) {
667 return field.name === name;
669 if (!action) { return; }
670 if ('confirm' in action && !window.confirm(action.confirm)) {
674 var c = new instance.web.CompoundContext();
675 c.set_eval_context(_.extend({
678 active_model: this.dataset.model
679 }, this.records.get(id).toContext()));
680 if (action.context) {
681 c.add(action.context);
684 this.do_execute_action(
685 action, this.dataset, id, _.bind(callback, null, id));
688 * Handles the activation of a record (clicking on it)
690 * @param {Number} index index of the record in the dataset
691 * @param {Object} id identifier of the activated record
692 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
694 do_activate_record: function (index, id, dataset, view) {
695 this.dataset.ids = dataset.ids;
696 this.select_record(index, view);
699 * Handles signal for the addition of a new record (can be a creation,
700 * can be the addition from a remote source, ...)
702 * The default implementation is to switch to a new record on the form view
704 do_add_record: function () {
705 this.select_record(null);
708 * Handles deletion of all selected lines
710 do_delete_selected: function () {
711 var ids = this.groups.get_selection().ids;
713 this.do_delete(this.groups.get_selection().ids);
715 this.do_warn(_t("Warning"), _t("You must select at least one record."));
719 * Computes the aggregates for the current list view, either on the
720 * records provided or on the records of the internal
721 * :js:class:`~instance.web.ListView.Group`, by calling
722 * :js:func:`~instance.web.ListView.group.get_records`.
724 * Then displays the aggregates in the table through
725 * :js:method:`~instance.web.ListView.display_aggregates`.
727 * @param {Array} [records]
729 compute_aggregates: function (records) {
730 var columns = _(this.aggregate_columns).filter(function (column) {
731 return column['function']; });
732 if (_.isEmpty(columns)) { return; }
734 if (_.isEmpty(records)) {
735 records = this.groups.get_records();
737 records = _(records).compact();
739 var count = 0, sums = {};
740 _(columns).each(function (column) {
741 switch (column['function']) {
743 sums[column.id] = -Infinity;
746 sums[column.id] = Infinity;
752 _(records).each(function (record) {
753 count += record.count || 1;
754 _(columns).each(function (column) {
755 var field = column.id,
756 value = record.values[field];
757 switch (column['function']) {
759 sums[field] += value;
762 sums[field] += record.count * value;
765 if (sums[field] > value) {
770 if (sums[field] < value) {
779 _(columns).each(function (column) {
780 var field = column.id;
781 switch (column['function']) {
783 aggregates[field] = {value: sums[field] / count};
786 aggregates[field] = {value: sums[field]};
790 this.display_aggregates(aggregates);
792 display_aggregates: function (aggregation) {
794 var $footer_cells = this.$el.find('.oe_list_footer');
795 _(this.aggregate_columns).each(function (column) {
796 if (!column['function']) {
800 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
801 .html(column.format(aggregation, { process_modifiers: false }));
804 get_selected_ids: function() {
805 var ids = this.groups.get_selection().ids;
809 * Calculate the active domain of the list view. This should be done only
810 * if the header checkbox has been checked. This is done by evaluating the
811 * search results, and then adding the dataset domain (i.e. action domain).
813 get_active_domain: function () {
815 if (this.$('.oe_list_record_selector').prop('checked')) {
816 var search_view = this.getParent().searchview;
817 var search_data = search_view.build_search_data();
818 return instance.web.pyeval.eval_domains_and_contexts({
819 domains: search_data.domains,
820 contexts: search_data.contexts,
821 group_by_seq: search_data.groupbys || []
822 }).then(function (results) {
823 var domain = self.dataset.domain.concat(results.domain || []);
828 return $.Deferred().resolve();
832 * Adds padding columns at the start or end of all table rows (including
835 * @param {Number} count number of columns to add
836 * @param {Object} options
837 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
838 * @param {Object} [options.except] content row to not pad
840 pad_columns: function (count, options) {
841 options = options || {};
842 // padding for action/pager header
843 var $first_header = this.$el.find('thead tr:first th');
844 var colspan = $first_header.attr('colspan');
846 if (!this.previous_colspan) {
847 this.previous_colspan = colspan;
849 $first_header.attr('colspan', parseInt(colspan, 10) + count);
851 // Padding for column titles, footer and data rows
853 .find('.oe_list_header_columns, tr:not(thead tr)')
854 .not(options['except']);
855 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
856 if (options.position === 'before') {
857 $rows.prepend(newcols);
859 $rows.append(newcols);
863 * Removes all padding columns of the table
865 unpad_columns: function () {
866 this.$el.find('.oe_list_padding').remove();
867 if (this.previous_colspan) {
869 .find('thead tr:first th')
870 .attr('colspan', this.previous_colspan);
871 this.previous_colspan = null;
874 no_result: function () {
875 this.$el.find('.oe_view_nocontent').remove();
876 if (this.groups.group_by
877 || !this.options.action
878 || !this.options.action.help) {
881 this.$el.find('table:first').hide();
883 $('<div class="oe_view_nocontent">').html(this.options.action.help)
885 var create_nocontent = this.$buttons;
886 this.$el.find('.oe_view_nocontent').click(function() {
887 create_nocontent.openerpBounce();
891 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
893 * List display for the ListView, handles basic DOM events and transforms
894 * them in the relevant higher-level events, to which the list view (or
895 * other consumers) can subscribe.
897 * Events on this object are registered via jQuery.
902 * Triggered when a row is selected (using check boxes), provides an
903 * array of ids of all the selected records.
905 * Triggered when deletion buttons are hit, provide an array of ids of
906 * all the records being marked for suppression.
908 * Triggered when an action button is clicked, provides two parameters:
910 * * The name of the action to execute (as a string)
911 * * The id of the record to execute the action on
913 * Triggered when a row of the table is clicked, provides the index (in
914 * the rows array) and id of the selected record to the handle function.
916 * @constructs instance.web.ListView.List
917 * @extends instance.web.Class
919 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
921 init: function (group, opts) {
924 this.view = group.view;
925 this.session = this.view.session;
927 this.options = opts.options;
928 this.columns = opts.columns;
929 this.dataset = opts.dataset;
930 this.records = opts.records;
932 this.record_callbacks = {
933 'remove': function (event, record) {
934 var id = record.get('id');
935 self.dataset.remove_ids([id]);
936 var $row = self.$current.children('[data-id=' + id + ']');
937 var index = $row.data('index');
940 'reset': function () { return self.on_records_reset(); },
941 'change': function (event, record, attribute, value, old_value) {
943 if (attribute === 'id') {
945 throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
946 JSON.stringify(record.attributes) ));
948 self.dataset.add_ids([value], self.records.indexOf(record));
949 // Set id on new record
950 $row = self.$current.children('[data-id=false]');
952 $row = self.$current.children(
953 '[data-id=' + record.get('id') + ']');
955 $row.replaceWith(self.render_record(record));
957 'add': function (ev, records, record, index) {
958 var $new_row = $(self.render_record(record));
959 var id = record.get('id');
960 if (id) { self.dataset.add_ids([id], index); }
963 $new_row.prependTo(self.$current);
965 var previous_record = records.at(index-1),
966 $previous_sibling = self.$current.children(
967 '[data-id=' + previous_record.get('id') + ']');
968 $new_row.insertAfter($previous_sibling);
972 _(this.record_callbacks).each(function (callback, event) {
973 this.records.bind(event, callback);
976 this.$current = $('<tbody>')
977 .delegate('input[readonly=readonly]', 'click', function (e) {
979 Against all logic and sense, as of right now @readonly
980 apparently does nothing on checkbox and radio inputs, so
981 the trick of using @readonly to have, well, readonly
982 checkboxes (which still let clicks go through) does not
983 work out of the box. We *still* need to preventDefault()
984 on the event, otherwise the checkbox's state *will* toggle
989 .delegate('th.oe_list_record_selector', 'click', function (e) {
991 var selection = self.get_selection();
992 var checked = $(e.currentTarget).find('input').prop('checked');
994 'selected', [selection.ids, selection.records, ! checked]);
996 .delegate('td.oe_list_record_delete button', 'click', function (e) {
998 var $row = $(e.target).closest('tr');
999 $(self).trigger('deleted', [[self.row_id($row)]]);
1001 .delegate('td.oe_list_field_cell button', 'click', function (e) {
1002 e.stopPropagation();
1003 var $target = $(e.currentTarget),
1004 field = $target.closest('td').data('field'),
1005 $row = $target.closest('tr'),
1006 record_id = self.row_id($row);
1008 if ($target.attr('disabled')) {
1011 $target.attr('disabled', 'disabled');
1013 // note: $.data converts data to number if it's composed only
1014 // of digits, nice when storing actual numbers, not nice when
1015 // storing strings composed only of digits. Force the action
1016 // name to be a string
1017 $(self).trigger('action', [field.toString(), record_id, function (id) {
1018 $target.removeAttr('disabled');
1019 return self.reload_record(self.records.get(id));
1022 .delegate('a', 'click', function (e) {
1023 e.stopPropagation();
1025 .delegate('tr', 'click', function (e) {
1026 var row_id = self.row_id(e.currentTarget);
1028 e.stopPropagation();
1029 if (!self.dataset.select_id(row_id)) {
1030 throw new Error(_t("Could not find id in dataset"));
1032 self.row_clicked(e);
1036 row_clicked: function (e, view) {
1039 [this.dataset.ids[this.dataset.index],
1040 this.dataset, view]);
1042 render_cell: function (record, column) {
1044 if(column.type === 'reference') {
1045 value = record.get(column.id);
1047 // Ensure that value is in a reference "shape", otherwise we're
1048 // going to loop on performing name_get after we've resolved (and
1049 // set) a human-readable version. m2o does not have this issue
1050 // because the non-human-readable is just a number, where the
1051 // human-readable version is a pair
1052 if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
1053 // reference values are in the shape "$model,$id" (as a
1054 // string), we need to split and name_get this pair in order
1055 // to get a correctly displayable value in the field
1056 var model = ref_match[1],
1057 id = parseInt(ref_match[2], 10);
1058 new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
1059 if (!names.length) { return; }
1060 record.set(column.id, names[0][1]);
1063 } else if (column.type === 'many2one') {
1064 value = record.get(column.id);
1065 // m2o values are usually name_get formatted, [Number, String]
1066 // pairs, but in some cases only the id is provided. In these
1067 // cases, we need to perform a name_get call to fetch the actual
1068 // displayable value
1069 if (typeof value === 'number' || value instanceof Number) {
1070 // fetch the name, set it on the record (in the right field)
1071 // and let the various registered events handle refreshing the
1073 new instance.web.DataSet(this.view, column.relation)
1074 .name_get([value]).done(function (names) {
1075 if (!names.length) { return; }
1076 record.set(column.id, names[0]);
1079 } else if (column.type === 'many2many') {
1080 value = record.get(column.id);
1081 // non-resolved (string) m2m values are arrays
1082 if (value instanceof Array && !_.isEmpty(value)
1083 && !record.get(column.id + '__display')) {
1085 // they come in two shapes:
1086 if (value[0] instanceof Array) {
1087 var command = value[0];
1088 // 1. an array of m2m commands (usually (6, false, ids))
1089 if (command[0] !== 6) {
1090 throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
1094 // 2. an array of ids
1097 new instance.web.Model(column.relation)
1098 .call('name_get', [ids]).done(function (names) {
1099 // FIXME: nth horrible hack in this poor listview
1100 record.set(column.id + '__display',
1101 _(names).pluck(1).join(', '));
1102 record.set(column.id, ids);
1105 record.set(column.id, false);
1108 return column.format(record.toForm().data, {
1109 model: this.dataset.model,
1110 id: record.get('id')
1113 render: function () {
1114 this.$current.empty().append(
1115 QWeb.render('ListView.rows', _.extend({
1116 render_cell: function () {
1117 return self.render_cell.apply(self, arguments); }
1119 this.pad_table_to(4);
1121 pad_table_to: function (count) {
1122 if (this.records.length >= count ||
1123 _(this.columns).any(function(column) { return column.meta; })) {
1127 if (this.options.selectable) {
1128 cells.push('<th class="oe_list_record_selector"></td>');
1130 _(this.columns).each(function(column) {
1131 if (column.invisible === '1') {
1134 if (column.tag === 'button') {
1135 cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
1137 cells.push('<td title="' + column.string + '"> </td>');
1140 if (this.options.deletable) {
1141 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1143 cells.unshift('<tr>');
1144 cells.push('</tr>');
1146 var row = cells.join('');
1148 .children('tr:not([data-id])').remove().end()
1149 .append(new Array(count - this.records.length + 1).join(row));
1152 * Gets the ids of all currently selected records, if any
1153 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1155 get_selection: function () {
1156 var result = {ids: [], records: []};
1157 if (!this.options.selectable) {
1160 var records = this.records;
1161 this.$current.find('th.oe_list_record_selector input:checked')
1162 .closest('tr').each(function () {
1163 var record = records.get($(this).data('id'));
1164 result.ids.push(record.get('id'));
1165 result.records.push(record.attributes);
1170 * Returns the identifier of the object displayed in the provided table
1173 * @param {Object} row the selected table row
1174 * @returns {Number|String} the identifier of the row's object
1176 row_id: function (row) {
1177 return $(row).data('id');
1180 * Death signal, cleans up list display
1182 on_records_reset: function () {
1183 _(this.record_callbacks).each(function (callback, event) {
1184 this.records.unbind(event, callback);
1186 if (!this.$current) { return; }
1187 this.$current.remove();
1189 get_records: function () {
1190 return this.records.map(function (record) {
1191 return {count: 1, values: record.attributes};
1195 * Reloads the provided record by re-reading its content from the server.
1197 * @param {Record} record
1198 * @returns {$.Deferred} promise to the finalization of the reloading
1200 reload_record: function (record) {
1201 return this.view.reload_record(record);
1204 * Renders a list record to HTML
1206 * @param {Record} record index of the record to render in ``this.rows``
1207 * @returns {String} QWeb rendering of the selected record
1209 render_record: function (record) {
1211 var index = this.records.indexOf(record);
1212 return QWeb.render('ListView.row', {
1213 columns: this.columns,
1214 options: this.options,
1216 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1218 render_cell: function () {
1219 return self.render_cell.apply(self, arguments); }
1223 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1224 passthrough_events: 'action deleted row_link',
1226 * Grouped display for the ListView. Handles basic DOM events and interacts
1227 * with the :js:class:`~DataGroup` bound to it.
1229 * Provides events similar to those of
1230 * :js:class:`~instance.web.ListView.List`
1232 * @constructs instance.web.ListView.Groups
1233 * @extends instance.web.Class
1235 * @param {instance.web.ListView} view
1236 * @param {Object} [options]
1237 * @param {Collection} [options.records]
1238 * @param {Object} [options.options]
1239 * @param {Array} [options.columns]
1241 init: function (view, options) {
1242 options = options || {};
1244 this.records = options.records || view.records;
1245 this.options = options.options || view.options;
1246 this.columns = options.columns || view.columns;
1247 this.datagroup = null;
1255 this.records.bind('reset', function () {
1256 return self.on_records_reset(); });
1258 make_fragment: function () {
1259 return document.createDocumentFragment();
1262 * Returns a DOM node after which a new tbody can be inserted, so that it
1263 * follows the provided row.
1265 * Necessary to insert the result of a new group or list view within an
1266 * existing groups render, without losing track of the groups's own
1269 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1270 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1272 point_insertion: function (row) {
1274 var red_letter_tboday = $row.closest('tbody')[0];
1276 var $next_siblings = $row.nextAll();
1277 if ($next_siblings.length) {
1278 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1280 $root_kanal.append($next_siblings);
1281 this.elements.splice(
1282 _.indexOf(this.elements, red_letter_tboday),
1286 return red_letter_tboday;
1288 make_paginator: function () {
1290 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1291 .click(function (e) {
1292 e.stopPropagation();
1295 self.$row.closest('tbody').next()
1296 .replaceWith(self.render());
1298 var $next = $('<button type="button" data-pager-action="next">></button>')
1299 .click(function (e) {
1300 e.stopPropagation();
1303 self.$row.closest('tbody').next()
1304 .replaceWith(self.render());
1306 this.$row.children().last()
1307 .addClass('oe_list_group_pagination')
1309 .append('<span class="oe_list_pager_state"></span>')
1312 open: function (point_insertion) {
1313 this.render().insertAfter(point_insertion);
1315 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1316 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1317 if (no_subgroups && records_terminated) {
1318 this.make_paginator();
1321 close: function () {
1322 this.$row.children().last().empty();
1323 this.records.reset();
1326 * Prefixes ``$node`` with floated spaces in order to indent it relative
1327 * to its own left margin/baseline
1329 * @param {jQuery} $node jQuery object to indent
1330 * @param {Number} level current nesting level, >= 1
1331 * @returns {jQuery} the indentation node created
1333 indent: function ($node, level) {
1335 .css({'float': 'left', 'white-space': 'pre'})
1336 .text(new Array(level).join(' '))
1339 render_groups: function (datagroups) {
1341 var placeholder = this.make_fragment();
1342 _(datagroups).each(function (group) {
1343 if (self.children[group.value]) {
1344 self.records.proxy(group.value).reset();
1345 delete self.children[group.value];
1347 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1348 records: self.records.proxy(group.value),
1349 options: self.options,
1350 columns: self.columns
1352 self.bind_child_events(child);
1353 child.datagroup = group;
1355 var $row = child.$row = $('<tr class="oe_group_header">');
1356 if (group.openable && group.length) {
1357 $row.click(function (e) {
1358 if (!$row.data('open')) {
1359 $row.data('open', true)
1360 .find('span.ui-icon')
1361 .removeClass('ui-icon-triangle-1-e')
1362 .addClass('ui-icon-triangle-1-s');
1363 child.open(self.point_insertion(e.currentTarget));
1365 $row.removeData('open')
1366 .find('span.ui-icon')
1367 .removeClass('ui-icon-triangle-1-s')
1368 .addClass('ui-icon-triangle-1-e');
1370 // force recompute the selection as closing group reset properties
1371 var selection = self.get_selection();
1372 $(self).trigger('selected', [selection.ids, this.records]);
1376 placeholder.appendChild($row[0]);
1378 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1379 // Don't fill this if group_by_no_leaf but no group_by
1380 if (group.grouped_on) {
1382 row_data[group.grouped_on] = group;
1383 var group_label = _t("Undefined");
1384 var group_column = _(self.columns).detect(function (column) {
1385 return column.id === group.grouped_on; });
1388 group_label = group_column.format(row_data, {
1389 value_if_empty: _t("Undefined"),
1390 process_modifiers: false
1393 group_label = _.str.escapeHTML(row_data[group_column.id].value);
1396 group_label = group.value;
1397 if (group_label instanceof Array) {
1398 group_label = group_label[1];
1400 if (group_label === false) {
1401 group_label = _t('Undefined');
1403 group_label = _.str.escapeHTML(group_label);
1406 // group_label is html-clean (through format or explicit
1407 // escaping if format failed), can inject straight into HTML
1408 $group_column.html(_.str.sprintf(_t("%s (%d)"),
1409 group_label, group.length));
1411 if (group.length && group.openable) {
1412 // Make openable if not terminal group & group_by_no_leaf
1413 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1415 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1416 // wonky background position to ensure nothing is displayed
1417 // there but the rest of the behavior is ui-icon's
1418 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1421 self.indent($group_column, group.level);
1423 if (self.options.selectable) {
1424 $row.append('<td>');
1426 _(self.columns).chain()
1427 .filter(function (column) { return column.invisible !== '1'; })
1428 .each(function (column) {
1430 // do not do anything
1431 } else if (column.id in group.aggregates) {
1433 r[column.id] = {value: group.aggregates[column.id]};
1434 $('<td class="oe_number">')
1435 .html(column.format(r, {process_modifiers: false}))
1438 $row.append('<td>');
1441 if (self.options.deletable) {
1442 $row.append('<td class="oe_list_group_pagination">');
1447 bind_child_events: function (child) {
1448 var $this = $(this),
1450 $(child).bind('selected', function (e, _0, _1, deselected) {
1451 // can have selections spanning multiple links
1452 var selection = self.get_selection();
1453 $this.trigger(e, [selection.ids, selection.records, deselected]);
1454 }).bind(this.passthrough_events, function (e) {
1455 // additional positional parameters are provided to trigger as an
1456 // Array, following the event type or event object, but are
1457 // provided to the .bind event handler as *args.
1458 // Convert our *args back into an Array in order to trigger them
1459 // on the group itself, so it can ultimately be forwarded wherever
1460 // it's supposed to go.
1461 var args = Array.prototype.slice.call(arguments, 1);
1462 $this.trigger.call($this, e, args);
1465 render_dataset: function (dataset) {
1467 list = new (this.view.options.ListType)(this, {
1468 options: this.options,
1469 columns: this.columns,
1471 records: this.records
1473 this.bind_child_events(list);
1475 var view = this.view,
1476 limit = view.limit(),
1477 page = this.datagroup.openable ? this.page : view.page;
1479 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field";}), 'name');
1480 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1481 //TODO xmo: investigate why we need to put the setTimeout
1482 return $.async_when().then(function() {
1483 return dataset.read_slice(fields, options).then(function (records) {
1484 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1485 if (self.records.length) {
1486 self.records.reset(null, {silent: true});
1488 if (!self.datagroup.openable) {
1489 view.configure_pager(dataset);
1491 if (dataset.size() == records.length) {
1493 self.$row.find('td.oe_list_group_pagination').empty();
1495 var pages = Math.ceil(dataset.size() / limit);
1497 .find('.oe_list_pager_state')
1498 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1503 .find('button[data-pager-action=previous]')
1505 page === 0 ? 'hidden' : '')
1507 .find('button[data-pager-action=next]')
1509 page === pages - 1 ? 'hidden' : '');
1513 self.records.add(records, {silent: true});
1515 if (_.isEmpty(records)) {
1522 setup_resequence_rows: function (list, dataset) {
1523 // drag and drop enabled if list is not sorted and there is a
1524 // visible column with @widget=handle or "sequence" column in the view.
1525 if ((dataset.sort && dataset.sort())
1526 || !_(this.columns).any(function (column) {
1527 return column.widget === 'handle'
1528 || column.name === 'sequence'; })) {
1531 var sequence_field = _(this.columns).find(function (c) {
1532 return c.widget === 'handle';
1534 var seqname = sequence_field ? sequence_field.name : 'sequence';
1536 // ondrop, move relevant record & fix sequences
1537 list.$current.sortable({
1539 items: '> tr[data-id]',
1542 if (sequence_field) {
1543 list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1545 list.$current.sortable('option', {
1546 start: function (e, ui) {
1547 ui.placeholder.height(ui.item.height());
1549 stop: function (event, ui) {
1550 var to_move = list.records.get(ui.item.data('id')),
1551 target_id = ui.item.prev().data('id'),
1552 from_index = list.records.indexOf(to_move),
1553 target = list.records.get(target_id);
1554 if (list.records.at(from_index - 1) == target) {
1558 list.records.remove(to_move);
1559 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1560 list.records.add(to_move, { at: to });
1562 // resequencing time!
1563 var record, index = to,
1564 // if drag to 1st row (to = 0), start sequencing from 0
1565 // (exclusive lower bound)
1566 seq = to ? list.records.at(to - 1).get(seqname) : 0;
1567 var fct = function (dataset, id, seq) {
1568 $.async_when().done(function () {
1570 attrs[seqname] = seq;
1571 dataset.write(id, attrs);
1574 while (++seq, (record = list.records.at(index++))) {
1575 // write are independent from one another, so we can just
1576 // launch them all at the same time and we don't really
1577 // give a fig about when they're done
1578 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1579 // Accounting > Taxes > Taxes, child tax accounts)
1580 // when synchronous (without setTimeout)
1581 fct(dataset, record.get('id'), seq);
1582 record.set(seqname, seq);
1587 render: function (post_render) {
1589 var $el = $('<tbody>');
1590 this.elements = [$el[0]];
1592 this.datagroup.list(
1593 _(this.view.visible_columns).chain()
1594 .filter(function (column) { return column.tag === 'field';})
1595 .pluck('name').value(),
1598 self.render_groups(groups));
1599 if (post_render) { post_render(); }
1600 }, function (dataset) {
1601 self.render_dataset(dataset).then(function (list) {
1602 self.children[null] = list;
1604 [list.$current.replaceAll($el)[0]];
1605 self.setup_resequence_rows(list, dataset);
1606 }).always(function() {
1607 if (post_render) { post_render(); }
1613 * Returns the ids of all selected records for this group, and the records
1616 get_selection: function () {
1617 var ids = [], records = [];
1620 .each(function (child) {
1621 var selection = child.get_selection();
1622 ids.push.apply(ids, selection.ids);
1623 records.push.apply(records, selection.records);
1626 return {ids: ids, records: records};
1628 on_records_reset: function () {
1630 $(this.elements).remove();
1632 get_records: function () {
1633 if (_(this.children).isEmpty()) {
1634 if (!this.datagroup.length) {
1638 count: this.datagroup.length,
1639 values: this.datagroup.aggregates
1642 return _(this.children).chain()
1643 .map(function (child) {
1644 return child.get_records();
1645 }).flatten().value();
1650 * Serializes concurrent calls to this asynchronous method. The method must
1651 * return a deferred or promise.
1653 * Current-implementation is class-serialized (the mutex is common to all
1654 * instances of the list view). Can be switched to instance-serialized if
1655 * having concurrent list views becomes possible and common.
1657 function synchronized(fn) {
1658 var fn_mutex = new $.Mutex();
1659 return function () {
1660 var args = _.toArray(arguments);
1662 return fn_mutex.exec(fn.bind.apply(fn, args));
1665 var DataGroup = instance.web.Class.extend({
1666 init: function(parent, model, domain, context, group_by, level) {
1667 this.model = new instance.web.Model(model, context, domain);
1668 this.group_by = group_by;
1669 this.context = context;
1670 this.domain = domain;
1672 this.level = level || 0;
1674 list: function (fields, ifGroups, ifRecords) {
1676 if (!_.isEmpty(this.group_by)) {
1677 // ensure group_by fields are read.
1678 fields = _.unique((fields || []).concat(this.group_by));
1680 var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
1681 $.when(query).done(function (querygroups) {
1684 var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
1685 ds._sort = self.sort;
1690 var child_datagroups = _(querygroups).map(function (group) {
1691 var child_context = _.extend(
1692 {}, self.model.context(), group.model.context());
1693 var child_dg = new DataGroup(
1694 self, self.model.name, group.model.domain(),
1695 child_context, group.model._context.group_by,
1697 child_dg.sort = self.sort;
1698 // copy querygroup properties
1699 child_dg.__context = child_context;
1700 child_dg.__domain = group.model.domain();
1701 child_dg.folded = group.get('folded');
1702 child_dg.grouped_on = group.get('grouped_on');
1703 child_dg.length = group.get('length');
1704 child_dg.value = group.get('value');
1705 child_dg.openable = group.get('has_children');
1706 child_dg.aggregates = group.get('aggregates');
1709 ifGroups(child_datagroups);
1713 var StaticDataGroup = DataGroup.extend({
1714 init: function (dataset) {
1715 this.dataset = dataset;
1717 list: function (fields, ifGroups, ifRecords) {
1718 ifRecords(this.dataset);
1725 var Events = /** @lends Events# */{
1727 * @param {String} event event to listen to on the current object, null for all events
1728 * @param {Function} handler event handler to bind to the relevant event
1731 bind: function (event, handler) {
1732 var calls = this['_callbacks'] || (this._callbacks = {});
1734 if (event in calls) {
1735 calls[event].push(handler);
1737 calls[event] = [handler];
1742 * @param {String} event event to unbind on the current object
1743 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1746 unbind: function (event, handler) {
1747 var calls = this._callbacks || {};
1748 if (!(event in calls)) { return this; }
1750 delete calls[event];
1752 var handlers = calls[event];
1754 _(handlers).indexOf(handler),
1760 * @param {String} event
1763 trigger: function (event) {
1765 if (!(calls = this._callbacks)) { return this; }
1766 var callbacks = (calls[event] || []).concat(calls[null] || []);
1767 for(var i=0, length=callbacks.length; i<length; ++i) {
1768 callbacks[i].apply(this, arguments);
1773 var Record = instance.web.Class.extend(/** @lends Record# */{
1775 * @constructs Record
1776 * @extends instance.web.Class
1779 * @param {Object} [data]
1781 init: function (data) {
1782 this.attributes = data || {};
1785 * @param {String} key
1788 get: function (key) {
1789 return this.attributes[key];
1794 * @param {Object} [options]
1795 * @param {Boolean} [options.silent=false]
1798 set: function (key, value, options) {
1799 options = options || {};
1800 var old_value = this.attributes[key];
1801 if (old_value === value) {
1804 this.attributes[key] = value;
1805 if (!options.silent) {
1806 this.trigger('change:' + key, this, value, old_value);
1807 this.trigger('change', this, key, value, old_value);
1812 * Converts the current record to the format expected by form views:
1814 * .. code-block:: javascript
1823 * @returns {Object} record displayable in a form view
1825 toForm: function () {
1826 var form_data = {}, attrs = this.attributes;
1827 for(var k in attrs) {
1828 form_data[k] = {value: attrs[k]};
1831 return {data: form_data};
1834 * Converts the current record to a format expected by context evaluations
1835 * (identical to record.attributes, except m2o fields are their integer
1836 * value rather than a pair)
1838 toContext: function () {
1839 var output = {}, attrs = this.attributes;
1840 for(var k in attrs) {
1842 if (typeof val !== 'object') {
1844 } else if (val instanceof Array) {
1847 throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
1853 Record.include(Events);
1854 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1856 * Smarter collections, with events, very strongly inspired by Backbone's.
1858 * Using a "dumb" array of records makes synchronization between the
1861 * @constructs Collection
1862 * @extends instance.web.Class
1865 * @param {Array} [records] records to initialize the collection with
1866 * @param {Object} [options]
1868 init: function (records, options) {
1869 options = options || {};
1870 _.bindAll(this, '_onRecordEvent');
1875 this._key = options.key;
1876 this._parent = options.parent;
1883 * @param {Object|Array} record
1884 * @param {Object} [options]
1885 * @param {Number} [options.at]
1886 * @param {Boolean} [options.silent=false]
1889 add: function (record, options) {
1890 options = options || {};
1891 var records = record instanceof Array ? record : [record];
1893 for(var i=0, length=records.length; i<length; ++i) {
1894 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1895 instance_.bind(null, this._onRecordEvent);
1896 this._byId[instance_.get('id')] = instance_;
1897 if (options.at === undefined || options.at === null) {
1898 this.records.push(instance_);
1899 if (!options.silent) {
1900 this.trigger('add', this, instance_, this.records.length-1);
1903 var insertion_index = options.at + i;
1904 this.records.splice(insertion_index, 0, instance_);
1905 if (!options.silent) {
1906 this.trigger('add', this, instance_, insertion_index);
1915 * Get a record by its index in the collection, can also take a group if
1916 * the collection is not degenerate
1918 * @param {Number} index
1919 * @param {String} [group]
1920 * @returns {Record|undefined}
1922 at: function (index, group) {
1924 var groups = group.split('.');
1925 return this._proxies[groups[0]].at(index, groups.join('.'));
1927 return this.records[index];
1930 * Get a record by its database id
1932 * @param {Number} id
1933 * @returns {Record|undefined}
1935 get: function (id) {
1936 if (!_(this._proxies).isEmpty()) {
1938 _(this._proxies).detect(function (proxy) {
1939 record = proxy.get(id);
1944 return this._byId[id];
1947 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1948 * the subtree's group
1950 * @param {String} section group path section
1951 * @returns {Collection}
1953 proxy: function (section) {
1954 this._proxies[section] = new Collection(null, {
1957 }).bind(null, this._onRecordEvent);
1958 return this._proxies[section];
1961 * @param {Array} [records]
1964 reset: function (records, options) {
1965 options = options || {};
1966 _(this._proxies).each(function (proxy) {
1970 _(this.records).invoke('unbind', null, this._onRecordEvent);
1977 if (!options.silent) {
1978 this.trigger('reset', this);
1983 * Removes the provided record from the collection
1985 * @param {Record} record
1988 remove: function (record) {
1989 var index = this.indexOf(record);
1991 _(this._proxies).each(function (proxy) {
1992 proxy.remove(record);
1997 record.unbind(null, this._onRecordEvent);
1998 this.records.splice(index, 1);
1999 delete this._byId[record.get('id')];
2001 this.trigger('remove', record, this);
2005 _onRecordEvent: function (event) {
2007 // don't propagate reset events
2008 case 'reset': return;
2010 var record = arguments[1];
2011 var new_value = arguments[2];
2012 var old_value = arguments[3];
2013 // [change:id, record, new_value, old_value]
2014 if (this._byId[old_value] === record) {
2015 delete this._byId[old_value];
2016 this._byId[new_value] = record;
2020 this.trigger.apply(this, arguments);
2023 // underscore-type methods
2024 find: function (callback) {
2026 for(var section in this._proxies) {
2027 if (!this._proxies.hasOwnProperty(section)) {
2030 if ((record = this._proxies[section].find(callback))) {
2034 for(var i=0; i<this.length; ++i) {
2035 record = this.records[i];
2036 if (callback(record)) {
2041 each: function (callback) {
2042 for(var section in this._proxies) {
2043 if (this._proxies.hasOwnProperty(section)) {
2044 this._proxies[section].each(callback);
2047 for(var i=0; i<this.length; ++i) {
2048 callback(this.records[i]);
2051 map: function (callback) {
2053 this.each(function (record) {
2054 results.push(callback(record));
2058 pluck: function (fieldname) {
2059 return this.map(function (record) {
2060 return record.get(fieldname);
2063 indexOf: function (record) {
2064 return _(this.records).indexOf(record);
2066 succ: function (record, options) {
2067 options = options || {wraparound: false};
2069 for(var section in this._proxies) {
2070 if (!this._proxies.hasOwnProperty(section)) {
2073 if ((result = this._proxies[section].succ(record, options))) {
2077 var index = this.indexOf(record);
2078 if (index === -1) { return null; }
2079 var next_index = index + 1;
2080 if (options.wraparound && (next_index === this.length)) {
2083 return this.at(next_index);
2085 pred: function (record, options) {
2086 options = options || {wraparound: false};
2089 for (var section in this._proxies) {
2090 if (!this._proxies.hasOwnProperty(section)) {
2093 if ((result = this._proxies[section].pred(record, options))) {
2098 var index = this.indexOf(record);
2099 if (index === -1) { return null; }
2100 var next_index = index - 1;
2101 if (options.wraparound && (next_index === -1)) {
2102 return this.at(this.length - 1);
2104 return this.at(next_index);
2107 Collection.include(Events);
2108 instance.web.list = {
2111 Collection: Collection
2114 * Registry for column objects used to format table cells (and some other tasks
2115 * e.g. aggregation computations).
2117 * Maps a field or button to a Column type via its ``$tag.$widget``,
2118 * ``$tag.$type`` or its ``$tag`` (alone).
2120 * This specific registry has a dedicated utility method ``for_`` taking a
2121 * field (from fields_get/fields_view_get.field) and a node (from a view) and
2122 * returning the right object *already instantiated from the data provided*.
2124 * @type {instance.web.Registry}
2126 instance.web.list.columns = new instance.web.Registry({
2127 'field': 'instance.web.list.Column',
2128 'field.boolean': 'instance.web.list.Boolean',
2129 'field.binary': 'instance.web.list.Binary',
2130 'field.char': 'instance.web.list.Char',
2131 'field.progressbar': 'instance.web.list.ProgressBar',
2132 'field.handle': 'instance.web.list.Handle',
2133 'button': 'instance.web.list.Button',
2134 'field.many2onebutton': 'instance.web.list.Many2OneButton',
2135 'field.many2many': 'instance.web.list.Many2Many'
2137 instance.web.list.columns.for_ = function (id, field, node) {
2138 var description = _.extend({tag: node.tag}, field, node.attrs);
2139 var tag = description.tag;
2140 var Type = this.get_any([
2141 tag + '.' + description.widget,
2142 tag + '.'+ description.type,
2145 return new Type(id, node.tag, description);
2148 instance.web.list.Column = instance.web.Class.extend({
2149 init: function (id, tag, attrs) {
2155 this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
2156 delete attrs.modifiers;
2157 _.extend(this, attrs);
2159 if (this.modifiers['tree_invisible']) {
2160 this.invisible = '1';
2161 } else { delete this.invisible; }
2163 modifiers_for: function (fields) {
2165 var domain_computer = instance.web.form.compute_domain;
2167 for (var attr in this.modifiers) {
2168 if (!this.modifiers.hasOwnProperty(attr)) { continue; }
2169 var modifier = this.modifiers[attr];
2170 out[attr] = _.isBoolean(modifier)
2172 : domain_computer(modifier, fields);
2177 to_aggregate: function () {
2178 if (this.type !== 'integer' && this.type !== 'float') {
2181 var aggregation_func = this['group_operator'] || 'sum';
2182 if (!(aggregation_func in this)) {
2185 var C = function (fn, label) {
2186 this['function'] = fn;
2190 return new C(aggregation_func, this[aggregation_func]);
2194 * @param row_data record whose values should be displayed in the cell
2195 * @param {Object} [options]
2196 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2197 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2198 * @param {String} [options.model] current record's model
2199 * @param {Number} [options.id] current record's id
2202 format: function (row_data, options) {
2203 options = options || {};
2205 if (options.process_modifiers !== false) {
2206 attrs = this.modifiers_for(row_data);
2208 if (attrs.invisible) { return ''; }
2210 if (!row_data[this.id]) {
2211 return options.value_if_empty === undefined
2213 : options.value_if_empty;
2215 return this._format(row_data, options);
2218 * Method to override in order to provide alternative HTML content for the
2219 * cell. Column._format will simply call ``instance.web.format_value`` and
2220 * escape the output.
2222 * The output of ``_format`` will *not* be escaped by ``format``, any
2223 * escaping *must be done* by ``format``.
2227 _format: function (row_data, options) {
2228 return _.escape(instance.web.format_value(
2229 row_data[this.id].value, this, options.value_if_empty));
2232 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2234 init: function (id, string) {
2235 this._super(id, '', {string: string});
2238 instance.web.list.Button = instance.web.list.Column.extend({
2240 * Return an actual ``<button>`` tag
2242 format: function (row_data, options) {
2243 options = options || {};
2245 if (options.process_modifiers !== false) {
2246 attrs = this.modifiers_for(row_data);
2248 if (attrs.invisible) { return ''; }
2250 return QWeb.render('ListView.row.button', {
2252 prefix: instance.session.prefix,
2253 disabled: attrs.readonly
2254 || isNaN(row_data.id.value)
2255 || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
2259 instance.web.list.Boolean = instance.web.list.Column.extend({
2261 * Return a potentially disabled checkbox input
2265 _format: function (row_data, options) {
2266 return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
2267 row_data[this.id].value ? 'checked="checked"' : '');
2270 instance.web.list.Binary = instance.web.list.Column.extend({
2272 * Return a link to the binary data as a file
2276 _format: function (row_data, options) {
2277 var text = _t("Download");
2278 var value = row_data[this.id].value;
2280 if (value && value.substr(0, 10).indexOf(' ') == -1) {
2281 download_url = "data:application/octet-stream;base64," + value;
2283 download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
2284 if (this.filename) {
2285 download_url += '&filename_field=' + this.filename;
2288 if (this.filename && row_data[this.filename]) {
2289 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2290 row_data[this.filename].value, {type: 'char'}));
2292 return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
2295 size: instance.web.binary_to_binsize(value),
2299 instance.web.list.Char = instance.web.list.Column.extend({
2302 * If password field, only display replacement characters (if value is
2305 _format: function (row_data, options) {
2306 var value = row_data[this.id].value;
2307 if (value && this.password === 'True') {
2308 return value.replace(/[\s\S]/g, _.escape(this.replacement));
2310 return this._super(row_data, options);
2313 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2315 * Return a formatted progress bar display
2319 _format: function (row_data, options) {
2321 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2322 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2326 instance.web.list.Handle = instance.web.list.Column.extend({
2328 this._super.apply(this, arguments);
2329 // Handle overrides the field to not be form-editable.
2330 this.modifiers.readonly = true;
2333 * Return styling hooks for a drag handle
2337 _format: function (row_data, options) {
2338 return '<div class="oe_list_handle">';
2341 instance.web.list.Many2OneButton = instance.web.list.Column.extend({
2342 _format: function (row_data, options) {
2343 this.has_value = !!row_data[this.id].value;
2344 this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
2345 this.string = this.has_value ? _t('View') : _t('Create');
2346 return QWeb.render('Many2OneButton.cell', {
2348 'prefix': instance.session.prefix,
2352 instance.web.list.Many2Many = instance.web.list.Column.extend({
2353 _format: function (row_data, options) {
2354 if (!_.isEmpty(row_data[this.id].value)) {
2355 // If value, use __display version for printing
2356 row_data[this.id] = row_data[this.id + '__display'];
2358 return this._super(row_data, options);
2362 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: