1 openerp.web.list = function (instance) {
2 var _t = instance.web._t,
3 _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
5 instance.web.views.add('list', 'instance.web.ListView');
6 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
8 display_name: _lt('List'),
10 // records can be selected one by one
12 // list rows can be deleted
14 // whether the column headers should be displayed
16 // display addition button, with that label
17 'addable': _lt("Create"),
18 // whether the list view can be sorted, note that once a view has been
19 // sorted it can not be reordered anymore
21 // whether the view rows can be reordered (via vertical drag & drop)
23 'action_buttons': true,
24 //whether the editable property of the view has to be disabled
25 'disable_editable_mode': false,
29 'click thead th.oe_sortable[data-id]': 'sort_by_column'
32 * Core class for list-type displays.
34 * As a view, needs a number of view-related parameters to be correctly
35 * instantiated, provides options and overridable methods for behavioral
38 * See constructor parameters and method documentations for information on
39 * the default behaviors and possible options for the list view.
41 * @constructs instance.web.ListView
42 * @extends instance.web.View
44 * @param parent parent object
45 * @param {instance.web.DataSet} dataset the dataset the view should work with
46 * @param {String} view_id the listview's identifier, if any
47 * @param {Object} options A set of options used to configure the view
48 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
49 * @param {Boolean} [options.header=true] should the list's header be displayed
50 * @param {Boolean} [options.deletable=true] are the list rows deletable
51 * @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.
52 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
53 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
55 init: function(parent, dataset, view_id, options) {
58 this.set_default_options(_.extend({}, this.defaults, options || {}));
59 this.dataset = dataset;
60 this.model = dataset.model;
61 this.view_id = view_id;
62 this.previous_colspan = null;
68 this.records = new Collection();
70 this.set_groups(new (this.options.GroupsType)(this));
72 if (this.dataset instanceof instance.web.DataSetStatic) {
73 this.groups.datagroup = new StaticDataGroup(this.dataset);
75 this.groups.datagroup = new DataGroup(
78 dataset.get_context());
79 this.groups.datagroup.sort = this.dataset._sort;
83 this.records.bind('change', function (event, record, key) {
84 if (!_(self.aggregate_columns).chain()
85 .pluck('name').contains(key).value()) {
88 self.compute_aggregates();
94 view_loading: function(r) {
95 return this.load_list(r);
97 set_default_options: function (options) {
99 _.defaults(this.options, {
100 GroupsType: instance.web.ListView.Groups,
101 ListType: instance.web.ListView.List
106 * Retrieves the view's number of records per page (|| section)
108 * options > defaults > parent.action.limit > indefinite
110 * @returns {Number|null}
113 if (this._limit === undefined) {
114 this._limit = (this.options.limit
115 || this.defaults.limit
116 || (this.getParent().action || {}).limit
122 * Set a custom Group construct as the root of the List View.
124 * @param {instance.web.ListView.Groups} groups
126 set_groups: function (groups) {
129 $(this.groups).unbind("selected deleted action row_link");
133 this.groups = groups;
134 $(this.groups).bind({
135 'selected': function (e, ids, records) {
136 self.do_select(ids, records);
138 'deleted': function (e, ids) {
141 'action': function (e, action_name, id, callback) {
142 self.do_button_action(action_name, id, callback);
144 'row_link': function (e, id, dataset, view) {
145 self.do_activate_record(dataset.index, id, dataset, view);
150 * View startup method, the default behavior is to set the ``oe_list``
151 * class on its root element and to perform an RPC load call.
153 * @returns {$.Deferred} loading promise
156 this.$el.addClass('oe_list');
157 return this._super();
160 * Returns the style for the provided record in the current view (from the
161 * ``@colors`` and ``@fonts`` attributes)
163 * @param {Record} record record for the current row
164 * @returns {String} CSS style declaration
166 style_for: function (record) {
169 var context = _.extend({}, record.attributes, {
170 uid: this.session.uid,
171 current_date: new Date().toString('yyyy-MM-dd')
172 // TODO: time, datetime, relativedelta
176 for(var i=0, len=this.fonts.length; i<len; ++i) {
177 var pair = this.fonts[i],
179 expression = pair[1];
180 if (py.evaluate(expression, context).toJSON()) {
183 style += 'font-weight: bold;';
186 style += 'font-style: italic;';
189 style += 'text-decoration: underline;';
196 if (!this.colors) { return style; }
197 for(var i=0, len=this.colors.length; i<len; ++i) {
198 var pair = this.colors[i],
200 expression = pair[1];
201 if (py.evaluate(expression, context).toJSON()) {
202 return style += 'color: ' + color + ';';
204 // TODO: handle evaluation errors
209 * Called after loading the list view's description, sets up such things
210 * as the view table's columns, renders the table itself and hooks up the
211 * various table-level and row-level DOM events (action buttons, deletion
212 * buttons, selection of records, [New] button, selection of a given
215 * Sets up the following:
217 * * Processes arch and fields to generate a complete field descriptor for each field
218 * * Create the table itself and allocate visible columns
219 * * Hook in the top-level (header) [New|Add] and [Delete] button
220 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
221 * * Sets up event handlers for action buttons and per-row deletion button
222 * * Hooks global callback for clicking on a row
223 * * Sets up its sidebar, if any
225 * @param {Object} data wrapped fields_view_get result
226 * @param {Object} data.fields_view fields_view_get result (processed)
227 * @param {Object} data.fields_view.fields mapping of fields for the current model
228 * @param {Object} data.fields_view.arch current list view descriptor
229 * @param {Boolean} grouped Is the list view grouped
231 load_list: function(data) {
233 this.fields_view = data;
234 this.name = "" + this.fields_view.arch.attrs.string;
236 if (this.fields_view.arch.attrs.colors) {
237 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
239 .map(function(color_pair) {
240 var pair = color_pair.split(':'),
243 return [color, py.parse(py.tokenize(expr)), expr];
247 if (this.fields_view.arch.attrs.fonts) {
248 this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
249 .map(function(font_pair) {
250 var pair = font_pair.split(':'),
253 return [font, py.parse(py.tokenize(expr)), expr];
257 this.setup_columns(this.fields_view.fields, this.grouped);
259 this.$el.html(QWeb.render(this._template, this));
260 this.$el.addClass(this.fields_view.arch.attrs['class']);
264 this.$el.find('.oe_list_record_selector').click(function(){
265 self.$el.find('.oe_list_record_selector input').prop('checked',
266 self.$el.find('.oe_list_record_selector').prop('checked') || false);
267 var selection = self.groups.get_selection();
268 $(self.groups).trigger(
269 'selected', [selection.ids, selection.records]);
273 if (!this.$buttons) {
274 this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
275 if (this.options.$buttons) {
276 this.$buttons.appendTo(this.options.$buttons);
278 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
280 this.$buttons.find('.oe_list_add')
281 .click(this.proxy('do_add_record'))
282 .prop('disabled', this.grouped);
287 this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
288 if (this.options.$buttons) {
289 this.$pager.appendTo(this.options.$pager);
291 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
295 .on('click', 'a[data-pager-action]', function () {
297 var max_page = Math.floor(self.dataset.size() / self.limit());
298 switch ($this.data('pager-action')) {
300 self.page = 0; break;
302 self.page = max_page - 1;
305 self.page += 1; break;
307 self.page -= 1; break;
310 self.page = max_page;
311 } else if (self.page > max_page) {
314 self.reload_content();
315 }).find('.oe_list_pager_state')
316 .click(function (e) {
320 var $select = $('<select>')
321 .appendTo($this.empty())
322 .click(function (e) {e.stopPropagation();})
323 .append('<option value="80">80</option>' +
324 '<option value="200">200</option>' +
325 '<option value="500">500</option>' +
326 '<option value="2000">2000</option>' +
327 '<option value="NaN">' + _t("Unlimited") + '</option>')
328 .change(function () {
329 var val = parseInt($select.val(), 10);
330 self._limit = (isNaN(val) ? null : val);
332 self.reload_content();
334 $(this).trigger('change');
336 .val(self._limit || 'NaN');
341 if (!this.sidebar && this.options.$sidebar) {
342 this.sidebar = new instance.web.Sidebar(this);
343 this.sidebar.appendTo(this.options.$sidebar);
344 this.sidebar.add_items('other', _.compact([
345 { label: _t("Export"), callback: this.on_sidebar_export },
346 self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
348 this.sidebar.add_toolbar(this.fields_view.toolbar);
349 this.sidebar.$el.hide();
352 if(this.dataset._sort.length){
353 if(this.dataset._sort[0].indexOf('-') == -1){
354 this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
356 this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
359 this.trigger('list_view_loaded', data, this.grouped);
361 sort_by_column: function (e) {
363 var $column = $(e.currentTarget);
364 var col_name = $column.data('id')
365 var field = this.fields_view.fields[col_name];
366 // test if the field is a function field with store=false, since it's impossible
367 // for the server to sort those fields we desactivate the feature
368 if (field && field.store === false) {
371 this.dataset.sort(col_name);
372 if($column.hasClass("sortdown") || $column.hasClass("sortup")) {
373 $column.toggleClass("sortup sortdown");
375 $column.addClass("sortdown");
377 $column.siblings('.oe_sortable').removeClass("sortup sortdown");
379 this.reload_content();
382 * Configures the ListView pager based on the provided dataset's information
384 * Horrifying side-effect: sets the dataset's data on this.dataset?
386 * @param {instance.web.DataSet} dataset
388 configure_pager: function (dataset) {
389 this.dataset.ids = dataset.ids;
391 if (dataset._length) {
392 this.dataset._length = dataset._length;
395 var total = dataset.size();
396 var limit = this.limit() || total;
400 this.$pager.css("display", "");
401 this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
404 var range_start = this.page * limit + 1;
405 var range_stop = range_start - 1 + limit;
406 if (range_stop > total) {
409 spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
412 this.$pager.find('.oe_list_pager_state').text(spager);
415 * Sets up the listview's columns: merges view and fields data, move
416 * grouped-by columns to the front of the columns list and make them all
419 * @param {Object} fields fields_view_get's fields section
420 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
422 setup_columns: function (fields, grouped) {
423 var registry = instance.web.list.columns;
424 this.columns.splice(0, this.columns.length);
425 this.columns.push.apply(this.columns,
426 _(this.fields_view.arch.children).map(function (field) {
427 var id = field.attrs.name;
428 return registry.for_(id, fields[id], field);
431 this.columns.unshift(
432 new instance.web.list.MetaColumn('_group', _t("Group")));
435 this.visible_columns = _.filter(this.columns, function (column) {
436 return column.invisible !== '1';
439 this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
442 * Used to handle a click on a table row, if no other handler caught the
445 * The default implementation asks the list view's view manager to switch
446 * to a different view (by calling
447 * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
448 * provided record index (within the current list view's dataset).
450 * If the index is null, ``switch_to_record`` asks for the creation of a
453 * @param {Number|void} index the record index (in the current dataset) to switch to
454 * @param {String} [view="page"] the view type to switch to
456 select_record:function (index, view) {
457 view = view || index == null ? 'form' : 'form';
458 this.dataset.index = index;
459 _.delay(_.bind(function () {
460 this.do_switch_view(view);
463 do_show: function () {
466 this.$buttons.show();
472 do_hide: function () {
474 this.sidebar.$el.hide();
477 this.$buttons.hide();
485 * Reloads the list view based on the current settings (dataset & al)
488 * @param {Boolean} [grouped] Should the list be displayed grouped
489 * @param {Object} [context] context to send the server while loading the view
491 reload_view: function (grouped, context, initial) {
492 return this.load_view(context);
495 * re-renders the content of the list view
497 * @returns {$.Deferred} promise to content reloading
499 reload_content: function () {
501 self.$el.find('.oe_list_record_selector').prop('checked', false);
502 this.records.reset();
503 var reloaded = $.Deferred();
504 this.$el.find('.oe_list_content').append(
505 this.groups.render(function () {
506 if (self.dataset.index == null) {
507 if (self.records.length) {
508 self.dataset.index = 0;
510 } else if (self.dataset.index >= self.records.length) {
511 self.dataset.index = 0;
514 self.compute_aggregates();
521 return reloaded.promise();
523 reload: function () {
524 return this.reload_content();
526 reload_record: function (record) {
528 return this.dataset.read_ids(
530 _.pluck(_(this.columns).filter(function (r) {
531 return r.tag === 'field';
533 ).done(function (records) {
534 var values = records[0];
536 self.records.remove(record);
539 _(_.keys(values)).each(function(key){
540 record.set(key, values[key], {silent: true});
542 record.trigger('change', record);
546 do_load_state: function(state, warm) {
548 if (state.page && this.page !== state.page) {
549 this.page = state.page;
553 if (_.isString(state.limit)) {
556 if (state.limit !== this._limit) {
557 this._limit = state.limit;
562 this.reload_content();
566 * Handler for the result of eval_domain_and_context, actually perform the
569 * @param {Object} results results of evaluating domain and process for a search
571 do_search: function (domain, context, group_by) {
573 this.groups.datagroup = new DataGroup(
574 this, this.model, domain, context, group_by);
575 this.groups.datagroup.sort = this.dataset._sort;
577 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
580 this.no_leaf = !!context['group_by_no_leaf'];
581 this.grouped = !!group_by;
583 return this.alive(this.load_view(context)).then(
584 this.proxy('reload_content'));
587 * Handles the signal to delete lines from the records list
589 * @param {Array} ids the ids of the records to delete
591 do_delete: function (ids) {
592 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
596 return $.when(this.dataset.unlink(ids)).done(function () {
597 _(ids).each(function (id) {
598 self.records.remove(self.records.get(id));
600 self.configure_pager(self.dataset);
601 self.compute_aggregates();
605 * Handles the signal indicating that a new record has been selected
607 * @param {Array} ids selected record ids
608 * @param {Array} records selected record values
610 do_select: function (ids, records) {
612 this.dataset.index = 0;
614 this.sidebar.$el.hide();
616 this.compute_aggregates();
620 this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
622 this.options.$sidebar.show();
623 this.sidebar.$el.show();
626 this.compute_aggregates(_(records).map(function (record) {
627 return {count: 1, values: record};
631 * Handles action button signals on a record
633 * @param {String} name action name
634 * @param {Object} id id of the record the action should be called on
635 * @param {Function} callback should be called after the action is executed, if non-null
637 do_button_action: function (name, id, callback) {
638 this.handle_button(name, id, callback);
641 * Base handling of buttons, can be called when overriding do_button_action
642 * in order to bypass parent overrides.
644 * The callback will be provided with the ``id`` as its parameter, in case
645 * handle_button's caller had to alter the ``id`` (or even create one)
646 * while not being ``callback``'s creator.
648 * This method should not be overridden.
650 * @param {String} name action name
651 * @param {Object} id id of the record the action should be called on
652 * @param {Function} callback should be called after the action is executed, if non-null
654 handle_button: function (name, id, callback) {
655 var action = _.detect(this.columns, function (field) {
656 return field.name === name;
658 if (!action) { return; }
659 if ('confirm' in action && !window.confirm(action.confirm)) {
663 var c = new instance.web.CompoundContext();
664 c.set_eval_context(_.extend({
667 active_model: this.dataset.model
668 }, this.records.get(id).toContext()));
669 if (action.context) {
670 c.add(action.context);
673 this.do_execute_action(
674 action, this.dataset, id, _.bind(callback, null, id));
677 * Handles the activation of a record (clicking on it)
679 * @param {Number} index index of the record in the dataset
680 * @param {Object} id identifier of the activated record
681 * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
683 do_activate_record: function (index, id, dataset, view) {
684 this.dataset.ids = dataset.ids;
685 this.select_record(index, view);
688 * Handles signal for the addition of a new record (can be a creation,
689 * can be the addition from a remote source, ...)
691 * The default implementation is to switch to a new record on the form view
693 do_add_record: function () {
694 this.select_record(null);
697 * Handles deletion of all selected lines
699 do_delete_selected: function () {
700 var ids = this.groups.get_selection().ids;
702 this.do_delete(this.groups.get_selection().ids);
704 this.do_warn(_t("Warning"), _t("You must select at least one record."));
708 * Computes the aggregates for the current list view, either on the
709 * records provided or on the records of the internal
710 * :js:class:`~instance.web.ListView.Group`, by calling
711 * :js:func:`~instance.web.ListView.group.get_records`.
713 * Then displays the aggregates in the table through
714 * :js:method:`~instance.web.ListView.display_aggregates`.
716 * @param {Array} [records]
718 compute_aggregates: function (records) {
719 var columns = _(this.aggregate_columns).filter(function (column) {
720 return column['function']; });
721 if (_.isEmpty(columns)) { return; }
723 if (_.isEmpty(records)) {
724 records = this.groups.get_records();
726 records = _(records).compact();
728 var count = 0, sums = {};
729 _(columns).each(function (column) {
730 switch (column['function']) {
732 sums[column.id] = -Infinity;
735 sums[column.id] = Infinity;
741 _(records).each(function (record) {
742 count += record.count || 1;
743 _(columns).each(function (column) {
744 var field = column.id,
745 value = record.values[field];
746 switch (column['function']) {
748 sums[field] += value;
751 sums[field] += record.count * value;
754 if (sums[field] > value) {
759 if (sums[field] < value) {
768 _(columns).each(function (column) {
769 var field = column.id;
770 switch (column['function']) {
772 aggregates[field] = {value: sums[field] / count};
775 aggregates[field] = {value: sums[field]};
779 this.display_aggregates(aggregates);
781 display_aggregates: function (aggregation) {
783 var $footer_cells = this.$el.find('.oe_list_footer');
784 _(this.aggregate_columns).each(function (column) {
785 if (!column['function']) {
789 $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
790 .html(column.format(aggregation, { process_modifiers: false }));
793 get_selected_ids: function() {
794 var ids = this.groups.get_selection().ids;
798 * Adds padding columns at the start or end of all table rows (including
801 * @param {Number} count number of columns to add
802 * @param {Object} options
803 * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
804 * @param {Object} [options.except] content row to not pad
806 pad_columns: function (count, options) {
807 options = options || {};
808 // padding for action/pager header
809 var $first_header = this.$el.find('thead tr:first th');
810 var colspan = $first_header.attr('colspan');
812 if (!this.previous_colspan) {
813 this.previous_colspan = colspan;
815 $first_header.attr('colspan', parseInt(colspan, 10) + count);
817 // Padding for column titles, footer and data rows
819 .find('.oe_list_header_columns, tr:not(thead tr)')
820 .not(options['except']);
821 var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
822 if (options.position === 'before') {
823 $rows.prepend(newcols);
825 $rows.append(newcols);
829 * Removes all padding columns of the table
831 unpad_columns: function () {
832 this.$el.find('.oe_list_padding').remove();
833 if (this.previous_colspan) {
835 .find('thead tr:first th')
836 .attr('colspan', this.previous_colspan);
837 this.previous_colspan = null;
840 no_result: function () {
841 this.$el.find('.oe_view_nocontent').remove();
842 if (this.groups.group_by
843 || !this.options.action
844 || !this.options.action.help) {
847 this.$el.find('table:first').hide();
849 $('<div class="oe_view_nocontent">').html(this.options.action.help)
851 var create_nocontent = this.$buttons;
852 this.$el.find('.oe_view_nocontent').click(function() {
853 create_nocontent.openerpBounce();
857 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
859 * List display for the ListView, handles basic DOM events and transforms
860 * them in the relevant higher-level events, to which the list view (or
861 * other consumers) can subscribe.
863 * Events on this object are registered via jQuery.
868 * Triggered when a row is selected (using check boxes), provides an
869 * array of ids of all the selected records.
871 * Triggered when deletion buttons are hit, provide an array of ids of
872 * all the records being marked for suppression.
874 * Triggered when an action button is clicked, provides two parameters:
876 * * The name of the action to execute (as a string)
877 * * The id of the record to execute the action on
879 * Triggered when a row of the table is clicked, provides the index (in
880 * the rows array) and id of the selected record to the handle function.
882 * @constructs instance.web.ListView.List
883 * @extends instance.web.Class
885 * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
887 init: function (group, opts) {
890 this.view = group.view;
891 this.session = this.view.session;
893 this.options = opts.options;
894 this.columns = opts.columns;
895 this.dataset = opts.dataset;
896 this.records = opts.records;
898 this.record_callbacks = {
899 'remove': function (event, record) {
900 var id = record.get('id');
901 self.dataset.remove_ids([id]);
902 var $row = self.$current.children('[data-id=' + id + ']');
903 var index = $row.data('index');
906 'reset': function () { return self.on_records_reset(); },
907 'change': function (event, record, attribute, value, old_value) {
909 if (attribute === 'id') {
911 throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
912 JSON.stringify(record.attributes) ));
914 self.dataset.add_ids([value], self.records.indexOf(record));
915 // Set id on new record
916 $row = self.$current.children('[data-id=false]');
918 $row = self.$current.children(
919 '[data-id=' + record.get('id') + ']');
921 $row.replaceWith(self.render_record(record));
923 'add': function (ev, records, record, index) {
924 var $new_row = $(self.render_record(record));
925 var id = record.get('id');
926 if (id) { self.dataset.add_ids([id], index); }
929 $new_row.prependTo(self.$current);
931 var previous_record = records.at(index-1),
932 $previous_sibling = self.$current.children(
933 '[data-id=' + previous_record.get('id') + ']');
934 $new_row.insertAfter($previous_sibling);
938 _(this.record_callbacks).each(function (callback, event) {
939 this.records.bind(event, callback);
942 this.$current = $('<tbody>')
943 .delegate('input[readonly=readonly]', 'click', function (e) {
945 Against all logic and sense, as of right now @readonly
946 apparently does nothing on checkbox and radio inputs, so
947 the trick of using @readonly to have, well, readonly
948 checkboxes (which still let clicks go through) does not
949 work out of the box. We *still* need to preventDefault()
950 on the event, otherwise the checkbox's state *will* toggle
955 .delegate('th.oe_list_record_selector', 'click', function (e) {
957 var selection = self.get_selection();
959 'selected', [selection.ids, selection.records]);
961 .delegate('td.oe_list_record_delete button', 'click', function (e) {
963 var $row = $(e.target).closest('tr');
964 $(self).trigger('deleted', [[self.row_id($row)]]);
966 .delegate('td.oe_list_field_cell button', 'click', function (e) {
968 var $target = $(e.currentTarget),
969 field = $target.closest('td').data('field'),
970 $row = $target.closest('tr'),
971 record_id = self.row_id($row);
973 if ($target.attr('disabled')) {
976 $target.attr('disabled', 'disabled');
978 // note: $.data converts data to number if it's composed only
979 // of digits, nice when storing actual numbers, not nice when
980 // storing strings composed only of digits. Force the action
981 // name to be a string
982 $(self).trigger('action', [field.toString(), record_id, function (id) {
983 $target.removeAttr('disabled');
984 return self.reload_record(self.records.get(id));
987 .delegate('a', 'click', function (e) {
990 .delegate('tr', 'click', function (e) {
991 var row_id = self.row_id(e.currentTarget);
994 if (!self.dataset.select_id(row_id)) {
995 throw new Error(_t("Could not find id in dataset"));
1001 row_clicked: function (e, view) {
1004 [this.dataset.ids[this.dataset.index],
1005 this.dataset, view]);
1007 render_cell: function (record, column) {
1009 if(column.type === 'reference') {
1010 value = record.get(column.id);
1012 // Ensure that value is in a reference "shape", otherwise we're
1013 // going to loop on performing name_get after we've resolved (and
1014 // set) a human-readable version. m2o does not have this issue
1015 // because the non-human-readable is just a number, where the
1016 // human-readable version is a pair
1017 if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
1018 // reference values are in the shape "$model,$id" (as a
1019 // string), we need to split and name_get this pair in order
1020 // to get a correctly displayable value in the field
1021 var model = ref_match[1],
1022 id = parseInt(ref_match[2], 10);
1023 new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
1024 if (!names.length) { return; }
1025 record.set(column.id, names[0][1]);
1028 } else if (column.type === 'many2one') {
1029 value = record.get(column.id);
1030 // m2o values are usually name_get formatted, [Number, String]
1031 // pairs, but in some cases only the id is provided. In these
1032 // cases, we need to perform a name_get call to fetch the actual
1033 // displayable value
1034 if (typeof value === 'number' || value instanceof Number) {
1035 // fetch the name, set it on the record (in the right field)
1036 // and let the various registered events handle refreshing the
1038 new instance.web.DataSet(this.view, column.relation)
1039 .name_get([value]).done(function (names) {
1040 if (!names.length) { return; }
1041 record.set(column.id, names[0]);
1044 } else if (column.type === 'many2many') {
1045 value = record.get(column.id);
1046 // non-resolved (string) m2m values are arrays
1047 if (value instanceof Array && !_.isEmpty(value)
1048 && !record.get(column.id + '__display')) {
1050 // they come in two shapes:
1051 if (value[0] instanceof Array) {
1052 var command = value[0];
1053 // 1. an array of m2m commands (usually (6, false, ids))
1054 if (command[0] !== 6) {
1055 throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
1059 // 2. an array of ids
1062 new instance.web.Model(column.relation)
1063 .call('name_get', [ids]).done(function (names) {
1064 // FIXME: nth horrible hack in this poor listview
1065 record.set(column.id + '__display',
1066 _(names).pluck(1).join(', '));
1067 record.set(column.id, ids);
1070 record.set(column.id, false);
1073 return column.format(record.toForm().data, {
1074 model: this.dataset.model,
1075 id: record.get('id')
1078 render: function () {
1079 this.$current.empty().append(
1080 QWeb.render('ListView.rows', _.extend({
1081 render_cell: function () {
1082 return self.render_cell.apply(self, arguments); }
1084 this.pad_table_to(4);
1086 pad_table_to: function (count) {
1087 if (this.records.length >= count ||
1088 _(this.columns).any(function(column) { return column.meta; })) {
1092 if (this.options.selectable) {
1093 cells.push('<th class="oe_list_record_selector"></td>');
1095 _(this.columns).each(function(column) {
1096 if (column.invisible === '1') {
1099 if (column.tag === 'button') {
1100 cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
1102 cells.push('<td title="' + column.string + '"> </td>');
1105 if (this.options.deletable) {
1106 cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1108 cells.unshift('<tr>');
1109 cells.push('</tr>');
1111 var row = cells.join('');
1113 .children('tr:not([data-id])').remove().end()
1114 .append(new Array(count - this.records.length + 1).join(row));
1117 * Gets the ids of all currently selected records, if any
1118 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1120 get_selection: function () {
1121 var result = {ids: [], records: []};
1122 if (!this.options.selectable) {
1125 var records = this.records;
1126 this.$current.find('th.oe_list_record_selector input:checked')
1127 .closest('tr').each(function () {
1128 var record = records.get($(this).data('id'));
1129 result.ids.push(record.get('id'));
1130 result.records.push(record.attributes);
1135 * Returns the identifier of the object displayed in the provided table
1138 * @param {Object} row the selected table row
1139 * @returns {Number|String} the identifier of the row's object
1141 row_id: function (row) {
1142 return $(row).data('id');
1145 * Death signal, cleans up list display
1147 on_records_reset: function () {
1148 _(this.record_callbacks).each(function (callback, event) {
1149 this.records.unbind(event, callback);
1151 if (!this.$current) { return; }
1152 this.$current.remove();
1154 get_records: function () {
1155 return this.records.map(function (record) {
1156 return {count: 1, values: record.attributes};
1160 * Reloads the provided record by re-reading its content from the server.
1162 * @param {Record} record
1163 * @returns {$.Deferred} promise to the finalization of the reloading
1165 reload_record: function (record) {
1166 return this.view.reload_record(record);
1169 * Renders a list record to HTML
1171 * @param {Record} record index of the record to render in ``this.rows``
1172 * @returns {String} QWeb rendering of the selected record
1174 render_record: function (record) {
1176 var index = this.records.indexOf(record);
1177 return QWeb.render('ListView.row', {
1178 columns: this.columns,
1179 options: this.options,
1181 row_parity: (index % 2 === 0) ? 'even' : 'odd',
1183 render_cell: function () {
1184 return self.render_cell.apply(self, arguments); }
1188 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1189 passthrough_events: 'action deleted row_link',
1191 * Grouped display for the ListView. Handles basic DOM events and interacts
1192 * with the :js:class:`~DataGroup` bound to it.
1194 * Provides events similar to those of
1195 * :js:class:`~instance.web.ListView.List`
1197 * @constructs instance.web.ListView.Groups
1198 * @extends instance.web.Class
1200 * @param {instance.web.ListView} view
1201 * @param {Object} [options]
1202 * @param {Collection} [options.records]
1203 * @param {Object} [options.options]
1204 * @param {Array} [options.columns]
1206 init: function (view, options) {
1207 options = options || {};
1209 this.records = options.records || view.records;
1210 this.options = options.options || view.options;
1211 this.columns = options.columns || view.columns;
1212 this.datagroup = null;
1220 this.records.bind('reset', function () {
1221 return self.on_records_reset(); });
1223 make_fragment: function () {
1224 return document.createDocumentFragment();
1227 * Returns a DOM node after which a new tbody can be inserted, so that it
1228 * follows the provided row.
1230 * Necessary to insert the result of a new group or list view within an
1231 * existing groups render, without losing track of the groups's own
1234 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1235 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1237 point_insertion: function (row) {
1239 var red_letter_tboday = $row.closest('tbody')[0];
1241 var $next_siblings = $row.nextAll();
1242 if ($next_siblings.length) {
1243 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1245 $root_kanal.append($next_siblings);
1246 this.elements.splice(
1247 _.indexOf(this.elements, red_letter_tboday),
1251 return red_letter_tboday;
1253 make_paginator: function () {
1255 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1256 .click(function (e) {
1257 e.stopPropagation();
1260 self.$row.closest('tbody').next()
1261 .replaceWith(self.render());
1263 var $next = $('<button type="button" data-pager-action="next">></button>')
1264 .click(function (e) {
1265 e.stopPropagation();
1268 self.$row.closest('tbody').next()
1269 .replaceWith(self.render());
1271 this.$row.children().last()
1272 .addClass('oe_list_group_pagination')
1274 .append('<span class="oe_list_pager_state"></span>')
1277 open: function (point_insertion) {
1278 this.render().insertAfter(point_insertion);
1280 var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1281 records_terminated = !this.datagroup.context['group_by_no_leaf'];
1282 if (no_subgroups && records_terminated) {
1283 this.make_paginator();
1286 close: function () {
1287 this.$row.children().last().empty();
1288 this.records.reset();
1291 * Prefixes ``$node`` with floated spaces in order to indent it relative
1292 * to its own left margin/baseline
1294 * @param {jQuery} $node jQuery object to indent
1295 * @param {Number} level current nesting level, >= 1
1296 * @returns {jQuery} the indentation node created
1298 indent: function ($node, level) {
1300 .css({'float': 'left', 'white-space': 'pre'})
1301 .text(new Array(level).join(' '))
1304 render_groups: function (datagroups) {
1306 var placeholder = this.make_fragment();
1307 _(datagroups).each(function (group) {
1308 if (self.children[group.value]) {
1309 self.records.proxy(group.value).reset();
1310 delete self.children[group.value];
1312 var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1313 records: self.records.proxy(group.value),
1314 options: self.options,
1315 columns: self.columns
1317 self.bind_child_events(child);
1318 child.datagroup = group;
1320 var $row = child.$row = $('<tr class="oe_group_header">');
1321 if (group.openable && group.length) {
1322 $row.click(function (e) {
1323 if (!$row.data('open')) {
1324 $row.data('open', true)
1325 .find('span.ui-icon')
1326 .removeClass('ui-icon-triangle-1-e')
1327 .addClass('ui-icon-triangle-1-s');
1328 child.open(self.point_insertion(e.currentTarget));
1330 $row.removeData('open')
1331 .find('span.ui-icon')
1332 .removeClass('ui-icon-triangle-1-s')
1333 .addClass('ui-icon-triangle-1-e');
1338 placeholder.appendChild($row[0]);
1340 var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1341 // Don't fill this if group_by_no_leaf but no group_by
1342 if (group.grouped_on) {
1344 row_data[group.grouped_on] = group;
1345 var group_column = _(self.columns).detect(function (column) {
1346 return column.id === group.grouped_on; });
1347 if (! group_column) {
1348 throw new Error(_.str.sprintf(
1349 _t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
1354 group_label = group_column.format(row_data, {
1355 value_if_empty: _t("Undefined"),
1356 process_modifiers: false
1359 group_label = _.str.escapeHTML(row_data[group_column.id].value);
1361 // group_label is html-clean (through format or explicit
1362 // escaping if format failed), can inject straight into HTML
1363 $group_column.html(_.str.sprintf(_t("%s (%d)"),
1364 group_label, group.length));
1366 if (group.length && group.openable) {
1367 // Make openable if not terminal group & group_by_no_leaf
1368 $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1370 // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1371 // wonky background position to ensure nothing is displayed
1372 // there but the rest of the behavior is ui-icon's
1373 $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1376 self.indent($group_column, group.level);
1378 if (self.options.selectable) {
1379 $row.append('<td>');
1381 _(self.columns).chain()
1382 .filter(function (column) { return column.invisible !== '1'; })
1383 .each(function (column) {
1385 // do not do anything
1386 } else if (column.id in group.aggregates) {
1388 r[column.id] = {value: group.aggregates[column.id]};
1389 $('<td class="oe_number">')
1390 .html(column.format(r, {process_modifiers: false}))
1393 $row.append('<td>');
1396 if (self.options.deletable) {
1397 $row.append('<td class="oe_list_group_pagination">');
1402 bind_child_events: function (child) {
1403 var $this = $(this),
1405 $(child).bind('selected', function (e) {
1406 // can have selections spanning multiple links
1407 var selection = self.get_selection();
1408 $this.trigger(e, [selection.ids, selection.records]);
1409 }).bind(this.passthrough_events, function (e) {
1410 // additional positional parameters are provided to trigger as an
1411 // Array, following the event type or event object, but are
1412 // provided to the .bind event handler as *args.
1413 // Convert our *args back into an Array in order to trigger them
1414 // on the group itself, so it can ultimately be forwarded wherever
1415 // it's supposed to go.
1416 var args = Array.prototype.slice.call(arguments, 1);
1417 $this.trigger.call($this, e, args);
1420 render_dataset: function (dataset) {
1422 list = new (this.view.options.ListType)(this, {
1423 options: this.options,
1424 columns: this.columns,
1426 records: this.records
1428 this.bind_child_events(list);
1430 var view = this.view,
1431 limit = view.limit(),
1432 d = new $.Deferred(),
1433 page = this.datagroup.openable ? this.page : view.page;
1435 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1436 var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1437 //TODO xmo: investigate why we need to put the setTimeout
1438 $.async_when().done(function() {
1439 dataset.read_slice(fields, options).done(function (records) {
1440 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1441 if (self.records.length) {
1442 self.records.reset(null, {silent: true});
1444 if (!self.datagroup.openable) {
1445 view.configure_pager(dataset);
1447 if (dataset.size() == records.length) {
1449 self.$row.find('td.oe_list_group_pagination').empty();
1451 var pages = Math.ceil(dataset.size() / limit);
1453 .find('.oe_list_pager_state')
1454 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1459 .find('button[data-pager-action=previous]')
1461 page === 0 ? 'hidden' : '')
1463 .find('button[data-pager-action=next]')
1465 page === pages - 1 ? 'hidden' : '');
1469 self.records.add(records, {silent: true});
1472 if (_.isEmpty(records)) {
1479 setup_resequence_rows: function (list, dataset) {
1480 // drag and drop enabled if list is not sorted and there is a
1481 // visible column with @widget=handle or "sequence" column in the view.
1482 if ((dataset.sort && dataset.sort())
1483 || !_(this.columns).any(function (column) {
1484 return column.widget === 'handle'
1485 || column.name === 'sequence'; })) {
1488 var sequence_field = _(this.columns).find(function (c) {
1489 return c.widget === 'handle';
1491 var seqname = sequence_field ? sequence_field.name : 'sequence';
1493 // ondrop, move relevant record & fix sequences
1494 list.$current.sortable({
1496 items: '> tr[data-id]',
1499 if (sequence_field) {
1500 list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1502 list.$current.sortable('option', {
1503 start: function (e, ui) {
1504 ui.placeholder.height(ui.item.height());
1506 stop: function (event, ui) {
1507 var to_move = list.records.get(ui.item.data('id')),
1508 target_id = ui.item.prev().data('id'),
1509 from_index = list.records.indexOf(to_move),
1510 target = list.records.get(target_id);
1511 if (list.records.at(from_index - 1) == target) {
1515 list.records.remove(to_move);
1516 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1517 list.records.add(to_move, { at: to });
1519 // resequencing time!
1520 var record, index = to,
1521 // if drag to 1st row (to = 0), start sequencing from 0
1522 // (exclusive lower bound)
1523 seq = to ? list.records.at(to - 1).get(seqname) : 0;
1524 while (++seq, record = list.records.at(index++)) {
1525 // write are independent from one another, so we can just
1526 // launch them all at the same time and we don't really
1527 // give a fig about when they're done
1528 // FIXME: breaks on o2ms (e.g. Accounting > Financial
1529 // Accounting > Taxes > Taxes, child tax accounts)
1530 // when synchronous (without setTimeout)
1531 (function (dataset, id, seq) {
1532 $.async_when().done(function () {
1534 attrs[seqname] = seq;
1535 dataset.write(id, attrs);
1537 }(dataset, record.get('id'), seq));
1538 record.set(seqname, seq);
1543 render: function (post_render) {
1545 var $el = $('<tbody>');
1546 this.elements = [$el[0]];
1548 this.datagroup.list(
1549 _(this.view.visible_columns).chain()
1550 .filter(function (column) { return column.tag === 'field' })
1551 .pluck('name').value(),
1554 self.render_groups(groups));
1555 if (post_render) { post_render(); }
1556 }, function (dataset) {
1557 self.render_dataset(dataset).done(function (list) {
1558 self.children[null] = list;
1560 [list.$current.replaceAll($el)[0]];
1561 self.setup_resequence_rows(list, dataset);
1562 if (post_render) { post_render(); }
1568 * Returns the ids of all selected records for this group, and the records
1571 get_selection: function () {
1572 var ids = [], records = [];
1575 .each(function (child) {
1576 var selection = child.get_selection();
1577 ids.push.apply(ids, selection.ids);
1578 records.push.apply(records, selection.records);
1581 return {ids: ids, records: records};
1583 on_records_reset: function () {
1585 $(this.elements).remove();
1587 get_records: function () {
1588 if (_(this.children).isEmpty()) {
1589 if (!this.datagroup.length) {
1593 count: this.datagroup.length,
1594 values: this.datagroup.aggregates
1597 return _(this.children).chain()
1598 .map(function (child) {
1599 return child.get_records();
1600 }).flatten().value();
1604 var DataGroup = instance.web.Class.extend({
1605 init: function(parent, model, domain, context, group_by, level) {
1606 this.model = new instance.web.Model(model, context, domain);
1607 this.group_by = group_by;
1608 this.context = context;
1609 this.domain = domain;
1611 this.level = level || 0;
1613 list: function (fields, ifGroups, ifRecords) {
1615 var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
1616 $.when(query).done(function (querygroups) {
1619 var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
1620 ds._sort = self.sort;
1625 var child_datagroups = _(querygroups).map(function (group) {
1626 var child_context = _.extend(
1627 {}, self.model.context(), group.model.context());
1628 var child_dg = new DataGroup(
1629 self, self.model.name, group.model.domain(),
1630 child_context, group.model._context.group_by,
1632 child_dg.sort = self.sort;
1633 // copy querygroup properties
1634 child_dg.__context = child_context;
1635 child_dg.__domain = group.model.domain();
1636 child_dg.folded = group.get('folded');
1637 child_dg.grouped_on = group.get('grouped_on');
1638 child_dg.length = group.get('length');
1639 child_dg.value = group.get('value');
1640 child_dg.openable = group.get('has_children');
1641 child_dg.aggregates = group.get('aggregates');
1644 ifGroups(child_datagroups);
1648 var StaticDataGroup = DataGroup.extend({
1649 init: function (dataset) {
1650 this.dataset = dataset;
1652 list: function (fields, ifGroups, ifRecords) {
1653 ifRecords(this.dataset);
1660 var Events = /** @lends Events# */{
1662 * @param {String} event event to listen to on the current object, null for all events
1663 * @param {Function} handler event handler to bind to the relevant event
1666 bind: function (event, handler) {
1667 var calls = this['_callbacks'] || (this._callbacks = {});
1669 if (event in calls) {
1670 calls[event].push(handler);
1672 calls[event] = [handler];
1677 * @param {String} event event to unbind on the current object
1678 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1681 unbind: function (event, handler) {
1682 var calls = this._callbacks || {};
1683 if (!(event in calls)) { return this; }
1685 delete calls[event];
1687 var handlers = calls[event];
1689 _(handlers).indexOf(handler),
1695 * @param {String} event
1698 trigger: function (event) {
1700 if (!(calls = this._callbacks)) { return this; }
1701 var callbacks = (calls[event] || []).concat(calls[null] || []);
1702 for(var i=0, length=callbacks.length; i<length; ++i) {
1703 callbacks[i].apply(this, arguments);
1708 var Record = instance.web.Class.extend(/** @lends Record# */{
1710 * @constructs Record
1711 * @extends instance.web.Class
1714 * @param {Object} [data]
1716 init: function (data) {
1717 this.attributes = data || {};
1720 * @param {String} key
1723 get: function (key) {
1724 return this.attributes[key];
1729 * @param {Object} [options]
1730 * @param {Boolean} [options.silent=false]
1733 set: function (key, value, options) {
1734 options = options || {};
1735 var old_value = this.attributes[key];
1736 if (old_value === value) {
1739 this.attributes[key] = value;
1740 if (!options.silent) {
1741 this.trigger('change:' + key, this, value, old_value);
1742 this.trigger('change', this, key, value, old_value);
1747 * Converts the current record to the format expected by form views:
1749 * .. code-block:: javascript
1758 * @returns {Object} record displayable in a form view
1760 toForm: function () {
1761 var form_data = {}, attrs = this.attributes;
1762 for(var k in attrs) {
1763 form_data[k] = {value: attrs[k]};
1766 return {data: form_data};
1769 * Converts the current record to a format expected by context evaluations
1770 * (identical to record.attributes, except m2o fields are their integer
1771 * value rather than a pair)
1773 toContext: function () {
1774 var output = {}, attrs = this.attributes;
1775 for(var k in attrs) {
1777 if (typeof val !== 'object') {
1779 } else if (val instanceof Array) {
1782 throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
1788 Record.include(Events);
1789 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1791 * Smarter collections, with events, very strongly inspired by Backbone's.
1793 * Using a "dumb" array of records makes synchronization between the
1796 * @constructs Collection
1797 * @extends instance.web.Class
1800 * @param {Array} [records] records to initialize the collection with
1801 * @param {Object} [options]
1803 init: function (records, options) {
1804 options = options || {};
1805 _.bindAll(this, '_onRecordEvent');
1810 this._key = options.key;
1811 this._parent = options.parent;
1818 * @param {Object|Array} record
1819 * @param {Object} [options]
1820 * @param {Number} [options.at]
1821 * @param {Boolean} [options.silent=false]
1824 add: function (record, options) {
1825 options = options || {};
1826 var records = record instanceof Array ? record : [record];
1828 for(var i=0, length=records.length; i<length; ++i) {
1829 var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1830 instance_.bind(null, this._onRecordEvent);
1831 this._byId[instance_.get('id')] = instance_;
1832 if (options.at == undefined) {
1833 this.records.push(instance_);
1834 if (!options.silent) {
1835 this.trigger('add', this, instance_, this.records.length-1);
1838 var insertion_index = options.at + i;
1839 this.records.splice(insertion_index, 0, instance_);
1840 if (!options.silent) {
1841 this.trigger('add', this, instance_, insertion_index);
1850 * Get a record by its index in the collection, can also take a group if
1851 * the collection is not degenerate
1853 * @param {Number} index
1854 * @param {String} [group]
1855 * @returns {Record|undefined}
1857 at: function (index, group) {
1859 var groups = group.split('.');
1860 return this._proxies[groups[0]].at(index, groups.join('.'));
1862 return this.records[index];
1865 * Get a record by its database id
1867 * @param {Number} id
1868 * @returns {Record|undefined}
1870 get: function (id) {
1871 if (!_(this._proxies).isEmpty()) {
1873 _(this._proxies).detect(function (proxy) {
1874 return record = proxy.get(id);
1878 return this._byId[id];
1881 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1882 * the subtree's group
1884 * @param {String} section group path section
1885 * @returns {Collection}
1887 proxy: function (section) {
1888 return this._proxies[section] = new Collection(null, {
1891 }).bind(null, this._onRecordEvent);
1894 * @param {Array} [records]
1897 reset: function (records, options) {
1898 options = options || {};
1899 _(this._proxies).each(function (proxy) {
1903 _(this.records).invoke('unbind', null, this._onRecordEvent);
1910 if (!options.silent) {
1911 this.trigger('reset', this);
1916 * Removes the provided record from the collection
1918 * @param {Record} record
1921 remove: function (record) {
1922 var index = this.indexOf(record);
1924 _(this._proxies).each(function (proxy) {
1925 proxy.remove(record);
1930 record.unbind(null, this._onRecordEvent);
1931 this.records.splice(index, 1);
1932 delete this._byId[record.get('id')];
1934 this.trigger('remove', record, this);
1938 _onRecordEvent: function (event) {
1940 // don't propagate reset events
1941 case 'reset': return;
1943 var record = arguments[1];
1944 var new_value = arguments[2];
1945 var old_value = arguments[3];
1946 // [change:id, record, new_value, old_value]
1947 if (this._byId[old_value] === record) {
1948 delete this._byId[old_value];
1949 this._byId[new_value] = record;
1953 this.trigger.apply(this, arguments);
1956 // underscore-type methods
1957 find: function (callback) {
1959 for(var section in this._proxies) {
1960 if (!this._proxies.hasOwnProperty(section)) {
1963 if ((record = this._proxies[section].find(callback))) {
1967 for(var i=0; i<this.length; ++i) {
1968 record = this.records[i];
1969 if (callback(record)) {
1974 each: function (callback) {
1975 for(var section in this._proxies) {
1976 if (this._proxies.hasOwnProperty(section)) {
1977 this._proxies[section].each(callback);
1980 for(var i=0; i<this.length; ++i) {
1981 callback(this.records[i]);
1984 map: function (callback) {
1986 this.each(function (record) {
1987 results.push(callback(record));
1991 pluck: function (fieldname) {
1992 return this.map(function (record) {
1993 return record.get(fieldname);
1996 indexOf: function (record) {
1997 return _(this.records).indexOf(record);
1999 succ: function (record, options) {
2000 options = options || {wraparound: false};
2002 for(var section in this._proxies) {
2003 if (!this._proxies.hasOwnProperty(section)) {
2006 if ((result = this._proxies[section].succ(record, options))) {
2010 var index = this.indexOf(record);
2011 if (index === -1) { return null; }
2012 var next_index = index + 1;
2013 if (options.wraparound && (next_index === this.length)) {
2016 return this.at(next_index);
2018 pred: function (record, options) {
2019 options = options || {wraparound: false};
2022 for (var section in this._proxies) {
2023 if (!this._proxies.hasOwnProperty(section)) {
2026 if ((result = this._proxies[section].pred(record, options))) {
2031 var index = this.indexOf(record);
2032 if (index === -1) { return null; }
2033 var next_index = index - 1;
2034 if (options.wraparound && (next_index === -1)) {
2035 return this.at(this.length - 1);
2037 return this.at(next_index);
2040 Collection.include(Events);
2041 instance.web.list = {
2044 Collection: Collection
2047 * Registry for column objects used to format table cells (and some other tasks
2048 * e.g. aggregation computations).
2050 * Maps a field or button to a Column type via its ``$tag.$widget``,
2051 * ``$tag.$type`` or its ``$tag`` (alone).
2053 * This specific registry has a dedicated utility method ``for_`` taking a
2054 * field (from fields_get/fields_view_get.field) and a node (from a view) and
2055 * returning the right object *already instantiated from the data provided*.
2057 * @type {instance.web.Registry}
2059 instance.web.list.columns = new instance.web.Registry({
2060 'field': 'instance.web.list.Column',
2061 'field.boolean': 'instance.web.list.Boolean',
2062 'field.binary': 'instance.web.list.Binary',
2063 'field.progressbar': 'instance.web.list.ProgressBar',
2064 'field.handle': 'instance.web.list.Handle',
2065 'button': 'instance.web.list.Button',
2066 'field.many2onebutton': 'instance.web.list.Many2OneButton',
2067 'field.many2many': 'instance.web.list.Many2Many'
2069 instance.web.list.columns.for_ = function (id, field, node) {
2070 var description = _.extend({tag: node.tag}, field, node.attrs);
2071 var tag = description.tag;
2072 var Type = this.get_any([
2073 tag + '.' + description.widget,
2074 tag + '.'+ description.type,
2077 return new Type(id, node.tag, description)
2080 instance.web.list.Column = instance.web.Class.extend({
2081 init: function (id, tag, attrs) {
2087 this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
2088 delete attrs.modifiers;
2089 _.extend(this, attrs);
2091 if (this.modifiers['tree_invisible']) {
2092 this.invisible = '1';
2093 } else { delete this.invisible; }
2095 modifiers_for: function (fields) {
2097 var domain_computer = instance.web.form.compute_domain;
2099 for (var attr in this.modifiers) {
2100 if (!this.modifiers.hasOwnProperty(attr)) { continue; }
2101 var modifier = this.modifiers[attr];
2102 out[attr] = _.isBoolean(modifier)
2104 : domain_computer(modifier, fields);
2109 to_aggregate: function () {
2110 if (this.type !== 'integer' && this.type !== 'float') {
2113 var aggregation_func = this['group_operator'] || 'sum';
2114 if (!(aggregation_func in this)) {
2117 var C = function (fn, label) {
2118 this['function'] = fn;
2122 return new C(aggregation_func, this[aggregation_func]);
2126 * @param row_data record whose values should be displayed in the cell
2127 * @param {Object} [options]
2128 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2129 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2130 * @param {String} [options.model] current record's model
2131 * @param {Number} [options.id] current record's id
2134 format: function (row_data, options) {
2135 options = options || {};
2137 if (options.process_modifiers !== false) {
2138 attrs = this.modifiers_for(row_data);
2140 if (attrs.invisible) { return ''; }
2142 if (!row_data[this.id]) {
2143 return options.value_if_empty === undefined
2145 : options.value_if_empty;
2147 return this._format(row_data, options);
2150 * Method to override in order to provide alternative HTML content for the
2151 * cell. Column._format will simply call ``instance.web.format_value`` and
2152 * escape the output.
2154 * The output of ``_format`` will *not* be escaped by ``format``, any
2155 * escaping *must be done* by ``format``.
2159 _format: function (row_data, options) {
2160 return _.escape(instance.web.format_value(
2161 row_data[this.id].value, this, options.value_if_empty));
2164 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2166 init: function (id, string) {
2167 this._super(id, '', {string: string});
2170 instance.web.list.Button = instance.web.list.Column.extend({
2172 * Return an actual ``<button>`` tag
2174 format: function (row_data, options) {
2175 options = options || {};
2177 if (options.process_modifiers !== false) {
2178 attrs = this.modifiers_for(row_data);
2180 if (attrs.invisible) { return ''; }
2182 return QWeb.render('ListView.row.button', {
2184 prefix: instance.session.prefix,
2185 disabled: attrs.readonly
2186 || isNaN(row_data.id.value)
2187 || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
2191 instance.web.list.Boolean = instance.web.list.Column.extend({
2193 * Return a potentially disabled checkbox input
2197 _format: function (row_data, options) {
2198 return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
2199 row_data[this.id].value ? 'checked="checked"' : '');
2202 instance.web.list.Binary = instance.web.list.Column.extend({
2204 * Return a link to the binary data as a file
2208 _format: function (row_data, options) {
2209 var text = _t("Download");
2210 var value = row_data[this.id].value;
2212 if (value && value.substr(0, 10).indexOf(' ') == -1) {
2213 download_url = "data:application/octet-stream;base64," + value;
2215 download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
2216 if (this.filename) {
2217 download_url += '&filename_field=' + this.filename;
2220 if (this.filename && row_data[this.filename]) {
2221 text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2222 row_data[this.filename].value, {type: 'char'}));
2224 return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
2227 size: instance.web.binary_to_binsize(value),
2231 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2233 * Return a formatted progress bar display
2237 _format: function (row_data, options) {
2239 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2240 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2244 instance.web.list.Handle = instance.web.list.Column.extend({
2246 this._super.apply(this, arguments);
2247 // Handle overrides the field to not be form-editable.
2248 this.modifiers.readonly = true;
2251 * Return styling hooks for a drag handle
2255 _format: function (row_data, options) {
2256 return '<div class="oe_list_handle">';
2259 instance.web.list.Many2OneButton = instance.web.list.Column.extend({
2260 _format: function (row_data, options) {
2261 this.has_value = !!row_data[this.id].value;
2262 this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
2263 this.string = this.has_value ? _t('View') : _t('Create');
2264 return QWeb.render('Many2OneButton.cell', {
2266 'prefix': instance.session.prefix,
2270 instance.web.list.Many2Many = instance.web.list.Column.extend({
2271 _format: function (row_data, options) {
2272 if (!_.isEmpty(row_data[this.id].value)) {
2273 // If value, use __display version for printing
2274 row_data[this.id] = row_data[this.id + '__display'];
2276 return this._super(row_data, options);
2280 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: